text:
'use strict';

angular.module('memexLinkerApp')
.controller('SavedentitiesCtrl', function ($scope, $http, $q, socket, lodash, entityService, linkUtils, Crossfilter) {
  var _ = lodash;
  var uniqueFlatAndDefined = linkUtils.uniqueFlatAndDefined;
  var collectAdProperty = linkUtils.collectAdProperty;
  var collectAdProperty2 = linkUtils.collectAdProperty2;
  var _SEARCH_URL = '/api/v1/search';
  $scope.entities = []
  $scope.entities2 = []

  $scope.adIds = []
  $scope.temp_url=[]

  var sources = {
    1 : 'Backpage',
    2 : 'Craigslist',
    3 : 'Classivox',
    4 : 'MyProviderGuide',
    5 : 'NaughtyReviews',
    6 : 'RedBook',
    7 : 'CityVibe',
    8 : 'MassageTroll',
    9 : 'RedBookForum',
    10 : 'CityXGuide',
    11 : 'CityXGuideForum',
    12 : 'RubAds',
    13 : 'Anunico',
    14 : 'SipSap',
    15 : 'EscortsInCollege',
    16 : 'EscortPhoneList',
    17 : 'EroticMugshots',
    18 : 'EscortsAdsXXX',
    19 : 'EscortsinCA',
    20 : 'EscortsintheUS',
    21 : 'LiveEscortReviews',
    22 : 'MyProviderGuideForum',
    23 : 'USASexGuide',
    24 : 'EroticReview',
    25 : 'AdultSearch',
    26 : 'HappyMassage',
    27: 'UtopiaGuide',
    28 : 'MissingKids'
  };

  function _formatEntity(rawEntity) {
    var ads = rawEntity._source.base;
    var postTimes = _.map(ads, function(ad){
      return new Date(ad.posttime);
    });
    var lastPostTime = _.max(postTimes);
    var firstPostTime = _.min(postTimes);
    var ages = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'age')).sort();
    var rates60 = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'rate60')).sort();
    var websites=[];
    var sourcesid = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'sources_id'));
    for (var i = 0; i < sourcesid.length; i++) {
      websites = websites.concat(sources[sourcesid[i]]);
    }
    websites = _.filter(_.uniq(websites), function(element){
      return ! _.isUndefined(element);
    });
    var phones = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'phone'));
    var titles = linkUtils.collectAdProperty(ads, 'title');
    var texts = linkUtils.collectAdProperty(ads, 'text');
    var snippet1= "";
    var snippet2= "";
    var snippet3= "";
    var all_text = titles + texts;
    var names = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'name'));
    var cities = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'city'));
    for (var i = 0; i < cities.length; i++) {
      cities[i]=cities[i].substring(0,20);
    }
    var youtube = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'youtube'));
    var instagram = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'instagram'));
    var twitter = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'twitter'));
    var socialmedia = twitter + instagram + youtube;
    var ethnicity = linkUtils.uniqueFlatAndDefined(linkUtils.collectAdProperty(ads, 'ethnicity'));
    var imageUrls = _.uniq(lodash.flatten(
      _.map(ads, function(ad) {
        return ad.image_locations;
      }),
      true));
    imageUrls = _.filter(imageUrls, function(element){
      return ! _.isUndefined(element);
    });
    var faceImageUrls = _.uniq(lodash.flatten(
      _.map(ads, function(ad) {
        return ad.face_image_url;
      }),
      true
      ));
    faceImageUrls = _.filter(faceImageUrls, function(element){
      return ! _.isUndefined(element);
    });
    var entity = {
      id: rawEntity._id,
      phones: phones,
      names: names,
      nPosts: ads.length,
      firstPostTime: firstPostTime,
      lastPostTime: lastPostTime,
      websites: websites,
      cities: cities,
      ages: ages,
      rates60: rates60,
      imageUrls: imageUrls,
      nPics: imageUrls.length,
      faceImageUrls: faceImageUrls,
      nSuggestedByImage: 0,
      nSuggestedByPhone: 0,
      nSuggestedByText: 0,
      socialmedia: socialmedia,
      titles: titles,
      texts: texts,
      all_text: all_text
    };
    return entity;
  }

  $http.get('/api/annotations/search').then(function(response){

    var x=[];
    for (var i = 0; i < response.data.length; i++) {
      x[i] = response.data[i]._source.entityid;
    }
    x = _.uniq(x);
    x = _.filter(x, function(element){
      return ! _.isUndefined(element);
    });
    console.log(x);
    $scope.entities = [];

    for (var i = 0; i < x.length; i++) {
      $scope.adIds.push(x[i]);
      $scope.temp_url.push('http://localhost:9000/entitydetail/' + x[i]);

      $http.post(_SEARCH_URL, {query:x[i]}).then(function(response){
        var e = _.map(response.data.entities, function(e) {
          var entity = _formatEntity(e);
          console.log(entity);
          return entity;
        });
        console.log('adding entity...');
        console.log(e);
        $scope.entities.push(e);
        $scope.entities = _.flatten($scope.entities);
      });
    }
    // $scope.entities2 = y
    // console.log($scope.entities2)
  });

});


text:
const qs = require('qs');
const Mock = require('mockjs');
const config = require('../utils/config');
const { apiPrefix } = config;

let usersListData = Mock.mock({
  'data|300-400': [
    {
      id: '@id',
      name: '@name',
      nickName: '@last',
      phone: /^1[34578]\d{9}$/,
      'age|11-99': 1,
      address: '@county(true)',
      isMale: '@boolean',
      email: '@email',
      createTime: '@datetime',
      avatar () {
        return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
      },
    },
  ],
});

let database = usersListData.data;

const EnumRoleType = {
  ADMIN: 'admin',
  DEFAULT: 'guest',
  DEVELOPER: 'developer',
};

const userPermission = {
  DEFAULT: {
    visit: ['1', '2', '21', '7', '5', '51', '52', '53'],
    role: EnumRoleType.DEFAULT,
  },
  ADMIN: {
    role: EnumRoleType.ADMIN,
  },
  DEVELOPER: {
    role: EnumRoleType.DEVELOPER,
  },
};

const adminUsers = [
  {
    id: 0,
    username: 'admin',
    password: 'admin',
    permissions: userPermission.ADMIN,
  }, {
    id: 1,
    username: 'guest',
    password: 'guest',
    permissions: userPermission.DEFAULT,
  }, {
    id: 2,
    username: '吴彦祖',
    password: '123456',
    permissions: userPermission.DEVELOPER,
  },
];

const queryArray = (array, key, keyAlias = 'key') => {
  if (!(array instanceof Array)) {
    return null
  }
  let data;

  for (let item of array) {
    if (item[keyAlias] === key) {
      data = item;
      break
    }
  }

  if (data) {
    return data
  }
  return null
};

const NOTFOUND = {
  message: 'Not Found',
  documentation_url: 'http://localhost:8000/request',
};

module.exports = {

  [`POST ${apiPrefix}/user/login`] (req, res) {
    const { username, password } = req.body;
    const user = adminUsers.filter((item) => item.username === username);

    if (user.length > 0 && user[0].password === password) {
      const now = new Date();
      now.setDate(now.getDate() + 1);
      res.cookie('token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), {
        maxAge: 900000,
        httpOnly: true,
      });
      res.json({ success: true, message: 'Ok' })
    } else {
      res.status(400).end()
    }
  },

  [`GET ${apiPrefix}/user/logout`] (req, res) {
    res.clearCookie('token');
    res.status(200).end()
  },

  [`GET ${apiPrefix}/user`] (req, res) {
    const cookie = req.headers.cookie || '';
    const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' });
    const response = {};
    const user = {};
    if (!cookies.token) {
      res.status(200).send({ message: 'Not Login' });
      return
    }
    const token = JSON.parse(cookies.token);
    if (token) {
      response.success = token.deadline > new Date().getTime()
    }
    if (response.success) {
      const userItem = adminUsers.filter(_ => _.id === token.id);
      if (userItem.length > 0) {
        user.permissions = userItem[0].permissions;
        user.username = userItem[0].username;
        user.id = userItem[0].id
      }
    }
    response.user = user;
    res.json(response)
  },

  [`GET ${apiPrefix}/users`] (req, res) {
    const { query } = req;
    let { pageSize, page, ...other } = query;
    pageSize = pageSize || 10;
    page = page || 1;

    let newData = database;
    for (let key in other) {
      if ({}.hasOwnProperty.call(other, key)) {
        newData = newData.filter((item) => {
          if ({}.hasOwnProperty.call(item, key)) {
            if (key === 'address') {
              return other[key].every(iitem => item[key].indexOf(iitem) > -1)
            } else if (key === 'createTime') {
              const start = new Date(other[key][0]).getTime();
              const end = new Date(other[key][1]).getTime();
              const now = new Date(item[key]).getTime();
              if (start && end) {
                return now >= start && now <= end
              }
              return true
            }
            return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
          }
          return true
        })
      }
    }

    res.status(200).json({
      data: newData.slice((page - 1) * pageSize, page * pageSize),
      total: newData.length,
    })
  },

  [`DELETE ${apiPrefix}/users`] (req, res) {
    const { ids } = req.body;
    database = database.filter((item) => !ids.some(_ => _ === item.id));
    res.status(204).end()
  },

  [`POST ${apiPrefix}/user`] (req, res) {
    const newData = req.body;
    newData.createTime = Mock.mock('@now');
    newData.avatar = newData.avatar || Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', newData.nickName.substr(0, 1));
    newData.id = Mock.mock('@id');

    database.unshift(newData);

    res.status(200).end()
  },

  [`GET ${apiPrefix}/user/:id`] (req, res) {
    const { id } = req.params;
    const data = queryArray(database, id, 'id');
    if (data) {
      res.status(200).json(data)
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`DELETE ${apiPrefix}/user/:id`] (req, res) {
    const { id } = req.params;
    const data = queryArray(database, id, 'id');
    if (data) {
      database = database.filter((item) => item.id !== id);
      res.status(204).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`PATCH ${apiPrefix}/user/:id`] (req, res) {
    const { id } = req.params;
    const editItem = req.body;
    let isExist = false;

    database = database.map((item) => {
      if (item.id === id) {
        isExist = true;
        return Object.assign({}, item, editItem)
      }
      return item
    });

    if (isExist) {
      res.status(201).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },
};

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"io"
	"mime"
	"os"
	"path/filepath"
)

type Storage interface {
	Get(token string, filename string) (reader io.ReadCloser, contentType string, contentLength uint64, err error)
	Head(token string, filename string) (contentType string, contentLength uint64, err error)
	Put(token string, filename string, reader io.Reader, contentType string, contentLength uint64) error
	Del(token string, filename string) (contentType string, err error)
}

type LocalStorage struct {
	Storage
	basedir string
}

func NewLocalStorage(basedir string) (*LocalStorage, error) {
	return &LocalStorage{basedir: basedir}, nil
}

func (s *LocalStorage) Head(token string, filename string) (contentType string, contentLength uint64, err error) {
	path := filepath.Join(s.basedir, token, filename)

	var fi os.FileInfo
	if fi, err = os.Lstat(path); err != nil {
		return
	}

	contentLength = uint64(fi.Size())

	contentType = mime.TypeByExtension(filepath.Ext(filename))

	return
}

func (s *LocalStorage) Get(token string, filename string) (reader io.ReadCloser, contentType string, contentLength uint64, err error) {
	path := filepath.Join(s.basedir, token, filename)

	// content type , content length
	if reader, err = os.Open(path); err != nil {
		return
	}

	var fi os.FileInfo
	if fi, err = os.Lstat(path); err != nil {
		return
	}

	contentLength = uint64(fi.Size())

	contentType = mime.TypeByExtension(filepath.Ext(filename))

	return
}

func (s *LocalStorage) Del(token string, filename string) (contentType string, err error) {
	path := filepath.Join(s.basedir, token, filename)

	_, err = os.Stat(path)
	if err != nil {
		return
	}
	contentType = mime.TypeByExtension(filepath.Ext(filename))

	err = os.Remove(path)
	if err != nil {
		return
	}
	return
}

func (s *LocalStorage) Put(token string, filename string, reader io.Reader, contentType string, contentLength uint64) error {
	var f io.WriteCloser
	var err error

	path := filepath.Join(s.basedir, token)

	if err = os.Mkdir(path, 0700); err != nil && !os.IsExist(err) {
		return err
	}

	if f, err = os.OpenFile(filepath.Join(path, filename), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600); err != nil {
		fmt.Printf("%s", err)
		return err
	}

	defer f.Close()

	if _, err = io.Copy(f, reader); err != nil {
		return err
	}

	return nil
}


text:
<resources>
    <dimen name="large_half">240px</dimen>

    <dimen name="value">45sp</dimen>
    <dimen name="small_value">30sp</dimen>
    <dimen name="step_count">30sp</dimen>
    <dimen name="units">11sp</dimen>
    <dimen name="desired_pace">36sp</dimen>
    <dimen name="desired_pace_width">128sp</dimen>

    <dimen name="button">48sp</dimen>
    <dimen name="button_sign">24sp</dimen>

    <dimen name="margin">10px</dimen>
    <dimen name="padding">5px</dimen>
    <dimen name="row_spacing">10px</dimen>

</resources>


text:
<?php

namespace Beloop\Component\Course\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class LessonRepository.
 */
class LessonRepository extends EntityRepository
{
}


text:
cask "wavebox" do
  arch = Hardware::CPU.intel? ? "mac" : "macarm64"

  version "10.102.21.2"

  if Hardware::CPU.intel?
    sha256 "d2609980fba00e14daf43a4b1b9a3893c7f83eba0cd7b398f22a14ec3ce73f2b"
  else
    sha256 "af921811c717ae8bb3bffaccad3614c1409a7442edebb652a9e49589a8b45631"
  end

  url "https://download.wavebox.app/stable/#{arch}/Install%20Wavebox%20#{version}.dmg",
      verified: "download.wavebox.app/"
  name "Wavebox"
  desc "Web browser"
  homepage "https://wavebox.io/"

  livecheck do
    url "https://download.wavebox.app/latest/stable/mac"
    strategy :header_match
  end

  auto_updates true
  depends_on macos: ">= :sierra"

  app "Wavebox.app"

  uninstall quit: "io.wavebox.wavebox"

  zap trash: [
    "~/Library/Application Support/WaveboxApp",
    "~/Library/Caches/com.bookry.wavebox",
    "~/Library/Caches/WaveboxApp",
    "~/Library/Preferences/com.bookry.wavebox.plist",
    "~/Library/Saved Application State/com.bookry.wavebox.savedState",
  ]
end


text:
    Connecting to Glidera...

{{glidera.error}}

        <button class="outline dark-gray tiny round" ng-click="glidera.submitOauthCode(glidera.code)">Try again</button>


text:
path=`pwd`
replace="/docker/server-web"
replaceTo=""
apppath="${path/$replace/$replaceTo}"

# Remove container
docker rm -f mapbiomas-server-web

# build image
docker build -t terras/mapbiomas-server-web .

# run container
docker run -d -v $apppath:/var/www -p 80:80 --link mapbiomas-server-db:dbhost -h mapbiomas-server-web --name mapbiomas-server-web terras/mapbiomas-server-web ./start.sh

# GEE Auth
#docker exec -it mapbiomas-server-web earthengine authenticate

# Show IP
containerip=`docker inspect --format '{{.NetworkSettings.IPAddress}}' mapbiomas-server-web`
echo "mapbiomas-server-web IPAddress: $containerip"


text:
#include "../system.h"

// Material
Material::Material() {
	this->albedofn = "data/texture/def_albedo.png";
	this->normalfn = "data/texture/def_normal.png";
	this->specularfn = "data/texture/def_specular.png";
	this->emissivefn = "data/texture/def_emissive.png";
	this->alphaMaskfn = "data/texture/def_alphaMask.png";
}

void Material::init() {
	albedo.init(albedofn);
	normal.init(normalfn);
	specular.init(specularfn);
	emissive.init(emissivefn, false);
	alphaMask.init(alphaMaskfn, false);
}

void Material::bind() {
	albedo.bind(GL_TEXTURE0);
	normal.bind(GL_TEXTURE1);
	specular.bind(GL_TEXTURE2);
	emissive.bind(GL_TEXTURE3);
	alphaMask.bind(GL_TEXTURE4);
}

void Material::unbind() {
	alphaMask.unbind();
	emissive.unbind();
	specular.unbind();
	normal.unbind();
	albedo.unbind();
}

void Material::release() {
	alphaMask.release();
	emissive.release();
	specular.release();
	normal.release();
	albedo.release();
}

void Material::setAlbedoFilename(std::string fn) {
	this->albedofn = fn;
}

void Material::setNormalFilename(std::string fn) {
	this->normalfn = fn;
}

void Material::setSpecularFilename(std::string fn) {
	this->specularfn = fn;
}

void Material::setEmissiveFilename(std::string fn) {
	this->emissivefn = fn;
}

void Material::setAlphaMaskFilename(std::string fn) {
	this->alphaMaskfn = fn;
}


text:
import { RequireItResult } from './RsgRequireItResult';
import { MarkdownExample, Example } from './RsgExample';
import { LoaderComponent, ExpandMode, Component } from './RsgComponent';

export interface BaseSection {
	name?: string;
	slug?: string;
	ignore?: string | string[];
	description?: string;
	exampleMode?: ExpandMode;
	usageMode?: ExpandMode;
	href?: string;
	sectionDepth?: number;
	external?: boolean;
	expand?: boolean;
}

export interface ProcessedSection extends BaseSection {
	visibleName?: string;
	filepath?: string;
	externalLink?: boolean;
	href?: string;
}

/**
 * Section used on the client in javascript
 * It is the output of the function `client/utils/processSection`
 */
export interface Section extends ProcessedSection {
	content?: Example[] | string;
	components?: Component[];
	sections?: Section[];
}

/**
 * Item of the Table Of Contents used in
 * ComponentsList
 * TableOfContent
 * filterSectionByName
 */
export interface TOCItem extends ProcessedSection {
	heading?: boolean;
	shouldOpenInNewTab?: boolean;
	selected?: boolean;
	initialOpen?: boolean;
	forcedOpen?: boolean;
	content?: React.ReactNode;
	components?: TOCItem[];
	sections?: TOCItem[];
}

/**
 * Used in the config file and at the early stages of processing
 * in `schema/config.ts` this is the type that is used
 */
export interface ConfigSection extends BaseSection {
	components?: string | string[] | (() => string[]);
	sections?: ConfigSection[];
	content?: string;
}

/**
 * Type returned when sections are transformed to their webpack
 * loadable equivalents
 */
export interface LoaderSection extends BaseSection {
	slug?: string;
	content?: RequireItResult | MarkdownExample;
	components: LoaderComponent[];
	sections: LoaderSection[];
}


text:
using System.Data.Entity;
using Tweeter.Data;
using Tweeter.Data.Migrations;

namespace Tweeter.Mvc
{
    public class DatabaseConfig
    {
        public static void Initialize()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<TweeterAppDbContext, Configuration>());
        //    TweeterAppDbContext.Create().Database.Initialize(true);
        }
    }
}


text:
package com.blt.talk.service.jpa.entity;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;

/**
 * The persistent class for the IMGroupMessage_0 database table.
 *
 */
@MappedSuperclass
public abstract class IMGroupMessageEntity extends IMAbstractMessage {

    private static final long serialVersionUID = 1L;

    /**
     * 根据群组ID分表
     *
     * @param groupId
     * @return
     * @since 1.0
     */
    public static IMGroupMessageEntity getInstance(long groupId) {
        return new IMGroupMessage();
    }

    @Column(name = "group_id", nullable = false)
    private Long groupId;

    public Long getGroupId() {
        return this.groupId;
    }

    public void setGroupId(Long groupId) {
        this.groupId = groupId;
    }

}


text:
using System;
using System.Collections.Generic;
using DirectCanvas.Brushes;
using DirectCanvas.Helpers;
using DirectCanvas.Misc;
using DirectCanvas.Transforms;
using SlimDX;
using SlimDX.Direct2D;

namespace DirectCanvas.Shapes
{
    public abstract class Geometry : IDisposable
    {
        private readonly Direct2DRenderTarget m_renderTargetResourceOwner;
        private TransformedGeometry m_transformedGeometry;
        private Mesh m_mesh;

        internal Geometry(Direct2DRenderTarget renderTargetResourceOwner)
        {
            m_renderTargetResourceOwner = renderTargetResourceOwner;
        }

        public void Freeze()
        {
            if(m_mesh != null)
            {
                m_mesh.Dispose();
                m_mesh = null;
            }

            m_mesh = new Mesh(m_renderTargetResourceOwner.InternalRenderTarget);

            using(var tesselationSink = m_mesh.Open())
            {
                var geometry = GetInternalGeometry();
                SlimDX.Direct2D.Geometry.Tessellate(geometry, tesselationSink);
                tesselationSink.Close();
            }
        }

        public GeneralTransform Transform { get; set; }

        public RectangleF GetBounds()
        {
            var bounds = SlimDX.Direct2D.Geometry.GetBounds(GetCurrentGeometry());
            var ret = new RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height);
            return ret;
        }

        public RectangleF GetBoundsInverted()
        {
            var bounds = SlimDX.Direct2D.Geometry.GetBounds(GetCurrentGeometry(), Matrix3x2.Invert(GetCurrentTransform()));
            var ret = new RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height);
            return ret;
        }

        public RectangleF GetBoundsTransformed()
        {
            var bounds = SlimDX.Direct2D.Geometry.GetBounds(GetCurrentGeometry());
            var ret = new RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height);
            return ret;
        }

        private Matrix3x2 GetCurrentTransform()
        {
            if (Transform == null)
                return Matrix3x2.Identity;

            return Transform.GetTransform();
        }

        private SlimDX.Direct2D.Geometry GetCurrentGeometry()
        {
            if (m_transformedGeometry != null)
                return m_transformedGeometry;

            return GetInternalGeometry();
        }

        internal void Fill(DrawingLayer drawingLayer, Brushes.Brush brush)
        {
            var bounds = GetBoundsInverted();
            drawingLayer.PushState();

            BrushHelper.PrepareBrush(brush, drawingLayer, bounds, GetCurrentTransform(), Matrix3x2.Identity);

            if (m_transformedGeometry != null)
            {
                m_transformedGeometry.Dispose();
                m_transformedGeometry = null;
            }

            m_transformedGeometry = new TransformedGeometry(InternalRenderTargetResourceOwner.InternalRenderTarget.Factory,
                                                            GetInternalGeometry(),
                                                            GetCurrentTransform());

            if (m_mesh == null)
                drawingLayer.D2DRenderTarget.InternalRenderTarget.FillGeometry(m_transformedGeometry, brush.InternalBrush);
            else
            {
                drawingLayer.D2DRenderTarget.InternalRenderTarget.AntialiasMode = AntialiasMode.Aliased;
                drawingLayer.D2DRenderTarget.InternalRenderTarget.FillMesh(m_mesh, brush.InternalBrush);
            }

            drawingLayer.PopState();
        }

        internal void Draw(DrawingLayer drawingLayer, Brushes.Brush brush, float stroakWidth)
        {
            var bounds = GetBoundsInverted();
            drawingLayer.PushState();

            BrushHelper.PrepareBrush(brush, drawingLayer, bounds, GetCurrentTransform(), Matrix3x2.Identity);

            if (m_transformedGeometry != null)
            {
                m_transformedGeometry.Dispose();
                m_transformedGeometry = null;
            }

            m_transformedGeometry = new TransformedGeometry(InternalRenderTargetResourceOwner.InternalRenderTarget.Factory,
                                                            GetInternalGeometry(),
                                                            GetCurrentTransform());

            if (m_mesh == null)
                drawingLayer.D2DRenderTarget.InternalRenderTarget.DrawGeometry(m_transformedGeometry, brush.InternalBrush, stroakWidth);
            else
            {
                drawingLayer.D2DRenderTarget.InternalRenderTarget.AntialiasMode = AntialiasMode.Aliased;
                drawingLayer.D2DRenderTarget.InternalRenderTarget.FillMesh(m_mesh, brush.InternalBrush);
            }

            drawingLayer.PopState();
        }

        internal Direct2DRenderTarget InternalRenderTargetResourceOwner
        {
            get { return m_renderTargetResourceOwner; }
        }

        protected abstract SlimDX.Direct2D.Geometry GetInternalGeometry();

        public virtual void Dispose()
        {
            if(m_mesh != null)
            {
                m_mesh.Dispose();
                m_mesh = null;
            }

            if(m_transformedGeometry != null)
            {
                m_transformedGeometry.Dispose();
                m_transformedGeometry = null;
            }
        }
    }
}


text:
Check out the docs [on hackage](http://hackage.haskell.org/package/directory-tree),
and install with a:

    cabal install directory-tree

or if you're on debian it looks like there are packages available:

    $ apt-get install libghc-directory-tree-dev


text:
'use strict'

module.exports = function (options) {
  return {

    apps: {},

    // POST /apps
    createApp: function (app, callback) {
      if (this.apps[app.id]) {
        return callback(new Error('App ' + app.id + ' already exists.'))
      }
      this.apps[app.id] = {
        id: app.id,
        created: app.created,
        handlers: {},
        logs: []
      }
      callback(null)
    },

    // GET /apps
    listApps: function (callback) {
      var result = []

      Object.keys(this.apps).forEach(function (appKey) {
        var appValue = this.apps[appKey]
        result.unshift({
          id: appValue.id,
          created: appValue.created
        })
      }, this)

      callback(null, result)
    },

    // GET /apps/:app_id
    retrieveApp: function (appId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      callback(null, {
        id: app.id,
        created: app.created
      })
    },

    // DELETE /apps/:app_id
    deleteApp: function (appId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'))
      }
      delete this.apps[appId]
      callback(null)
    },

    // This isn't exposed through the API.
    createHandler: function (appId, handler, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'))
      }
      if (app.handlers[handler.id]) {
        return callback(new Error('Handler ' + handler.id + ' aleady exists in app ' + app.id + '.'))
      }
      app.handlers[handler.id] = handler
      callback(null)
    },

    // This isn't exposed through the API.
    listHandlers: function (appId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      callback(null, app.handlers)
    },

    // This isn't exposed through the API.
    retrieveHandler: function (appId, handlerId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      var handler = app.handlers[handlerId]
      if (!handler) {
        return callback(new Error('Handler ' + handlerId + ' does not exist in app' + app.id + '.'), null)
      }
      callback(null, handler)
    },

    // * /apps/:app_id/test/*
    createLog: function (appId, handlerId, log, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      var handler = app.handlers[handlerId]
      if (!handler) {
        return callback(new Error('Handler ' + handlerId + ' does not exist in app' + app.id + '.'), null)
      }
      app.logs.push(log)
      handler.totalMatches = (handler.totalMatches || 0) + 1
      callback(null)
    },

    // DELETE /apps/:app_id/logs
    deleteLogs: function (appId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      app.logs = []
      callback(null)
    },

    // GET /apps/:app_id/logs
    listLogs: function (appId, callback) {
      var app = this.apps[appId]
      if (!app) {
        return callback(new Error('App ' + appId + ' does not exist.'), null)
      }
      callback(null, app.logs)
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Boletus immutabilis var. immutabilis

### Remarks
null


text:
package org.vitrivr.cineast.core.data;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import georegression.struct.point.Point2D_F32;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Skeleton {

  public static final SkeletonPointName[][] BONES = {
      {SkeletonPointName.LEFT_ANKLE, SkeletonPointName.LEFT_KNEE},
      {SkeletonPointName.LEFT_KNEE, SkeletonPointName.LEFT_HIP},
      {SkeletonPointName.RIGHT_ANKLE, SkeletonPointName.RIGHT_KNEE},
      {SkeletonPointName.RIGHT_KNEE, SkeletonPointName.RIGHT_HIP},
      {SkeletonPointName.LEFT_HIP, SkeletonPointName.RIGHT_HIP},
      {SkeletonPointName.LEFT_SHOULDER, SkeletonPointName.LEFT_HIP},
      {SkeletonPointName.RIGHT_SHOULDER, SkeletonPointName.RIGHT_HIP},
      {SkeletonPointName.LEFT_SHOULDER, SkeletonPointName.RIGHT_SHOULDER},
      {SkeletonPointName.LEFT_SHOULDER, SkeletonPointName.LEFT_ELBOW},
      {SkeletonPointName.RIGHT_SHOULDER, SkeletonPointName.RIGHT_ELBOW},
      {SkeletonPointName.LEFT_ELBOW, SkeletonPointName.LEFT_WRIST},
      {SkeletonPointName.RIGHT_ELBOW, SkeletonPointName.RIGHT_WRIST},
      {SkeletonPointName.LEFT_EYE, SkeletonPointName.RIGHT_EYE},
      {SkeletonPointName.NOSE, SkeletonPointName.LEFT_EYE},
      {SkeletonPointName.NOSE, SkeletonPointName.RIGHT_EYE},
      {SkeletonPointName.LEFT_EYE, SkeletonPointName.LEFT_EAR},
      {SkeletonPointName.RIGHT_EYE, SkeletonPointName.RIGHT_EAR},
      {SkeletonPointName.NOSE, SkeletonPointName.LEFT_SHOULDER},
      {SkeletonPointName.NOSE, SkeletonPointName.RIGHT_SHOULDER}
  };
  private static final int POINT_COUNT = 17;
  private final Point2D_F32[] points = new Point2D_F32[POINT_COUNT];
  private final float[] weights = new float[POINT_COUNT];
  @JsonCreator
  public Skeleton(
      @JsonProperty("coordinates") float[] coordinates,
      @JsonProperty("weights") float[] weights
  ) {

    if (coordinates == null || coordinates.length < 2 * POINT_COUNT || weights == null || weights.length < POINT_COUNT) {
      throw new IllegalArgumentException();
    }

    for (int i = 0; i < POINT_COUNT; ++i) {
      this.weights[i] = weights[i];
      this.points[i] = new Point2D_F32(coordinates[2 * i], coordinates[2 * i + 1]);
    }

  }

  public Skeleton() {
    //empty skeleton
    for (int i = 0; i < POINT_COUNT; ++i) {
      this.points[i] = new Point2D_F32(0f, 0f);
    }
  }

  public List<Point2D_F32> getPoints() {
    ArrayList<Point2D_F32> _return = new ArrayList<>(POINT_COUNT);
    for (int i = 0; i < POINT_COUNT; ++i) {
      _return.add(this.points[i].copy());
    }
    return _return;
  }

  public List<Point2D_F32> getPointsScaled(float scaleX, float scaleY) {
    ArrayList<Point2D_F32> _return = new ArrayList<>(POINT_COUNT);
    for (int i = 0; i < POINT_COUNT; ++i) {
      _return.add(new Point2D_F32(points[i].x * scaleX, points[i].y * scaleY));
    }
    return _return;
  }

  public Point2D_F32 getPoint(SkeletonPointName name) {
    return this.points[name.ordinal()].copy();
  }

  public float getWeight(SkeletonPointName name) {
    return this.weights[name.ordinal()];
  }

  public void setPointWeighted(SkeletonPointName pointName, float weight, Point2D_F32 point) {
    this.weights[pointName.ordinal()] = weight;
    this.points[pointName.ordinal()] = point;
  }

  public enum SkeletonPointName {
    NOSE,
    LEFT_EYE,
    RIGHT_EYE,
    LEFT_EAR,
    RIGHT_EAR,
    LEFT_SHOULDER,
    RIGHT_SHOULDER,
    LEFT_ELBOW,
    RIGHT_ELBOW,
    LEFT_WRIST,
    RIGHT_WRIST,
    LEFT_HIP,
    RIGHT_HIP,
    LEFT_KNEE,
    RIGHT_KNEE,
    LEFT_ANKLE,
    RIGHT_ANKLE
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Skeleton skeleton = (Skeleton) o;
    return Arrays.equals(points, skeleton.points) && Arrays.equals(weights, skeleton.weights);
  }

  @Override
  public int hashCode() {
    int result = Arrays.hashCode(points);
    result = 31 * result + Arrays.hashCode(weights);
    return result;
  }
}


text:
using NFugue.Extensions;
using NFugue.Parsing;
using NFugue.Providers;
using NFugue.Theory;
using Sanford.Multimedia.Midi;
using System;
using System.Collections.Generic;
using System.Text;

namespace NFugue.Midi
{
    public class MidiParser : Parser
    {
        private List<Dictionary<byte, TempNote>> noteCache;
        private int resolutionTicksPerBeat = MidiDefaults.DefaultResolutionTicksPerBeat;
        private int tempoBPM = MidiDefaults.DefaultTempoBeatsPerMinute;
        private int currentChannel = -1;
        private double[] currentTimeInBeats;
        private double[] expectedTimeInBeats;

        public void Parse(Sequence sequence)
        {
            Start();
            foreach (var track in sequence)
            {
                foreach (var midiEvent in track.Iterator())
                {
                    ParseEvent(midiEvent);
                }
            }
            Stop();
        }

        public void Start()
        {
            OnBeforeParsingStarted();
            InitNoteCache();
            resolutionTicksPerBeat = MidiDefaults.DefaultResolutionTicksPerBeat;
        }

        public void Stop()
        {
            OnAfterParsingFinished();
        }

        public event EventHandler<MidiEventArgs> HandledMidiEvent;
        public event EventHandler<MidiEventArgs> UnhandledMidiEvent;

        public void ParseEvent(MidiEvent @event)
        {
            IMidiMessage message = @event.MidiMessage;
            if (message.MessageType == MessageType.Channel)
            {
                ParseChannelMessage((ChannelMessage)message, @event);
            }
            else if (message.MessageType == MessageType.Meta)
            {
                ParseMetaMessage((MetaMessage)message, @event);
            }
            else if (message.MessageType == MessageType.SystemExclusive)
            {
                ParseSysExMessage((SysExMessage)message, @event);
            }
            else
            {
                UnhandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
            }
        }

        private void ParseChannelMessage(ChannelMessage message, MidiEvent @event)
        {
            // For any message that isn't a NoteOn event, update the current time and channel.
            // (We don't do this for NoteOn events because NoteOn aren't written until the NoteOff event)
            if (!IsNoteOnEvent(message.Command, message.MidiChannel, @event))
            {
                CheckChannel(message.MidiChannel);
            }
            switch (message.Command)
            {
                case ChannelCommand.NoteOff:
                    OnNoteOff(message.MidiChannel, @event);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.NoteOn:
                    OnNoteOn(message.MidiChannel, @event);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.PolyPressure:
                    OnPolyphonicPressureParsed(message.Data1, message.Data2);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.Controller:
                    OnControllerEventParsed(message.Data1, message.Data2);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.ProgramChange:
                    OnInstrumentParsed(message.Data1);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.ChannelPressure:
                    OnChannelPressureParsed(message.Data1);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case ChannelCommand.PitchWheel:
                    OnPitchWheelParsed(message.Data1, message.Data2);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                default:
                    UnhandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
            }
        }

        private void ParseMetaMessage(MetaMessage message, MidiEvent @event)
        {
            switch (message.MetaType)
            {
                case MetaType.Lyric:
                    OnLyricParsed(Encoding.ASCII.GetString(message.GetBytes()));
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case MetaType.Marker:
                    OnMarkerParsed(Encoding.ASCII.GetString(message.GetBytes()));
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case MetaType.Tempo:
                    WhenTempoChanged(message);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case MetaType.TimeSignature:
                    OnTimeSignatureParsed(message.GetBytes()[0], message.GetBytes()[1]);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                case MetaType.KeySignature:
                    KeySigParsed(message);
                    HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
                default:
                    UnhandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
                    break;
            }
        }

        private void ParseSysExMessage(IMidiMessage message, MidiEvent @event)
        {
            OnSystemExclusiveParsed(message.GetBytes());
            HandledMidiEvent?.Invoke(this, new MidiEventArgs(@event));
        }

        private bool IsNoteOnEvent(ChannelCommand command, int channel, MidiEvent @event)
        {
            return command == ChannelCommand.NoteOn && noteCache?[channel]?.GetValueOrDefault(@event.MidiMessage.GetBytes()[1]) == null &&
                    (@event.MidiMessage.GetBytes()[2] == 0);
        }

        private bool IsNoteOffEvent(ChannelCommand command, int channel, MidiEvent @event)
        {
            // An event is a NoteOff event if it is actually a NoteOff event,
            // or if it is a NoteOn event where the note has already been played and the attack velocity is 0.
            return (command == ChannelCommand.NoteOff) ||
                   ((command == ChannelCommand.NoteOn) &&
                    (noteCache?[channel]?.GetValueOrDefault(@event.MidiMessage.GetBytes()[1]) != null) &&
                    (@event.MidiMessage.GetBytes()[2] == 0));
        }

        private void OnNoteOff(int channel, MidiEvent @event)
        {
            byte note = @event.MidiMessage.GetBytes()[1];
            TempNote tempNote = noteCache?[channel]?[note];
            if (tempNote == null)
            {
                // A note was turned off when that note was never indicated as having been turned on
                return;
            }
            noteCache[channel].Remove(note);
            CheckTime(tempNote.StartTick);

            long durationInTicks = @event.AbsoluteTicks - tempNote.StartTick;
            double durationInBeats = GetDurationInBeats(durationInTicks);
            byte noteOffVelocity = @event.MidiMessage.GetBytes()[2];
            expectedTimeInBeats[currentChannel] = currentTimeInBeats[currentChannel] + durationInBeats;

            Note noteObject = new Note(note)
            {
                Duration = GetDurationInBeats(durationInTicks),
                OnVelocity = tempNote.NoteOnVelocity,
                OffVelocity = noteOffVelocity
            };
            OnNoteReleased(new Note(note) { OffVelocity = noteOffVelocity });
            OnNoteParsed(noteObject);
        }

        private void OnNoteOn(int channel, MidiEvent @event)
        {
            if (IsNoteOffEvent(ChannelCommand.NoteOn, channel, @event))
            {
                // Some MIDI files use the Note On event with 0 velocity to indicate Note Off
                OnNoteOff(channel, @event);
                return;
            }

            byte note = @event.MidiMessage.GetBytes()[1];
            byte noteOnVelocity = @event.MidiMessage.GetBytes()[2];
            if (noteCache?[channel]?.GetValueOrDefault(note) != null)
            {
                // The note already existed in the cache! Nothing to do about it now. This shouldn't happen.
            }
            else
            {
                noteCache?[channel]?.Add(note, new TempNote(@event.AbsoluteTicks, noteOnVelocity));
            }
            OnNotePressed(new Note(note) { OnVelocity = noteOnVelocity });
        }

        private void WhenTempoChanged(MetaMessage meta)
        {
            int newTempoMSPQ = (meta.GetBytes()[2] & 0xFF) |
                ((meta.GetBytes()[1] & 0xFF) << 8) |
                ((meta.GetBytes()[0] & 0xFF) << 16);
            this.tempoBPM = newTempoMSPQ = 60000000 / newTempoMSPQ;
            OnTempoChanged(tempoBPM);
        }

        private void KeySigParsed(MetaMessage meta)
        {
            byte scale = (byte)(meta.GetBytes()[1] == 0 ? ScaleType.Major : ScaleType.Minor);
            OnKeySignatureParsed(KeyProviderFactory.GetKeyProvider().ConvertAccidentalCountToKeyRootPositionInOctave(
                meta.GetBytes()[0], scale), scale);
        }

        private void CheckTime(long tick)
        {
            double newTimeInBeats = GetDurationInBeats(tick);
            if (expectedTimeInBeats[currentChannel] != newTimeInBeats)
            {
                if (newTimeInBeats > expectedTimeInBeats[this.currentChannel])
                {
                    OnNoteParsed(Note.CreateRest(newTimeInBeats - expectedTimeInBeats[currentChannel]));
                }
                else
                {
                    OnTrackBeatTimeRequested(newTimeInBeats);
                }
            }
            currentTimeInBeats[currentChannel] = newTimeInBeats;
        }

        private void CheckChannel(int channel)
        {
            if (currentChannel != channel)
            {
                OnTrackChanged(channel);
                currentChannel = channel;
            }
        }

        private double GetDurationInBeats(long durationInTicks)
        {
            return durationInTicks / (double)resolutionTicksPerBeat / 4.0d;
        }

        private void InitNoteCache()
        {
            noteCache = new List<Dictionary<byte, TempNote>>();
            currentTimeInBeats = new double[MidiDefaults.Tracks];
            expectedTimeInBeats = new double[MidiDefaults.Tracks];

            for (int i = 0; i < MidiDefaults.Tracks; i++)
            {
                noteCache.Add(new Dictionary<byte, TempNote>());
                currentTimeInBeats[i] = 0.0d;
                expectedTimeInBeats[i] = 0.0d;
            }
        }

        internal class TempNote
        {
            public long StartTick { get; }
            public byte NoteOnVelocity { get; }

            public TempNote(long startTick, byte noteOnVelocity)
            {
                StartTick = startTick;
                NoteOnVelocity = noteOnVelocity;
            }
        }
    }
}


text:
package scala.tools.nsc.interactive.tests.core

case class DuplicateTestMarker(msg: String) extends Exception(msg)

object TestMarker {
  import scala.collection.mutable.Map
  private val markers: Map[String, TestMarker] = Map.empty

  private def checkForDuplicate(marker: TestMarker): Unit = {
    markers.get(marker.marker) match {
      case None => markers(marker.marker) = marker
      case Some(otherMarker) =>
        val msg = "Marker `%s` is already used by %s. Please choose a different marker for %s".format(marker.marker, marker, otherMarker)
        throw new DuplicateTestMarker(msg)
    }
  }
}

abstract case class TestMarker(marker: String) {
  TestMarker.checkForDuplicate(this)
}

object TypeCompletionMarker extends TestMarker("/*!*/")

object ScopeCompletionMarker extends TestMarker("/*_*/")

object TypeMarker extends TestMarker("/*?*/")

object HyperlinkMarker extends TestMarker("/*#*/")


text:
#include <sys/time.h>

#include "test.h"

/* The glib timer will subtract a perterbation of up to 10ms based on your
 * DBUS session or HOSTNAME (see g_timeout_set_expiration). */
#define SLEEP 10
#define SLEEP_MIN (SLEEP-10)
#define SLEEP_MAX (SLEEP*4)
#define M2U(m) ((m) * 1000)

static int callcount;
struct timeval starttime;

static char
elapsed(time_t min, time_t max)
{
    struct timeval tv;
    long long diff;

    assert(gettimeofday(&tv, NULL) == 0);
    diff = (tv.tv_sec - starttime.tv_sec) * M2U(1000)
            + tv.tv_usec - starttime.tv_usec;

    assert(gettimeofday(&starttime, NULL) == 0);
    if (diff < M2U(min) || diff > M2U(max)) {
        printf("ERROR: Timeout is out-of-bounds!\n");
        return 0;
    }
    return 1;
}

static void
exit_cb(verto_ctx *ctx, verto_ev *ev)
{
    (void) ev;
    assert(callcount == 3);
    verto_break(ctx);
}

static void
cb(verto_ctx *ctx, verto_ev *ev)
{
    assert(elapsed(SLEEP_MIN, SLEEP_MAX));
    if (++callcount == 3)
        assert(verto_add_timeout(ctx, VERTO_EV_FLAG_NONE, exit_cb, SLEEP*2));
    else if (callcount == 2) {
        assert(verto_add_timeout(ctx, VERTO_EV_FLAG_NONE, cb, SLEEP));
        verto_del(ev);
    }
}

int
do_test(verto_ctx *ctx)
{
    callcount = 0;

    assert(gettimeofday(&starttime, NULL) == 0);
    assert(verto_add_timeout(ctx, VERTO_EV_FLAG_PERSIST, cb, SLEEP));
    return 0;
}


text:
package org.scribble.codegen.java.endpointapi.ioifaces;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.scribble.codegen.java.endpointapi.ScribSocketGenerator;
import org.scribble.codegen.java.endpointapi.SessionApiGenerator;
import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator;
import org.scribble.codegen.java.util.AbstractMethodBuilder;
import org.scribble.codegen.java.util.EnumBuilder;
import org.scribble.codegen.java.util.InterfaceBuilder;
import org.scribble.codegen.java.util.JavaBuilder;
import org.scribble.main.ScribbleException;
import org.scribble.model.endpoint.EState;
import org.scribble.model.endpoint.actions.EAction;
import org.scribble.sesstype.name.Role;

public class BranchInterfaceGenerator extends IOStateInterfaceGenerator
{
	public BranchInterfaceGenerator(StateChannelApiGenerator apigen, Map<EAction, InterfaceBuilder> actions, EState curr)
	{
		super(apigen, actions, curr);
	}

	@Override
	protected void constructInterface() throws ScribbleException
	{
		super.constructInterface();
		addBranchEnum();
		addBranchMethods();
	}

	protected void addBranchMethods()
	{
		Role self = this.apigen.getSelf();
		//Set<EAction> as = this.curr.getActions();
		List<EAction> as = this.curr.getActions();

		// FIXME: factor out with BranchSocketGenerator
		AbstractMethodBuilder bra = this.ib.newAbstractMethod("branch");
		String ret = CaseInterfaceGenerator.getCasesInterfaceName(self, this.curr)
				+ "<" + IntStream.range(1, as.size()+1).mapToObj((i) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">";  // FIXME: factor out
		bra.setReturn(ret);
		bra.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role");
		bra.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");

		AbstractMethodBuilder bra2 = this.ib.newAbstractMethod("branch");
		bra2.setReturn(JavaBuilder.VOID);
		bra2.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role");
		String next = HandleInterfaceGenerator.getHandleInterfaceName(self, this.curr) + "<" + IntStream.range(1, as.size() + 1).mapToObj((i) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">";
		bra2.addParameters(next + " handler");
		bra2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");

		AbstractMethodBuilder bra3 = this.ib.newAbstractMethod("handle");
		bra3.setReturn(JavaBuilder.VOID);
		bra3.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role");
		String handle = HandleInterfaceGenerator.getHandleInterfaceName(self, this.curr) + "<" +
				as.stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR)
					.map((a) -> SuccessorInterfaceGenerator.getSuccessorInterfaceName(a)).collect(Collectors.joining(", ")) + ">";
		bra3.addParameters(handle + " handler");
		bra3.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");
	}

	protected void addBranchEnum()
	{
		Role self = this.apigen.getSelf();

		// Duplicated from BranchSocketGenerator
		EnumBuilder eb = this.ib.newMemberEnum(getBranchInterfaceEnumName(self, this.curr));
		eb.addModifiers(JavaBuilder.PUBLIC);
		eb.addInterfaces(ScribSocketGenerator.OPENUM_INTERFACE);
		this.curr.getActions().stream().forEach((a) -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid)));
	}

	// Don't add Action Interfaces (added to CaseInterface)
	@Override
	protected void addSuccessorParamsAndActionInterfaces()
	{
		int i = 1;
		for (EAction a : this.curr.getActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList()))
		{
			this.ib.addParameters("__Succ" + i + " extends " + SuccessorInterfaceGenerator.getSuccessorInterfaceName(a));
			i++;
		}
	}

	public static String getBranchInterfaceEnumName(Role self, EState curr)
	{
		return getIOStateInterfaceName(self, curr) + "_Enum";
	}
}


text:
static NSString *TemperatureDewpointRegex = @"\\bT(0|1)(\\d{3})(?:(0|1)(\\d{3}))?\\b\\s*";

@implementation TemperatureDewpointRemark

@synthesize temperature;
@synthesize dewpoint;
@synthesize dewpointUnknown;

+ (void) load {
    [Remark registerSubclass:self];
}

- (instancetype) initFromRemarks:(NSMutableString *)remarks forMETAR:(METAR *)METAR {
    if (self = [super initFromRemarks:remarks forMETAR:METAR]) {
        NSTextCheckingResult *match = [self matchRemarks:remarks withRegex:TemperatureDewpointRegex];
        if (!match) return (self = nil);

        NSString *codedTempSign = [remarks substringWithRange:[match rangeAtIndex:1]];
        NSInteger tempMultiplier = ([codedTempSign isEqualToString:@"0"] ? 1 : -1);
        NSString *codedTemp = [remarks substringWithRange:[match rangeAtIndex:2]];
        self.temperature = codedTemp.integerValue/10.0*tempMultiplier;

        if ([match rangeAtIndex:3].location != NSNotFound) {
            NSString *codedDewpointSign = [remarks substringWithRange:[match rangeAtIndex:3]];
            NSInteger dewpointMultiplier = ([codedDewpointSign isEqualToString:@"0"] ? 1 : -1);
            NSString *codedDewpoint = [remarks substringWithRange:[match rangeAtIndex:4]];
            self.dewpoint = codedDewpoint.integerValue/10.0*dewpointMultiplier;
            self.dewpointUnknown = NO;
        } else
            self.dewpointUnknown = YES;

        [remarks deleteCharactersInRange:match.range];
    }
    return self;
}

- (RemarkUrgency) urgency {
    return UrgencyRoutine;
}

- (NSString *) stringValue {
    if (self.dewpointUnknown)
        return [NSString localizedStringWithFormat:MDLocalizedString(@"METAR.Remark.TemperatureDewpoint.TempOnly", @"{temperature}"),
                self.temperature];
    else
        return [NSString localizedStringWithFormat:MDLocalizedString(@"METAR.Remark.TemperatureDewpoint.TempDewpoint", @"{temperature}, {dewpoint}"),
                self.temperature, self.dewpoint];
}

@end


text:
package org.optaplannerdelirium.sss.solver.score;

import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import org.optaplanner.core.impl.score.director.incremental.AbstractIncrementalScoreCalculator;
import org.optaplannerdelirium.sss.domain.GiftAssignment;
import org.optaplannerdelirium.sss.domain.Reindeer;
import org.optaplannerdelirium.sss.domain.ReindeerRoutingSolution;
import org.optaplannerdelirium.sss.domain.Standstill;

public class ReindeerRoutingIncrementalScoreCalculator extends AbstractIncrementalScoreCalculator<ReindeerRoutingSolution> {

    private long hardScore;
    private long softScore;

    public void resetWorkingSolution(ReindeerRoutingSolution solution) {
        hardScore = 0L;
        softScore = 0L;
        for (Reindeer reindeer : solution.getReindeerList()) {
            insertTransportationToNextPenalty(reindeer);
        }
        for (GiftAssignment giftAssignment : solution.getGiftAssignmentList()) {
            insertTransportationWeight(giftAssignment);
            insertTransportationToNextPenalty(giftAssignment);
        }
    }

    public void beforeEntityAdded(Object entity) {
        // Do nothing
    }

    public void afterEntityAdded(Object entity) {
        Standstill standstill = (Standstill) entity;
        insertTransportationWeight(standstill);
        insertTransportationToNextPenalty(standstill);
    }

    public void beforeVariableChanged(Object entity, String variableName) {
        Standstill standstill = (Standstill) entity;
        if (variableName.equals("transportationWeight")) {
            retractTransportationWeight(standstill);
        } else if (variableName.equals("transportationToNextPenalty")) {
            retractTransportationToNextPenalty(standstill);
        }
    }

    public void afterVariableChanged(Object entity, String variableName) {
        Standstill standstill = (Standstill) entity;
        if (variableName.equals("transportationWeight")) {
            insertTransportationWeight(standstill);
        } else if (variableName.equals("transportationToNextPenalty")) {
            insertTransportationToNextPenalty(standstill);
        }
    }

    public void beforeEntityRemoved(Object entity) {
        Standstill standstill = (Standstill) entity;
        retractTransportationWeight(standstill);
        retractTransportationToNextPenalty(standstill);
    }

    public void afterEntityRemoved(Object entity) {
        // Do nothing
    }

    private void insertTransportationWeight(Standstill standstill) {
        Long transportationWeight = standstill.getTransportationWeight();
        if (transportationWeight == null) {
            return;
        }
        long weightCapacity = Reindeer.WEIGHT_CAPACITY - transportationWeight;
        if (weightCapacity < 0L) {
            hardScore += weightCapacity;
        }
    }

    private void retractTransportationWeight(Standstill standstill) {
        Long transportationWeight = standstill.getTransportationWeight();
        if (transportationWeight == null) {
            return;
        }
        long weightCapacity = Reindeer.WEIGHT_CAPACITY - transportationWeight;
        if (weightCapacity < 0L) {
            hardScore -= weightCapacity;
        }
    }

    private void insertTransportationToNextPenalty(Standstill standstill) {
        Long transportationToNextPenalty = standstill.getTransportationToNextPenalty();
        if (transportationToNextPenalty == null) {
            return;
        }
        softScore -= transportationToNextPenalty;
    }

    private void retractTransportationToNextPenalty(Standstill standstill) {
        Long transportationToNextPenalty = standstill.getTransportationToNextPenalty();
        if (transportationToNextPenalty == null) {
            return;
        }
        softScore += transportationToNextPenalty;
    }

    public HardSoftLongScore calculateScore() {
        return HardSoftLongScore.valueOf(hardScore, softScore);
    }

}


text:
package com.greencode.enticement_android.LayoutControllers;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.greencode.enticement_android.Enticement.EnticementApplication;
import com.greencode.enticement_android.Databases.Firebase;
import com.greencode.enticement_android.Models.ChatRoom;
import com.greencode.enticement_android.R;

public class MyChatRoomRecyclerViewAdapter extends FirebaseRecyclerAdapter<ChatRoom, MyChatRoomRecyclerViewAdapter.ChatRoomViewHolder> {
    private Context mContext;
    private final EnticementApplication mInstance = EnticementApplication.getInstance();

    public MyChatRoomRecyclerViewAdapter(Context context) {
        super(ChatRoom.class, R.layout.chatroom_item_row, MyChatRoomRecyclerViewAdapter.ChatRoomViewHolder.class, Firebase.ChatRoomRef);
        this.mContext = context;
    }

    @Override
    public ChatRoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.chatroom_item_row, parent, false);
        return new ChatRoomViewHolder(view);
    }

    @Override
    protected void populateViewHolder(ChatRoomViewHolder viewHolder, ChatRoom model, int position) {
        String id = mInstance.getPrefManager().getProfile().getId();

        if (model.getUserID1().equals(id) || model.getUserID2().equals(id)) {
            Firebase.getUserProfileToChatRoom(model);
            viewHolder.setName(model.getUser().getName());
            String msg;
            if (model.getLastMessageFrom().equals(id)) {
                msg = "You: " + model.getLastMessage();
                viewHolder.setLastMsg(msg);
            } else {
                msg = model.getName() + ": " + model.getLastMessage();
                viewHolder.setLastMsg(msg);
            }
            viewHolder.setUnreadcount(model.getUnreadCount());
            viewHolder.setLastMsg(model.getLastMessage());
        } else {
            viewHolder.remove();
        }
    }

    public interface ClickListener {
        void onClick(View view, int position);
        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
        private GestureDetector gestureDetector;
        private MyChatRoomRecyclerViewAdapter.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MyChatRoomRecyclerViewAdapter.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

    class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView avatar;
        TextView name;
        TextView message;
        TextView timestamp;
        TextView unreadcount;
        View rootView;

        ChatRoomViewHolder(View view) {
            super(view);
            rootView = view;
            avatar = (ImageView) view.findViewById(R.id.chatroom_avatar);
            name = (TextView) view.findViewById(R.id.chatroom_name);
            message = (TextView) view.findViewById(R.id.chatroom_lastmsg);
            timestamp = (TextView) view.findViewById(R.id.chatroom_time);
            unreadcount = (TextView) view.findViewById(R.id.chatroom_count);
        }

        void setAvatar(String link) {

        }

        void setLastMsg(String msg) {
            this.message.setText(msg);
        }

        void setName(String name) {
            this.name.setText(name);
        }

        void setUnreadcount(int count) {
            if (count == 0) {
                this.unreadcount.setVisibility(View.GONE);
            } else {
                this.unreadcount.setText(String.valueOf(count));
                this.name.setTypeface(Typeface.DEFAULT_BOLD);
                this.message.setTypeface(Typeface.DEFAULT_BOLD);
            }
        }

        void remove() {
            rootView.destroyDrawingCache();
        }

        @Override
        public void onClick(View view) {

        }
    }
}


text:
/*!
  \class SbCylinderSheetProjector SbCylinderSheetProjector.h Inventor/projectors/SbCylinderSheetProjector.h
  \brief The SbCylinderSheetProjector class projects 2D points to 3D points on a sheet covering a cylindrical shape.
  \ingroup projectors
 */

// FIXME: we do not use a hyperbolic sheet, as we're supposed to do,
// for this class. Instead we use a straight plane. This should hardly
// be noticable for the user, but for correctness, a hyperbolic sheet
// should of course be used. 20000308 mortene.

#include <Inventor/projectors/SbCylinderSheetProjector.h>
#include <float.h> // FLT_EPSILON

#if COIN_DEBUG
#include <Inventor/errors/SoDebugError.h>
#endif // COIN_DEBUG

/*! \var SbCylinderSheetProjector::workingProjPoint
  Last projected point, in the working space coordinate system.
*/
/*! \var SbCylinderSheetProjector::planeDir
  Normal vector of the plane defining the orientation of the sheet.
*/
/*! \var SbCylinderSheetProjector::tolPlane
  The tolerance value specifying how much of the cylinder is "above"
  the sheet.
*/

/*!
  Constructor. Uses default cylinder defintion, see
  SbCylinderProjector::SbCylinderProjector().

  \a orienttoeye decides whether or not the cylinder and sheet should
  always be oriented towards the viewer.
*/
SbCylinderSheetProjector::SbCylinderSheetProjector(const SbBool orienttoeye)
  : inherited(orienttoeye)
{
}

/*!
  Constructor with explicit definition of projection cylinder.
*/
SbCylinderSheetProjector::SbCylinderSheetProjector(const SbCylinder & cyl,
                                                   const SbBool orienttoeye)
  : inherited(cyl, orienttoeye)
{
}

// Documented in superclass.
SbProjector *
SbCylinderSheetProjector::copy(void) const
{
  return new SbCylinderSheetProjector(*this);
}

// Documented in superclass.
SbVec3f
SbCylinderSheetProjector::project(const SbVec2f & point)
{
  if (this->needSetup) this->setupPlane();

  SbLine projline = this->getWorkingLine(point);
  SbVec3f projpt;

  // FIXME: add code to intersect hyperbolic sheet (see code in
  // SbSphereSheetProjector).
  //
  // Here's a complete, stand-alone example that can be used while
  // testing projection. It projects a grid on top of the
  // SbCylinderSheetProjector and spits out an iv-file with an
  // SoPointSet that shows off how the sheet will look:
  //
  //
  // -----8<--- [snip] -----8<--- [snip] -----8<--- [snip] ---
  // #include <stdio.h>
  // #include <Inventor/SbLinear.h>
  // #include <Inventor/projectors/SbCylinderSheetProjector.h>
  // #include <Inventor/SoDB.h>
  //
  // int
  // main(void)
  // {
  //   SoDB::init();
  //
  //   const float START = 0.0f;
  //   const float END = 1.0f;
  //   const float STEPS = 50.0f;
  //   const float STEPSIZE = ((END - START) / STEPS);
  //
  //   SbCylinderSheetProjector ssp;
  //
  //   SbViewVolume volume;
  //   volume.ortho(-1, 1, -1, 1, -1, 1);
  //   ssp.setViewVolume(volume);
  //
  //   (void)fprintf(stdout, "#Inventor V2.1 ascii\n\n"
  //                 "Separator {\n"
  //                 "  Coordinate3 {\n"
  //                 "    point [\n");
  //
  //   for (float i=START; i <= END; i += STEPSIZE) {
  //     for (float j=START; j <= END; j += STEPSIZE) {
  //       SbVec3f v = ssp.project(SbVec2f(j, i));
  //       (void)fprintf(stdout, "\t%f %f %f,\n", v[0], v[1], v[2]);
  //     }
  //   }
  //
  //   (void)fprintf(stdout, "      ]\n"
  //                 "    }\n"
  //                 "  DrawStyle { pointSize 2 }\n"
  //                 "  PointSet { }\n"
  //                 "}\n");
  //
  //   return 0;
  // }
  // -----8<--- [snip] -----8<--- [snip] -----8<--- [snip] ---

  SbBool tst = this->intersectCylinderFront(projline, projpt);
  if (!tst) {
    if (!this->tolPlane.intersect(projline, projpt)) {
#if COIN_DEBUG
      SoDebugError::postWarning("SbCylinderSheetProjector::project",
                                "working line is parallel to cylinder axis.");
#endif // COIN_DEBUG
      return SbVec3f(0.0f, 0.0f, 0.0f);
    }
  }
  this->lastPoint = projpt;
  this->workingProjPoint = projpt; // FIXME: investigate (pederb)
  return projpt;
}

// Documented in superclass.
SbRotation
SbCylinderSheetProjector::getRotation(const SbVec3f & point1,
                                      const SbVec3f & point2)
{
  const SbLine & axis = this->cylinder.getAxis();
  SbVec3f v1 = point1 - axis.getClosestPoint(point1);
  SbVec3f v2 = point2 - axis.getClosestPoint(point2);
  SbRotation rot(v1, v2); // rotate vector v1 into vector v2

  // FIXME: add rotation from sheet (pederb)

  SbVec3f dummy;
  float angle;
  rot.getValue(dummy, angle);

  if (dummy.dot(axis.getDirection()) > 0.0f)
    return SbRotation(axis.getDirection(), angle);
  return SbRotation(axis.getDirection(), -angle);
}

/*!
  Recalculates projection surface settings after changes to the
  parameters.
*/
void
SbCylinderSheetProjector::setupPlane(void)
{
  const SbLine & axis = this->cylinder.getAxis();
  SbVec3f refDir;
  if (this->orientToEye) {
    refDir = -this->viewVol.getProjectionDirection();
    this->worldToWorking.multDirMatrix(refDir, refDir);
  }
  else {
    refDir = SbVec3f(0.0f, 0.0f, 1.0f);
  }
  SbVec3f somePt = axis.getPosition() + refDir;
  SbVec3f ptOnAxis = axis.getClosestPoint(somePt);

  this->planeDir = somePt - ptOnAxis;

  if (this->planeDir.normalize() < FLT_EPSILON) {
    // the cylinder axis is parallel to the view direction. This is a
    // special case, and not really supported by the projector. Just
    // create a tilted plane to make it possible to rotate the
    // cylinder even for this case.
    this->planeDir = this->viewVol.getViewUp() +
      this->viewVol.getProjectionDirection();
    this->worldToWorking.multDirMatrix(this->planeDir, this->planeDir);
    (void) this->planeDir.normalize();
  }

  if (!this->intersectFront) this->planeDir = -this->planeDir;

  this->tolPlane = SbPlane(this->planeDir, axis.getPosition());
  this->needSetup = FALSE;
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='League',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),
                ('name', models.CharField(max_length=200)),
                ('country', models.CharField(max_length=200)),
                ('league_id', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),
                ('name', models.CharField(max_length=200)),
                ('nickname', models.CharField(max_length=200)),
                ('team_id', models.IntegerField()),
                ('league', models.ForeignKey(verbose_name="team's league", to='scores.League')),
            ],
        ),
    ]


text:
class House < ActiveRecord::Base
  belongs_to :property_manager
  has_one :address, as: :addressable

  has_many :housing_assignments
  has_many :users, through: :housing_assignments
  has_many :rules
  has_many :events
  has_many :messages
  has_many :communal_items
  has_many :chores

  validates :name, presence: true
  validates :house_key, presence: true
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DNK.TravelInsuranceClient.TIServices;

namespace DNK.TravelInsuranceClient
{
    public class InputData : importedPolicy
    {
        public InputData()
        {
            this.common = new importedCommon();
            this.insureds = new importedInsureds();
            this.risks = new importedRisks();
        }

        public InputData(string insuranceProgrammUID, string countryUID, string additionalSportWorkUID, string additionalDiscountExtraUID,
                         DateTime policyPeriodFrom, DateTime policyPeriodTill, short? multiDays, string fio, string addressTel, DateTime? dateOfBirth,
                         string eMail, string comments) : this()
        {
            this.common.insuranceProgrammUID = Guid.Parse(insuranceProgrammUID);
            this.common.countryUID = Guid.Parse(countryUID);
            if (!string.IsNullOrEmpty(additionalSportWorkUID))
                this.common.additionalCondition = Guid.Parse(additionalSportWorkUID);
            if (!string.IsNullOrEmpty(additionalDiscountExtraUID))
                this.common.additionalCondition2 = Guid.Parse(additionalDiscountExtraUID);
            this.common.policyPeriodFrom = policyPeriodFrom.Date;
            this.common.policyPeriodTill = policyPeriodTill.Date;
            if (multiDays.HasValue)
                this.common.multiDays = multiDays.Value;
            this.common.fio = fio;
            if (!string.IsNullOrWhiteSpace(addressTel))
                this.common.addressTel = addressTel;
            if (dateOfBirth.HasValue)
                this.common.dateOfBirth = dateOfBirth.Value;
            if (!string.IsNullOrWhiteSpace(eMail))
                this.common.eMail = eMail;
            if (!string.IsNullOrWhiteSpace(comments))
                this.common.comments = comments;
        }

        public void AddInsured(string _fio, string _passport, DateTime _dateOfBirth)
        {
            if (!string.IsNullOrWhiteSpace(_fio))
            {
                importedInsured importedInsured = this.insureds.FirstOrDefault(p => p.fio.ToLower() == _fio.ToLower() && p.dateOfBirth == _dateOfBirth.Date);
                if (importedInsured == null)
                    this.insureds.Add(new importedInsured { fio = _fio, passport = _passport, dateOfBirth = _dateOfBirth.Date });
            }
        }

        public void AddRisk(string riskUID, int struhSum, string currency, string riskFranshize)
        {
            if (!string.IsNullOrEmpty(riskUID))
            {
                importedPolicyRisk importedPolicyRisk = new importedPolicyRisk();
                importedPolicyRisk.riskUID = Guid.Parse(riskUID);
                importedPolicyRisk.amountAtRisk = struhSum;
                importedPolicyRisk.amountCurrency = currency;
                if (!string.IsNullOrEmpty(riskFranshize))
                    importedPolicyRisk.franshize = riskFranshize;

                this.risks.Add(importedPolicyRisk);
            }
        }
    }
}


text:
require 'spec_helper'

klass = OneviewSDK::API300::C7000::StoragePool
RSpec.describe klass, integration: true, type: DELETE, sequence: rseq(klass) do
  include_examples 'StoragePoolDeleteExample', 'integration api300 context' do
    let(:current_client) { $client_300 }
  end
end


text:
**The documentation has now moved to the wiki in this repository.** For a quick start, look here.

**Development is on the "dev" branch (and feature branches). Please make any pull requests to the "dev" branch**.

This is the repository for the open source version of Event Store, which now includes the clustering implementation for high availability. Further information on commercial support and options such as LDAP authentication can be found on the Event Store website at http://geteventstore.com.

##Building from Source

Event Store is written in a mixture of C#, C++ and JavaScript. It can run either on Mono or .NET, however because it contains platform specific code (including hosting the v8 JavaScript engine), it must be built for the platform on which you intend to run it.

Binaries are available from http://geteventstore.com, however if you want to build it from source, instructions for Windows and Linux are below.

###Debug Builds on Windows / .NET

####Prerequisites

- .NET Framework v4.0+
- Windows platform SDK with compilers (v7.1) or Visual C++ installed
- git on PATH
- svn on PATH

####Building the Event Store

*Important note: if you have previously built from source, it's possible you have V8 checked out via git instead of Subversion. If this is the case, you should use the `clean-all` target noted below before building again.*

From a command prompt:

- `build.cmd` - runs the Event Store build
- `build.cmd clean-all` - cleans the repository

Optional parameters (Specified using `-ParameterName value`)

- `-Platform` - `x64` (default) or `x86`
- `-Configuration` - `release` (default) or `debug`
- `-Version` - the semantic version number to give to the release. Defaults to version `0.0.0.0` which should be used for all non-released builds.
- `-SpecificVisualStudioVersion` - `2010`, `2012`, `2013`, `Windows7.1SDK`. Default is to use whichever version is installed - this only needs to be overriden if you have multiple versions installed.
- `-ForceNetwork` - true if you want to force the script to get dependencies even if Windows thinks theres no network connection (otherwise we don't try to avoid sometimes lengthy delays).
- `-Defines` - any additional defines you want to pass to the compiler. Should be enclosed in single quotes

####Building the Event Store from Visual Studio

If you want to build from Visual Studio, it's necessary to first build from the
command line in order to build `js1.dll` which incorporates V8. When this is
available in the `src\EventStore\Libs\` directory, it is possible to build the
`src\EventStore\EventStore.sln` solution from within Visual Studio.

When building through Visual Studio, there are PowerShell scripts which run as
pre- and post-build tasks on the EventStore.Common project, which set the
informational version attribute of the EventStore.Common.dll assembly to the
current commit hash on each build and then revert it.

Unfortunately Visual Studio runs these scripts in 32-bit PowerShell. Since it's
most likely that you're running 64-bit PowerShell under normal circumstances,
the execution policy of 32-bit PowerShell will probably prohibit running
scripts. *There is a batch file in the root of the repository named
`RunMeElevatedFirst.cmd` which will set the execution policy for 32-bit
PowerShell if you run it as Administrator. Obviously you may want to audit what
the script does before executing it on your machine!*

###Debug Builds on Linux (Ubuntu 12.04) / Mono

####Prerequisites

- git on `PATH`
- Mono version 3.2.3 or greater on PATH
- svn on `PATH`
- gcc installed

####Building the Event Store

```bash
./build.sh <target> <version> <platform> <configuration>
```

- `target` is one of `quick`, `incremental` or `full` (see above)
- `version` is the semantic version to apply
- `platform` - either x86 or x64 (defaults to x64)
- `configuration` - either debug or release (defaults to release)


text:
import select
import socket
import sys
import os
import threading

SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 4769

def get_local_ip():
    return [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]

class PositionUpdater(object):
    def __init__(self, pos):
        self.pos = pos
        self.updater = None

    def get(self):
        return self.pos

    def set(self, pos):
        self.pos = pos

    def inc(self):
        self.pos = self.pos + 1000

    def run(self):
        print('pos', self.pos/1000)
        self.updater = threading.Timer(1, self.run)
        self.inc()
        self.updater.start()

    def stop(self):
        self.updater.cancel()

def chat_server(host, port):
    playstate = "0"
    fullscreenstate = "0"
    filename = "Some file.mkv"
    duration = 13245000
    position = PositionUpdater(0)
    stop = False
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    server_socket.listen(10)

    SOCKET_LIST.append(server_socket)

    print("Server: %s:%s" % (host, port))

    while not stop:
        ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)

        for sock in ready_to_read:
            # a new connection request recieved
            if sock == server_socket:
                sockfd, addr = server_socket.accept()
                SOCKET_LIST.append(sockfd)

                print("[%s:%s] connected" % addr)
                sockfd.send(b'0000 Python ZoomPlayer emulator\r\n0001 1.0\r\n')
                sockfd.send(b'1800 %s\r\n1000 %s\r\n' % (filename.encode('utf-8'), playstate.encode('utf-8')))

            # a message from a client, not a new connection
            else:
                try:
                    data = sock.recv(RECV_BUFFER)
                    if data:
                        data_str = data.decode('utf-8').strip()
                        print("[%s:%s]" % addr, data_str)
                        if data_str == 'server_stop':
                            stop = True
                            break
                        # ZP functions
                        if data_str.startswith(("5100", "5110", "5120", "5130")):
                            sock.send(data)
                            # Play / Pause
                            if 'fnPlay' in data_str:
                                if playstate == "0":
                                    playstate = "3"
                                    sock.send(b'1000 3\r\n')
                                    position.run()
                                else:
                                    playstate = "0"
                                    sock.send(b'1000 0\r\n')
                                    position.stop()
                            # Stop
                            elif 'fnStop' in data_str:
                                playstate = "0"
                                sock.send(b'1000 0\r\n')
                                position.stop()
                                position.set(0)
                            elif 'exSeekTo' in data_str:
                                position.set(int(data_str.split(',')[1])*1000)
                        # Fullscreen
                        elif data_str.startswith('1010'):
                            if fullscreenstate == "0":
                                fullscreenstate = "1"
                                sock.send(b'1010 1\r\n')
                            else:
                                fullscreenstate = "0"
                                sock.send(b'1010 0\r\n')
                        # Filename
                        elif data_str.startswith('1800'):
                            sock.send(b'1800 %s\r\n' % filename)
                        # Duration
                        elif data_str.startswith('1110'):
                            sock.send(b'1110 %i\r\n' % duration)
                        # Position
                        elif data_str.startswith('1120'):
                            sock.send(b'1120 %i\r\n' % position.get())
                        else:
                            broadcast(server_socket, sock, data)
                    else:
                        if sock in SOCKET_LIST:
                            SOCKET_LIST.remove(sock)

                        print("[%s:%s] (no data) disconnected" % addr)

                except Exception as e:
                    print("[%s:%s] disconnected" % addr, str(e))
                    continue

    server_socket.close()

# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
    for socket in SOCKET_LIST:
        # send the message only to peer
        if socket != server_socket and socket != sock :
            try :
                socket.send(message)
            except :
                # broken socket connection
                socket.close()
                # broken socket, remove it
                if socket in SOCKET_LIST:
                    SOCKET_LIST.remove(socket)

def main():
    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    else:
        port = PORT
    sys.exit(chat_server(get_local_ip(), port))

if __name__ == '__main__':
    main()


text:
 <link href="pantheios.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

Examples

pantheios/inserters/exception.hpp File Reference

Detailed Description

[C++ only] String inserter for std::exception-derived types.

#include <pantheios/pantheios.h>

#include <stlsoft/shims/access/string/fwd.h>

#include <exception>

Go to the source code of this file.

Namespaces

namespace  	pantheios

Functions

std::exception const & 	exception (std::exception const &x)

 	Converts a reference to an exception to an instance of a type that allows the exception to be inserted into Pantheios diagnostic logging statements.

    pantheios
    Library documentation
    © Matthew Wilson &
    Synesis Software,
    2006-2011


text:
<configuration>

	<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
		<target>System.err</target>
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
			</pattern>
		</encoder>
	</appender>

	<logger name="it.polimi.modaclouds.monitoring.monitoring_manager" level="INFO" />
	<logger name="it.polimi.modaclouds.qos_models.monitoring_rules.actions" level="INFO" />

	<root level="ERROR">
		<appender-ref ref="STDERR" />
	</root>
</configuration>


text:
package org.stagemonitor.core.metrics.metrics2;

import com.codahale.metrics.Clock;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;

import org.junit.Before;
import org.junit.Test;
import org.stagemonitor.core.CorePlugin;
import org.stagemonitor.core.util.HttpClient;

import java.net.URL;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.counter;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.gauge;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.histogram;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.meter;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.metricNameMap;
import static org.stagemonitor.core.metrics.MetricsReporterTestHelper.timer;
import static org.stagemonitor.core.metrics.metrics2.MetricName.name;

public class InfluxDbReporterTest {

	private static final TimeUnit DURATION_UNIT = TimeUnit.MICROSECONDS;

	private InfluxDbReporter influxDbReporter;
	private HttpClient httpClient;
	private long timestamp;

	@Before
	public void setUp() throws Exception {
		httpClient = mock(HttpClient.class);
		Clock clock = mock(Clock.class);
		timestamp = System.currentTimeMillis();
		when(clock.getTime()).thenReturn(timestamp);
		final CorePlugin corePlugin = mock(CorePlugin.class);
		when(corePlugin.getInfluxDbUrl()).thenReturn(new URL("http://localhost:8086"));
		when(corePlugin.getInfluxDbDb()).thenReturn("stm");
		influxDbReporter = InfluxDbReporter.forRegistry(new Metric2Registry(), corePlugin)
				.convertRatesTo(TimeUnit.SECONDS)
				.convertDurationsTo(DURATION_UNIT)
				.globalTags(singletonMap("app", "test"))
				.httpClient(httpClient)
				.clock(clock)
				.build();
	}

	@Test
	public void testReportGauges() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(name("cpu_usage").type("user").tag("core", "1").build(), gauge(3)),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("cpu_usage,core=1,type=user,app=test value=3 %d", timestamp))));
	}

	@Test
	public void testReportNullGauge() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(name("cpu_usage").type("user").tag("core", "1").build(), gauge(null)),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(Collections.emptyList()));
	}

	@Test
	public void testReportBooleanGauge() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(name("gauge").build(), gauge(true)),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("gauge,app=test value_boolean=true %d", timestamp))));
	}

	@Test
	public void testReportStringGauge() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(name("gauge").build(), gauge("foo")),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("gauge,app=test value_string=\"foo\" %d", timestamp))));
	}

	@Test
	public void testReportGaugesExponent() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(name("cpu_usage").type("user").tag("core", "1").build(), gauge(1e-8)),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("cpu_usage,core=1,type=user,app=test value=1.0e-8 %d", timestamp))));
	}

	@Test
	public void testReportCounters() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(Gauge.class),
				metricNameMap(name("web_sessions").build(), counter(123)),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("web_sessions,app=test count=123i %d", timestamp))));
	}

	@Test
	public void testReportHistograms() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(Gauge.class),
				metricNameMap(Counter.class),
				metricNameMap(name("histogram").build(), histogram(400)),
				metricNameMap(Meter.class),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("histogram,app=test count=1i,min=400,max=200,mean=400.0,p50=600.0,std=500.0,p25=0.0,p75=700.0,p95=800.0,p98=900.0,p99=1000.0,p999=1100.0 %d", timestamp))));
	}

	@Test
	public void testReportMeters() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(Gauge.class),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(name("meter").build(), meter(10)),
				metricNameMap(Timer.class));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("meter,app=test count=10i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0 %d", timestamp))));
	}

	@Test
	public void testReportTimers() throws Exception {
		influxDbReporter.reportMetrics(
				metricNameMap(Gauge.class),
				metricNameMap(Counter.class),
				metricNameMap(Histogram.class),
				metricNameMap(Meter.class),
				metricNameMap(name("response_time").build(), timer(400)));

		verify(httpClient).send(eq("POST"), eq("http://localhost:8086/write?precision=ms&db=stm"),
				eq(singletonList(format("response_time,app=test count=1i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0,min=0.4,max=0.2,mean=0.4,p50=0.6,std=0.5,p25=0.0,p75=0.7,p95=0.8,p98=0.9,p99=1.0,p999=1.1 %d", timestamp))));
	}

	@Test
	public void testGetInfluxDbStringOrderedTags() throws Exception {
		assertEquals("cpu_usage,core=1,level=user",
				InfluxDbReporter.getInfluxDbLineProtocolString(name("cpu_usage").tag("level", "user").tag("core", "1").build()));
	}

	@Test
	public void testGetInfluxDbStringWhiteSpace() throws Exception {
		assertEquals("cpu\\ usage,level=soft\\ irq",
				InfluxDbReporter.getInfluxDbLineProtocolString(name("cpu usage").tag("level", "soft irq").build()));
	}

	@Test
	public void testGetInfluxDbStringNoTags() throws Exception {
		assertEquals("cpu_usage",
				InfluxDbReporter.getInfluxDbLineProtocolString(name("cpu_usage").build()));
	}

	@Test
	public void testGetInfluxDbStringAllEscapingAndQuotingBehavior() throws Exception {
		assertEquals("\"measurement\\ with\\ quotes\",tag\\ key\\ with\\ spaces=tag\\,value\\,with\"commas\"",
				InfluxDbReporter.getInfluxDbLineProtocolString(name("\"measurement with quotes\"").tag("tag key with spaces", "tag,value,with\"commas\"").build()));
	}
}


text: Simple recipes


text:
package rds

import (
	. "aliyun-openapi-go-sdk/core"
	"strconv"
)

type UnlockDBInstanceRequest struct {
	RpcRequest
	OwnerId              int
	ResourceOwnerAccount string
	ResourceOwnerId      int
	DBInstanceId         string
	OwnerAccount         string
}

func (r *UnlockDBInstanceRequest) SetOwnerId(value int) {
	r.OwnerId = value
	r.QueryParams.Set("OwnerId", strconv.Itoa(value))
}
func (r *UnlockDBInstanceRequest) GetOwnerId() int {
	return r.OwnerId
}
func (r *UnlockDBInstanceRequest) SetResourceOwnerAccount(value string) {
	r.ResourceOwnerAccount = value
	r.QueryParams.Set("ResourceOwnerAccount", value)
}
func (r *UnlockDBInstanceRequest) GetResourceOwnerAccount() string {
	return r.ResourceOwnerAccount
}
func (r *UnlockDBInstanceRequest) SetResourceOwnerId(value int) {
	r.ResourceOwnerId = value
	r.QueryParams.Set("ResourceOwnerId", strconv.Itoa(value))
}
func (r *UnlockDBInstanceRequest) GetResourceOwnerId() int {
	return r.ResourceOwnerId
}
func (r *UnlockDBInstanceRequest) SetDBInstanceId(value string) {
	r.DBInstanceId = value
	r.QueryParams.Set("DBInstanceId", value)
}
func (r *UnlockDBInstanceRequest) GetDBInstanceId() string {
	return r.DBInstanceId
}
func (r *UnlockDBInstanceRequest) SetOwnerAccount(value string) {
	r.OwnerAccount = value
	r.QueryParams.Set("OwnerAccount", value)
}
func (r *UnlockDBInstanceRequest) GetOwnerAccount() string {
	return r.OwnerAccount
}

func (r *UnlockDBInstanceRequest) Init() {
	r.RpcRequest.Init()
	r.SetVersion(Version)
	r.SetAction("UnlockDBInstance")
	r.SetProduct(Product)
}

type UnlockDBInstanceResponse struct {
}

func UnlockDBInstance(req *UnlockDBInstanceRequest, accessId, accessSecret string) (*UnlockDBInstanceResponse, error) {
	var pResponse UnlockDBInstanceResponse
	body, err := ApiHttpRequest(accessId, accessSecret, req)
	if err != nil {
		return nil, err
	}
	ApiUnmarshalResponse(req.GetFormat(), body, &pResponse)
	return &pResponse, err
}


text:
This folder contains the Dockerfile and associated files for the ```durdn/atlassian-jira``` docker image which aims to make it a breeze getting an Atlassian Jira instance up and running.

## Using Docker Compose to run the published image (Recommended)
This will provision a local PostgreSQL DB container, download the `atlassian-jira`
image from the public Docker Hub, and start a locally running instance of JIRA.

1. Install Docker (http://docs.docker.com/installation/)
2. Install Docker Compose (http://docs.docker.com/compose/)
3. From this directory, run `docker-compose up`
4. After a few moments, JIRA should now be running locally on http://localhost:8080

## Using Docker Compose to build and run the Dockerfile (for developing the image)
This will provision a local PostgreSQL DB container, build the `atlassian-jira`
image from the Dockerfile, and start a locally running instance of JIRA. It's
meant to be used when you are contributing to the Dockerfile or don't have
access to the public Docker Hub.

1. Install Docker (http://docs.docker.com/installation/)
2. Install Docker Compose (http://docs.docker.com/compose/)
3. From this directory, run `docker-compose -f docker-compose-dev.yml up`
4. After a few minutes, JIRA should now be running locally on http://localhost:8080

## Database connection

The connection to the database can be specified with an URL of the format:
```
[database type]://[username]:[password]@[host]:[port]/[database name]
```
Where ```database type``` is either ```mysql``` or ```postgresql``` and the full URL might look like this:
```
postgresql://jira:jellyfish@172.17.0.2/jiradb
```

When a database url is specified Jira will skip the database configuration step in the setup.

## Configuration

Configuration options are set by setting environment variables when running the image. What follows it a table of the supported variables:

Variable     | Function
-------------|------------------------------
CONTEXT_PATH | Context path of the jira webapp. You can set this to add a path prefix to the url used to access the webapp. i.e. setting this to ```jira``` will change the url to http://localhost:8080/jira/. The value ```ROOT``` is reserved to mean that you don't want a context path prefix. Defaults to ```ROOT```
DATABASE_URL | Connection URL specifying where and how to connect to a database dedicated to jira. This variable is optional and if specified will cause the Jira setup wizard to skip the database setup set.


text:
<?php

defined( '_JEXEC' ) or die( 'Restricted access' );

if (!class_exists('vmPlugin')) require(VMPATH_PLUGINLIBS . DS . 'vmplugin.php');

abstract class vmCouponPlugin extends vmPlugin {

	function __construct(& $subject, $config) {

		parent::__construct($subject, $config);

		$this->_tablename = '#__virtuemart_coupon_' . $this->_name;

	}

}