text:
import { execFile, spawn as _spawn } from "child_process"
import { Promise as BluebirdPromise } from "bluebird"
import "source-map-support/register"

export const log = console.log

BluebirdPromise.config({
  longStackTraces: true,
  cancellation: true
})

export const DEFAULT_APP_DIR_NAME = "app"

export const commonArgs: any[] = [{
  name: "appDir",
  type: String,
  description: "Relative (to the working directory) path to the folder containing the application package.json. Working directory or app/ by default."
}]

const execFileAsync: (file: string, args?: string[], options?: ExecOptions) => BluebirdPromise<Buffer[]> = (<any>BluebirdPromise.promisify(execFile, {multiArgs: true}))

export function installDependencies(appDir: string, arch: string, electronVersion: string): BluebirdPromise<any> {
  log("Installing app dependencies for arch %s to %s", arch || process.arch, appDir)
  const env = Object.assign({}, process.env, {
    npm_config_disturl: "https://atom.io/download/atom-shell",
    npm_config_target: electronVersion,
    npm_config_runtime: "electron",
    HOME: require("os").homedir() + "/.electron-gyp",
  })

  if (arch != null) {
    env.npm_config_arch = arch
  }

  let npmExecPath = process.env.npm_execpath || process.env.NPM_CLI_JS
  const npmExecArgs = ["install"]
  if (npmExecPath == null) {
    npmExecPath = "npm"
  }
  else {
    npmExecArgs.unshift(npmExecPath)
    npmExecPath = process.env.npm_node_execpath || process.env.NODE_EXE || "node"
  }

  return spawn(npmExecPath, npmExecArgs, {
    cwd: appDir,
    stdio: "inherit",
    env: env
  })
}

interface BaseExecOptions {
  cwd?: string
  env?: any
  stdio?: any
}

interface ExecOptions extends BaseExecOptions {
  customFds?: any
  encoding?: string
  timeout?: number
  maxBuffer?: number
  killSignal?: string
}

interface SpawnOptions extends BaseExecOptions {
  custom?: any
  detached?: boolean
}

export function exec(file: string, args?: string[], options?: ExecOptions): BluebirdPromise<Buffer[]> {
  return execFileAsync(file, args, options)
}

export function spawn(command: string, args?: string[], options?: SpawnOptions): BluebirdPromise<any> {
  return new BluebirdPromise<any>((resolve, reject) => {
    const p = _spawn(command, args, options)
    p.on("close", (code: number) => code === 0 ? resolve() : reject(new Error(command + " exited with code " + code)))
  })
}

export function getElectronVersion(packageData: any, filePath: string): string {
  const devDependencies = packageData.devDependencies
  let electronPrebuiltDep = devDependencies == null ? null : devDependencies["electron-prebuilt"]
  if (electronPrebuiltDep == null) {
    const dependencies = packageData.dependencies
    electronPrebuiltDep = dependencies == null ? null : dependencies["electron-prebuilt"]
  }

  if (electronPrebuiltDep == null) {
    throw new Error("Cannot find electron-prebuilt dependency to get electron version in the '" + filePath + "'")
  }
  return electronPrebuiltDep.substring(1)
}


text:
<?php namespace core\base;

abstract class Controller
{
    private $model;

    use \core\traits\ClassMethods;

    public function __construct($model = null)
    {
        self::validateNumArgs(__FUNCTION__, func_num_args(), 0, 1);
        self::validateArgType(__FUNCTION__, $model, 1, ['string', 'object', 'null']);

        $this->setModel($model);
    }

    private function setModel($model)
    {
        $this->model = null;

        if (is_string($model)) {
            $namespace = 'model\\' . str_replace(DS, '\\', $model);
            $this->model = new $namespace;
        }
        if (is_object($model)) {
            $this->model = $model;
        }
    }

    abstract function index();

    protected final function loadModel($model)
    {
        self::validateNumArgs(__FUNCTION__, func_num_args(), 1, 1);
        self::validateArgType(__FUNCTION__, $model, 1, ['string']);

        if (is_string($model)) {
            $namespace = 'model\\' . str_replace(DS, '\\', $model);
            $model = new $namespace;
            return $model;
        }
        return null;
    }

    protected final function model()
    {
        self::validateNumArgs(__FUNCTION__, func_num_args());
        return $this->model;
    }
}

redpajama_set_name: RedPajamaGithub


text:
function [combinedPrior, combinedTransmat, combinedTerm, combinedMu, ...
    combinedSigma, combinedMixmat] = combinehmmparam(hmm, ...
    nSMap, gestureNdx, restNdx)
%%
% Combines pre-stroke, nucleus and post-stroke HMMs together.
%
% ARGS
% prior   - cell array of column vectors.
% term    - cell array of column vectors.
% i   - gesture index;

prior = hmm.prior(gestureNdx, :);
transmat = hmm.transmat(gestureNdx, :);
term = hmm.term(gestureNdx, :);
mu = hmm.mu(gestureNdx, :);
Sigma = hmm.Sigma(gestureNdx, :);
mixmat = hmm.mixmat(gestureNdx, :);

stageNdx = gesturestagendx(nSMap);
nStages = size(stageNdx, 1);

combinedPrior = cat(1, prior{:});
combinedPrior(stageNdx(3, 1) : stageNdx(3, 2)) = 0;
combinedPrior = normalise(combinedPrior);
assert(abs(sum(combinedPrior) - 1) < 1e-9);

totalNumStates = length(combinedPrior);

%% Combine transmat
combinedTransmat = zeros(totalNumStates);
for i = 1 : nStages
  nextStage = mod(i, nStages) + 1;
  fromNdx = stageNdx(i, 1) : stageNdx(i, 2);
  toNdx = stageNdx(nextStage, 1) : stageNdx(nextStage, 2);
  combinedTransmat(fromNdx, toNdx) = term{i} * prior{nextStage}';

  p = 1 - repmat(term{i}, 1, length(fromNdx));
  combinedTransmat(fromNdx, fromNdx) = transmat{i} .* p;
end
% Allow pre-stroke to transit to post-stroke.
combinedTransmat(stageNdx(1, 2) - 2 : stageNdx(1, 2), ...
          stageNdx(3, 1) : stageNdx(3, 1) + 2) = 0.01;
combinedTransmat = mk_stochastic(combinedTransmat);

%% Combine term
combinedTerm = cat(1, term{:});
combinedTerm(stageNdx(1, 1) : stageNdx(2, 2)) = 0;
% Allow pre-stroke to terminate.
combinedTerm(stageNdx(1, 2) - 2 : stageNdx(1, 2)) = ones(3, 1) * 0.01;

if nargout > 3
  combinedMu = cat(2, mu{:});
end

if nargout > 4
  combinedSigma = cat(3, Sigma{:});
  combinedMixmat = cat(1, mixmat{:});
end

end


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

using Microsoft.Build.Utilities;

using ObjectFactories.Services;

namespace ObjectFactories.MsBuild
{
  public class MsBuildLogger : ILog
  {
    #region Member Data
    private readonly TaskLoggingHelper _logging;
    #endregion

    #region MsBuildLogger()
    public MsBuildLogger(TaskLoggingHelper logging)
    {
      _logging = logging;
    }
    #endregion

    #region ILogger Members
    public void Log(string format, params object[] arguments)
    {
      _logging.LogMessage(format, arguments);
    }
    #endregion
  }
}


text:
from collections import OrderedDict

from tg import expose, flash, redirect, validate, config
from pylons import tmpl_context as c
from string import digits, lowercase
from tg.decorators import without_trailing_slash
from webob.exc import HTTPForbidden, HTTPNotFound
from pylons import app_globals as g

from allura import model as M
from allura.controllers import BaseController
from allura.lib import helpers as h
from allura.lib.decorators import require_post
from allura.lib.security import require_authenticated, require_access
from allura.lib.widgets import forms
from allura.lib.plugin import SiteAdminExtension
from allura.app import SitemapEntry

class F(object):
    remove_category_form = forms.RemoveTroveCategoryForm()
    add_category_form = forms.AddTroveCategoryForm()

class TroveCategoryController(BaseController):
    @expose()
    def _lookup(self, trove_cat_id, *remainder):
        cat = M.TroveCategory.query.get(trove_cat_id=int(trove_cat_id))
        if not cat:
            raise HTTPNotFound
        return TroveCategoryController(category=cat), remainder

    def _check_security(self):
        require_authenticated()

        enable_editing = config.get('trovecategories.enableediting', 'false')
        if enable_editing == 'admin':
            with h.push_context(config.get('site_admin_project', 'allura'),
                                neighborhood=config.get('site_admin_project_nbhd', 'Projects')):
                require_access(c.project, 'admin')
        elif enable_editing != 'true':
            raise HTTPForbidden()

    def __init__(self, category=None):
        self.category = category
        super(TroveCategoryController, self).__init__()

    @expose('jinja:allura:templates/trovecategories.html')
    def index(self, **kw):
        if self.category:
            selected_cat = self.category
            l = self.category.subcategories
            hierarchy = []
            temp_cat = self.category.parent_category
            while temp_cat:
                hierarchy = [temp_cat] + hierarchy
                temp_cat = temp_cat.parent_category
        else:
            l = M.TroveCategory.query.find(dict(trove_parent_id=0)).sort('fullname').all()
            selected_cat = None
            hierarchy = []
        return dict(
            categories=l,
            selected_cat=selected_cat,
            hierarchy=hierarchy,
            kw=kw)

    def generate_category(self, category):
        if not category:
            return ()

        children = {
            key: value
            for (key, value) in
            (self.generate_category(child) for child in category.subcategories)
        }

        return category.fullname, OrderedDict(sorted(children.iteritems()))

    @without_trailing_slash
    @expose('jinja:allura:templates/browse_trove_categories.html')
    def browse(self):
        parent_categories = M.TroveCategory.query.find(dict(trove_parent_id=0)).all()
        tree = {
            key: value
            for (key, value) in
            (self.generate_category(child) for child in parent_categories)
        }
        return dict(tree=OrderedDict(sorted(tree.iteritems())))

    @expose()
    @require_post()
    @validate(F.add_category_form, error_handler=index)
    def create(self, **kw):
        name = kw.get('categoryname')
        upper_id = int(kw.get('uppercategory_id', 0))
        shortname = kw.get('shortname', None)

        upper = M.TroveCategory.query.get(trove_cat_id=upper_id)
        if upper_id == 0:
            path = name
            show_as_skill = True
        elif upper is None:
            flash('Invalid upper category.', "error")
            redirect('/categories')
            return
        else:
            path = upper.fullpath + " :: " + name
            show_as_skill = upper.show_as_skill

        newid = max(
            [el.trove_cat_id for el in M.TroveCategory.query.find()]) + 1
        shortname = h.slugify(shortname or name)[1]

        oldcat = M.TroveCategory.query.get(shortname=shortname)
        if oldcat:
            flash('Category "%s" with shortname "%s" already exists.  Try a different, unique shortname' % (name, shortname), "error")
        else:
            category = M.TroveCategory(
                trove_cat_id=newid,
                trove_parent_id=upper_id,
                fullname=name,
                shortname=shortname,
                fullpath=path,
                show_as_skill=show_as_skill)
            if category:
                flash('Category "%s" successfully created.' % name)
            else:
                flash('An error occured while crearing the category.', "error")
        if upper:
            redirect(u'/categories/{}/?categoryname={}&shortname={}'.format(upper.trove_cat_id, name, shortname))
        else:
            redirect(u'/categories/?categoryname={}&shortname={}'.format(name, shortname))

    @expose()
    @require_post()
    @validate(F.remove_category_form, error_handler=index)
    def remove(self, **kw):
        cat = M.TroveCategory.query.get(trove_cat_id=int(kw['categoryid']))
        if cat.trove_parent_id:
            parent = M.TroveCategory.query.get(
                trove_cat_id=cat.trove_parent_id)
            redirecturl = '/categories/%s' % parent.trove_cat_id
        else:
            redirecturl = '/categories'
        if len(cat.subcategories) > 0:
            m = "This category contains at least one sub-category, "
            m = m + "therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.User.withskill(cat).count() > 0:
            m = "This category is used as a skill by at least a user, "
            m = m + "therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_root_database=cat._id):
            m = "This category is used as a database by at least a project, "
            m = m + "therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_developmentstatus=cat._id):
            m = "This category is used as development status by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_audience=cat._id):
            m = "This category is used as intended audience by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_license=cat._id):
            m = "This category is used as a license by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_os=cat._id):
            m = "This category is used as operating system by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_language=cat._id):
            m = "This category is used as programming language by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_topic=cat._id):
            m = "This category is used as a topic by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_natlanguage=cat._id):
            m = "This category is used as a natural language by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        if M.Project.query.get(trove_environment=cat._id):
            m = "This category is used as an environment by at least a "
            m = m + "project, therefore it can't be removed."
            flash(m, "error")
            redirect(redirecturl)
            return

        M.TroveCategory.delete(cat)

        flash('Category removed.')
        redirect(redirecturl)

class TroveCategorySiteAdminExtension(SiteAdminExtension):
    def update_sidebar_menu(self, links):
        enable_editing = config.get('trovecategories.enableediting', 'false')
        if enable_editing in ('admin', 'true'):
            links.append(SitemapEntry('Troves', '/categories',
                                      ui_icon=g.icons['admin']))


text:
require 'rubygems'
require 'test/unit'

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'geo_store_client'
require 'linccer_client'

class Test::Unit::TestCase
end


text:
"""
MicroBar - Low-pressure bar graphs for Python.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

BARS_BLOCK = ("_", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█")

class MicroBar(object):

    def __init__(self, minimum, maximum, bars=BARS_BLOCK):
        """
        @minimum: Minimum value for this bar graph
        @maximum: Maximum value for this bar graph
        @bars: Steps to be used with this bar graph

        Since bars is given at instanciation and get_bar only reads it, this
        class is thread-safe.
        """
        if not type(bars) is tuple:
            raise TypeError('Parameter "bars" must be of type tuple.')

        if not type(minimum) in [int, float]:
            raise TypeError(
                'Parameter "minimum" must be of type "int" or "float".')

        if not type(maximum) in [int, float]:
            raise TypeError(
                'Parameter "maximum" must be of type "int" or "float".')

        if not minimum < maximum:
            raise ValueError(
                'Parameter "minimum" must be smaller than "maximum".')

        self.minimum = minimum
        self.maximum = maximum
        self.bars = bars

    def get_bar(self, value):
        """
        Return the bar corresponding to the given value.
        """

        # norm current value over minimum to 1
        ratio = (value - self.minimum) / (self.maximum - self.minimum)

        # scale ratio to ticks
        index = int(round(ratio * (len(self.bars) - 1)))

        # get bar corresponding to the given value
        return self.bars[index]


text:
<resources>
    <string name="app_name">TimeDateFormaterTDTExample</string>
</resources>


text:
Lampy
=====

Control RGB lights from a Spark Core


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Widget.AppTheme.SearchView" parent="android:style/Widget.Material.SearchView">
        <item name="android:searchIcon">@android:color/transparent</item>
        <item name="android:searchHintIcon">@android:color/transparent</item>
        <item name="android:queryBackground">@android:color/transparent</item>
        <item name="android:submitBackground">@android:color/transparent</item>
    </style>
</resources>


text:
#ifndef BASIC_ROUTING_INTERFACE_H
#define BASIC_ROUTING_INTERFACE_H

#include "../DataStructures/RawRouteData.h"
#include "../DataStructures/SearchEngineData.h"
#include "../DataStructures/TurnInstructions.h"
#include "../Util/ContainerUtils.h"
#include "../Util/SimpleLogger.h"

#include <boost/assert.hpp>

#include <stack>

SearchEngineData::SearchEngineHeapPtr SearchEngineData::forwardHeap;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::backwardHeap;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::forwardHeap2;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::backwardHeap2;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::forwardHeap3;
SearchEngineData::SearchEngineHeapPtr SearchEngineData::backwardHeap3;

template <class DataFacadeT> class BasicRoutingInterface
{
  private:
    typedef typename DataFacadeT::EdgeData EdgeData;

  protected:
    DataFacadeT *facade;

  public:
    BasicRoutingInterface() = delete;
    BasicRoutingInterface(const BasicRoutingInterface &) = delete;
    explicit BasicRoutingInterface(DataFacadeT *facade) : facade(facade) {}
    virtual ~BasicRoutingInterface() {};

    inline void RoutingStep(SearchEngineData::QueryHeap &forward_heap,
                            SearchEngineData::QueryHeap &reverse_heap,
                            NodeID *middle_node_id,
                            int *upper_bound,
                            const int min_edge_offset,
                            const bool forward_direction) const
    {
        const NodeID node = forward_heap.DeleteMin();
        const int distance = forward_heap.GetKey(node);

        // const NodeID parentnode = forward_heap.GetData(node).parent;
        // SimpleLogger().Write() << (forward_direction ? "[fwd] " : "[rev] ") << "settled edge (" << parentnode << "," << node << "), dist: " << distance;

        if (reverse_heap.WasInserted(node))
        {
            const int new_distance = reverse_heap.GetKey(node) + distance;
            if (new_distance < *upper_bound)
            {
                if (new_distance >= 0)
                {
                    *middle_node_id = node;
                    *upper_bound = new_distance;
                //     SimpleLogger().Write() << "accepted middle node " << node << " at distance " << new_distance;
                // } else {
                //     SimpleLogger().Write() << "discared middle node " << node << " at distance " << new_distance;
                }
            }
        }

        if (distance + min_edge_offset > *upper_bound)
        {
            // SimpleLogger().Write() << "min_edge_offset: " << min_edge_offset;
            forward_heap.DeleteAll();
            return;
        }

        // Stalling
        for (const auto edge : facade->GetAdjacentEdgeRange(node))
        {
            const EdgeData &data = facade->GetEdgeData(edge);
            const bool reverse_flag = ((!forward_direction) ? data.forward : data.backward);
            if (reverse_flag)
            {
                const NodeID to = facade->GetTarget(edge);
                const int edge_weight = data.distance;

                BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid");

                if (forward_heap.WasInserted(to))
                {
                    if (forward_heap.GetKey(to) + edge_weight < distance)
                    {
                        return;
                    }
                }
            }
        }

        for (const auto edge : facade->GetAdjacentEdgeRange(node))
        {
            const EdgeData &data = facade->GetEdgeData(edge);
            bool forward_directionFlag = (forward_direction ? data.forward : data.backward);
            if (forward_directionFlag)
            {

                const NodeID to = facade->GetTarget(edge);
                const int edge_weight = data.distance;

                BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid");
                const int to_distance = distance + edge_weight;

                // New Node discovered -> Add to Heap + Node Info Storage
                if (!forward_heap.WasInserted(to))
                {
                    forward_heap.Insert(to, to_distance, node);
                }
                // Found a shorter Path -> Update distance
                else if (to_distance < forward_heap.GetKey(to))
                {
                    // new parent
                    forward_heap.GetData(to).parent = node;
                    forward_heap.DecreaseKey(to, to_distance);
                }
            }
        }
    }

    inline void UnpackPath(const std::vector<NodeID> &packed_path,
                           const PhantomNodes &phantom_node_pair,
                           std::vector<PathData> &unpacked_path) const
    {
        const bool start_traversed_in_reverse =
            (packed_path.front() != phantom_node_pair.source_phantom.forward_node_id);
        const bool target_traversed_in_reverse =
            (packed_path.back() != phantom_node_pair.target_phantom.forward_node_id);

        const unsigned packed_path_size = static_cast<unsigned>(packed_path.size());
        std::stack<std::pair<NodeID, NodeID>> recursion_stack;

        // We have to push the path in reverse order onto the stack because it's LIFO.
        for (unsigned i = packed_path_size - 1; i > 0; --i)
        {
            recursion_stack.emplace(packed_path[i - 1], packed_path[i]);
        }

        std::pair<NodeID, NodeID> edge;
        while (!recursion_stack.empty())
        {
            /*
            Graphical representation of variables:

            edge.first         edge.second
                *------------------>*
                       edge_id
            */
            edge = recursion_stack.top();
            recursion_stack.pop();

            // facade->FindEdge does not suffice here in case of shortcuts.
            // The above explanation unclear? Think!
            EdgeID smaller_edge_id = SPECIAL_EDGEID;
            int edge_weight = std::numeric_limits<EdgeWeight>::max();
            for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
            {
                const int weight = facade->GetEdgeData(edge_id).distance;
                if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
                    facade->GetEdgeData(edge_id).forward)
                {
                    smaller_edge_id = edge_id;
                    edge_weight = weight;
                }
            }

            /*
                Graphical representation of variables:

                edge.first         edge.second
                    *<------------------*
                           edge_id
            */
            if (SPECIAL_EDGEID == smaller_edge_id)
            {
                for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
                {
                    const int weight = facade->GetEdgeData(edge_id).distance;
                    if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
                        facade->GetEdgeData(edge_id).backward)
                    {
                        smaller_edge_id = edge_id;
                        edge_weight = weight;
                    }
                }
            }
            BOOST_ASSERT_MSG(edge_weight != INVALID_EDGE_WEIGHT, "edge id invalid");

            const EdgeData &ed = facade->GetEdgeData(smaller_edge_id);
            if (ed.shortcut)
            { // unpack
                const NodeID middle_node_id = ed.id;
                // again, we need to this in reversed order
                recursion_stack.emplace(middle_node_id, edge.second);
                recursion_stack.emplace(edge.first, middle_node_id);
            }
            else
            {
                BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut");
                unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id);
                const TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id);

                if (!facade->EdgeIsCompressed(ed.id))
                {
                    BOOST_ASSERT(!facade->EdgeIsCompressed(ed.id));
                    unpacked_path.emplace_back(facade->GetGeometryIndexForEdgeID(ed.id),
                                               name_index,
                                               turn_instruction,
                                               ed.distance);
                }
                else
                {
                    std::vector<unsigned> id_vector;
                    facade->GetUncompressedGeometry(facade->GetGeometryIndexForEdgeID(ed.id),
                                                    id_vector);

                    const std::size_t start_index =
                        (unpacked_path.empty()
                             ? ((start_traversed_in_reverse)
                                    ? id_vector.size() -
                                          phantom_node_pair.source_phantom.fwd_segment_position - 1
                                    : phantom_node_pair.source_phantom.fwd_segment_position)
                             : 0);
                    const std::size_t end_index = id_vector.size();

                    BOOST_ASSERT(start_index >= 0);
                    BOOST_ASSERT(start_index <= end_index);
                    for (std::size_t i = start_index; i < end_index; ++i)
                    {
                        unpacked_path.emplace_back(id_vector[i], name_index, TurnInstruction::NoTurn, 0);
                    }
                    unpacked_path.back().turn_instruction = turn_instruction;
                    unpacked_path.back().segment_duration = ed.distance;
                }
            }
        }
        if (SPECIAL_EDGEID != phantom_node_pair.target_phantom.packed_geometry_id)
        {
            std::vector<unsigned> id_vector;
            facade->GetUncompressedGeometry(phantom_node_pair.target_phantom.packed_geometry_id,
                                            id_vector);
            const bool is_local_path = (phantom_node_pair.source_phantom.packed_geometry_id ==
                                        phantom_node_pair.target_phantom.packed_geometry_id) &&
                                       unpacked_path.empty();

            std::size_t start_index = 0;
            if (is_local_path)
            {
                start_index = phantom_node_pair.source_phantom.fwd_segment_position;
                if (target_traversed_in_reverse)
                {
                    start_index =
                        id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position;
                }
            }

            std::size_t end_index = phantom_node_pair.target_phantom.fwd_segment_position;
            if (target_traversed_in_reverse)
            {
                std::reverse(id_vector.begin(), id_vector.end());
                end_index =
                    id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position;
            }

            if (start_index > end_index)
            {
                start_index = std::min(start_index, id_vector.size()-1);
            }

            for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i))
            {
                BOOST_ASSERT(i < id_vector.size());
                unpacked_path.emplace_back(PathData{id_vector[i],
                                           phantom_node_pair.target_phantom.name_id,
                                           TurnInstruction::NoTurn,
                                           0});
            }
        }

        // there is no equivalent to a node-based node in an edge-expanded graph.
        // two equivalent routes may start (or end) at different node-based edges
        // as they are added with the offset how much "distance" on the edge
        // has already been traversed. Depending on offset one needs to remove
        // the last node.
        if (unpacked_path.size() > 1)
        {
            const std::size_t last_index = unpacked_path.size() - 1;
            const std::size_t second_to_last_index = last_index - 1;

            // looks like a trivially true check but tests for underflow
            BOOST_ASSERT(last_index > second_to_last_index);

            if (unpacked_path[last_index].node == unpacked_path[second_to_last_index].node)
            {
                unpacked_path.pop_back();
            }
            BOOST_ASSERT(!unpacked_path.empty());
        }
    }

    inline void UnpackEdge(const NodeID s, const NodeID t, std::vector<NodeID> &unpacked_path) const
    {
        std::stack<std::pair<NodeID, NodeID>> recursion_stack;
        recursion_stack.emplace(s, t);

        std::pair<NodeID, NodeID> edge;
        while (!recursion_stack.empty())
        {
            edge = recursion_stack.top();
            recursion_stack.pop();

            EdgeID smaller_edge_id = SPECIAL_EDGEID;
            int edge_weight = std::numeric_limits<EdgeWeight>::max();
            for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
            {
                const int weight = facade->GetEdgeData(edge_id).distance;
                if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
                    facade->GetEdgeData(edge_id).forward)
                {
                    smaller_edge_id = edge_id;
                    edge_weight = weight;
                }
            }

            if (SPECIAL_EDGEID == smaller_edge_id)
            {
                for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
                {
                    const int weight = facade->GetEdgeData(edge_id).distance;
                    if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
                        facade->GetEdgeData(edge_id).backward)
                    {
                        smaller_edge_id = edge_id;
                        edge_weight = weight;
                    }
                }
            }
            BOOST_ASSERT_MSG(edge_weight != std::numeric_limits<EdgeWeight>::max(), "edge weight invalid");

            const EdgeData &ed = facade->GetEdgeData(smaller_edge_id);
            if (ed.shortcut)
            { // unpack
                const NodeID middle_node_id = ed.id;
                // again, we need to this in reversed order
                recursion_stack.emplace(middle_node_id, edge.second);
                recursion_stack.emplace(edge.first, middle_node_id);
            }
            else
            {
                BOOST_ASSERT_MSG(!ed.shortcut, "edge must be shortcut");
                unpacked_path.emplace_back(edge.first);
            }
        }
        unpacked_path.emplace_back(t);
    }

    inline void RetrievePackedPathFromHeap(const SearchEngineData::QueryHeap &forward_heap,
                                           const SearchEngineData::QueryHeap &reverse_heap,
                                           const NodeID middle_node_id,
                                           std::vector<NodeID> &packed_path) const
    {
        RetrievePackedPathFromSingleHeap(forward_heap, middle_node_id, packed_path);
        std::reverse(packed_path.begin(), packed_path.end());
        packed_path.emplace_back(middle_node_id);
        RetrievePackedPathFromSingleHeap(reverse_heap, middle_node_id, packed_path);
    }

    inline void RetrievePackedPathFromSingleHeap(const SearchEngineData::QueryHeap &search_heap,
                                                 const NodeID middle_node_id,
                                                 std::vector<NodeID> &packed_path) const
    {
        NodeID current_node_id = middle_node_id;
        while (current_node_id != search_heap.GetData(current_node_id).parent)
        {
            current_node_id = search_heap.GetData(current_node_id).parent;
            packed_path.emplace_back(current_node_id);
        }
    }
};

#endif // BASIC_ROUTING_INTERFACE_H


text:
import { IHookEngine } from '@ionic/cli-utils';
import { IonicNamespace } from './commands';
export declare const namespace: IonicNamespace;
export declare function registerHooks(hooks: IHookEngine): void;
export declare function run(pargv: string[], env: {
    [k: string]: string;
}): Promise<void>;


text:
--------------------------------
-- Get the opengl view port rectangle.
-- @function [parent=#GLView] getViewPortRect
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
--  only works on ios platform
-- @function [parent=#GLView] setContentScaleFactor
-- @param self
-- @param #float scaleFactor
-- @return bool#bool ret (return value: bool)

--------------------------------
--
-- @function [parent=#GLView] getContentScaleFactor
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Open or close IME keyboard , subclass must implement this method.
-- @function [parent=#GLView] setIMEKeyboardState
-- @param self
-- @param #bool open
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
-- Set Scissor rectangle with points.
-- @function [parent=#GLView] setScissorInPoints
-- @param self
-- @param #float x
-- @param #float y
-- @param #float w
-- @param #float h
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
--
-- @function [parent=#GLView] getViewName
-- @param self
-- @return string#string ret (return value: string)

--------------------------------
--  Get whether opengl render system is ready, subclass must implement this method.
-- @function [parent=#GLView] isOpenGLReady
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Get scale factor of the vertical direction.
-- @function [parent=#GLView] getScaleY
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
-- Get scale factor of the horizontal direction.
-- @function [parent=#GLView] getScaleX
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
-- Get the visible origin point of opengl viewport.
-- @function [parent=#GLView] getVisibleOrigin
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)

--------------------------------
-- Get the frame size of EGL view.

-- In general, it returns the screen size since the EGL view is a fullscreen view.
-- @function [parent=#GLView] getFrameSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
--  Set and get zoom factor for frame. This two methods are for

-- debugging big resolution (e.g.new ipad) app on desktop.
-- @function [parent=#GLView] setFrameZoomFactor
-- @param self
-- @param #float zoomFactor
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
--
-- @function [parent=#GLView] getFrameZoomFactor
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  Get design resolution size.

-- Default resolution size is the same as 'getFrameSize'.
-- @function [parent=#GLView] getDesignResolutionSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
--
-- @function [parent=#GLView] windowShouldClose
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Set the design resolution size.

-- param width Design resolution width.

-- param height Design resolution height.

-- param resolutionPolicy The resolution policy desired, you may choose:

-- [1] EXACT_FIT Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.

-- [2] NO_BORDER Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.

-- [3] SHOW_ALL  Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
-- @function [parent=#GLView] setDesignResolutionSize
-- @param self
-- @param #float width
-- @param #float height
-- @param #int resolutionPolicy
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
--  returns the current Resolution policy
-- @function [parent=#GLView] getResolutionPolicy
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
--  returns whether or not the view is in Retina Display mode
-- @function [parent=#GLView] isRetinaDisplay
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- Set opengl view port rectangle with points.
-- @function [parent=#GLView] setViewPortInPoints
-- @param self
-- @param #float x
-- @param #float y
-- @param #float w
-- @param #float h
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
-- Get the current scissor rectangle
-- @function [parent=#GLView] getScissorRect
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
--  Get retina factor
-- @function [parent=#GLView] getRetinaFactor
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
--
-- @function [parent=#GLView] setViewName
-- @param self
-- @param #string viewname
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
-- Get the visible rectangle of opengl viewport.
-- @function [parent=#GLView] getVisibleRect
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
-- Get the visible area size of opengl viewport.
-- @function [parent=#GLView] getVisibleSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- Get whether GL_SCISSOR_TEST is enable
-- @function [parent=#GLView] isScissorEnabled
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
--
-- @function [parent=#GLView] pollEvents
-- @param self
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
--
-- @function [parent=#GLView] setGLContextAttrs
-- @param self
-- @param #GLContextAttrs glContextAttrs
-- @return GLView#GLView self (return value: cc.GLView)

--------------------------------
--
-- @function [parent=#GLView] getGLContextAttrs
-- @param self
-- @return GLContextAttrs#GLContextAttrs ret (return value: GLContextAttrs)

return nil


text:
//
//  WFGarminFR405Manager.h
//  WFConnector
//
//  Created by Michael Moore on 6/17/10.
//  Copyright 2010 Wahoo Fitness. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <WFConnector/WFFitDeviceManager.h>

///////////////////////////////////////////////////////////////////////////////
//
// WFGarminFR405Manager Interface Declaration.
//

/**
 * Provides a means of communicating with, and transferring data from a
 * Garmin Frontrunner 405 device.
 */
@interface WFGarminFR405Manager : WFFitDeviceManager
{
}

@end


text:
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces

namespace FireRatingCloud
{
  /// <summary>
  /// Import updated FireRating parameter values
  /// from external database.
  /// </summary>
  [Transaction( TransactionMode.Manual )]
  public class Cmd_3_ImportSharedParameterValues
    : IExternalCommand
  {
    /// <summary>
    /// Test retrieving only recently modified records.
    /// </summary>
    static uint _test_timestamp = 0;

    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements )
    {
      UIApplication uiapp = commandData.Application;
      Document doc = uiapp.ActiveUIDocument.Document;

      // Determine custom project identifier.

      string project_id = Util.GetProjectIdentifier( doc );

      // Retrieve all doors referencing this project,
      // optionally modified after the given timestamp.

      List<FireRating.DoorData> doors
        = DbAccessor.GetDoorRecords(
          project_id, _test_timestamp );

      Result rc = Result.Succeeded;

      if ( null != doors && 0 < doors.Count )
      {
        rc = BimUpdater.UpdateBim( doc, doors, ref message )
          ? Result.Succeeded
          : Result.Failed;
      }
      return rc;
    }
  }
}


text: First app made by


text:
var models = require('../models');

exports.viewnotes = function(req, res) {
	if(req.session.email && req.session.loggedin)
	{
		console.log("The email in session is " + req.session.email);
		res.render('my_notes', {
			'notes': req.session.notes
		});
	}
	else // user is not logged in
	{
		res.render('index', {'error':false})
	}
};

exports.pullnote = function(req, res) {
	if(req.session.email && req.session.loggedin)
	{
		console.log("The email in session is " + req.session.email);
		var current_class_i = 0;
		console.log("Looking for notes for " + req.params.class);
		while(current_class_i < req.session.notes.length)
		{
			if(req.params.class == req.session.notes[current_class_i].class)
			{
				break;
			}
			current_class_i++;
		}
		console.log("Found class at " + current_class_i);
		console.log("Out of " + req.session.notes.length);
		res.render("edit_note", {
				'username': req.session.username,
				'class': req.params.class,
				'notes': req.session.notes,
				'update_note': req.session.notes[current_class_i].note,
				'current_class_i': current_class_i
		});
	}
	else // user is not logged in
	{
		res.render('index', {'error':false})
	}
};

exports.updatenote = function(req, res) {
	if(req.session.email && req.session.loggedin)
	{
		console.log("The email in session is " + req.session.email);

		req.session.notes[req.body.current_class_i].note = req.body.text;
		var mykey = "notes." + req.body.current_class_i + ".note";
		var myvalue = req.session.notes[req.body.current_class_i].note;
		var update = {$set: {}};
		update.$set[mykey] = myvalue;
		models.User.update({"email": req.session.email}, update).exec(afterAdd);
		function afterAdd(err) {
			if(err) { console.log(err); }
			console.log("Added a note.");
			res.render("my_notes", {
			'username': req.session.username,
			'notes': req.session.notes
			});

		};
	}
	else // user is not logged in
	{
		res.render('index', {'error':false})
	}
};

exports.viewall = function(req, res) {
	if(req.session.email && req.session.loggedin)
	{
		console.log("The email in session is " + req.session.email);
		console.log("Looking for notes for " + req.params.classname + "...");
		var new_notes = {};
		models.User.find({"notes.class": req.params.classname}).exec(afterfind);
		function afterfind(err, q_user) {
			if(err) { console.log(err); }
			console.log("Gathering all notes.");
			var new_i = 0;
			var i = 0;
			while(i < q_user.length)
			{
				var j = 0;
				while(j < q_user[i].notes.length)
				{
					if(q_user[i].notes[j].class == req.params.classname)
					{
						new_notes[new_i] = {"class": req.params.classname, "note": q_user[i].notes[j].note};
						new_i++;
						break;
					}
					j++;
				}
				i++;
			}
			res.render("class", {
			'username': req.session.username,
			'notes': new_notes,
			'classname': req.params.classname
			});
		};
	}
	else // user is not logged in
	{
		res.render('index', {'error':false})
	}
}


text:
import datetime
import logging
import os
import shutil

import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import (
    ModelCheckpoint,
    TensorBoard,
)
from tensorflow import feature_column as fc
from tensorflow.keras.activations import relu
from tensorflow.keras.layers import (
    Dense,
    DenseFeatures,
    Input,
    Lambda,
)
from tensorflow.keras.models import Model

logging.info(tf.version.VERSION)

CSV_COLUMNS = [
        'fare_amount',
        'pickup_datetime',
        'pickup_longitude',
        'pickup_latitude',
        'dropoff_longitude',
        'dropoff_latitude',
        'passenger_count',
        'key',
]
LABEL_COLUMN = 'fare_amount'
DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']]
DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

def features_and_labels(row_data):
    for unwanted_col in ['key']:
        row_data.pop(unwanted_col)
    label = row_data.pop(LABEL_COLUMN)
    return row_data, label

def load_dataset(pattern, batch_size, num_repeat):
    dataset = tf.data.experimental.make_csv_dataset(
        file_pattern=pattern,
        batch_size=batch_size,
        column_names=CSV_COLUMNS,
        column_defaults=DEFAULTS,
        num_epochs=num_repeat,
    )
    return dataset.map(features_and_labels)

def create_train_dataset(pattern, batch_size):
    dataset = load_dataset(pattern, batch_size, num_repeat=None)
    return dataset.prefetch(1)

def create_eval_dataset(pattern, batch_size):
    dataset = load_dataset(pattern, batch_size, num_repeat=1)
    return dataset.prefetch(1)

def parse_datetime(s):
    if type(s) is not str:
        s = s.numpy().decode('utf-8')
    return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S %Z")

def euclidean(params):
    lon1, lat1, lon2, lat2 = params
    londiff = lon2 - lon1
    latdiff = lat2 - lat1
    return tf.sqrt(londiff*londiff + latdiff*latdiff)

def get_dayofweek(s):
    ts = parse_datetime(s)
    return DAYS[ts.weekday()]

@tf.function
def dayofweek(ts_in):
    return tf.map_fn(
        lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string),
        ts_in
    )

@tf.function
def fare_thresh(x):
    return 60 * relu(x)

def transform(inputs, NUMERIC_COLS, STRING_COLS, nbuckets):
    # Pass-through columns
    transformed = inputs.copy()
    del transformed['pickup_datetime']

    feature_columns = {
        colname: fc.numeric_column(colname)
        for colname in NUMERIC_COLS
    }

    # Scaling longitude from range [-70, -78] to [0, 1]
    for lon_col in ['pickup_longitude', 'dropoff_longitude']:
        transformed[lon_col] = Lambda(
            lambda x: (x + 78)/8.0,
            name='scale_{}'.format(lon_col)
        )(inputs[lon_col])

    # Scaling latitude from range [37, 45] to [0, 1]
    for lat_col in ['pickup_latitude', 'dropoff_latitude']:
        transformed[lat_col] = Lambda(
            lambda x: (x - 37)/8.0,
            name='scale_{}'.format(lat_col)
        )(inputs[lat_col])

    # Adding Euclidean dist (no need to be accurate: NN will calibrate it)
    transformed['euclidean'] = Lambda(euclidean, name='euclidean')([
        inputs['pickup_longitude'],
        inputs['pickup_latitude'],
        inputs['dropoff_longitude'],
        inputs['dropoff_latitude']
    ])
    feature_columns['euclidean'] = fc.numeric_column('euclidean')

    # hour of day from timestamp of form '2010-02-08 09:17:00+00:00'
    transformed['hourofday'] = Lambda(
        lambda x: tf.strings.to_number(
            tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32),
        name='hourofday'
    )(inputs['pickup_datetime'])
    feature_columns['hourofday'] = fc.indicator_column(
        fc.categorical_column_with_identity(
            'hourofday', num_buckets=24))

    latbuckets = np.linspace(0, 1, nbuckets).tolist()
    lonbuckets = np.linspace(0, 1, nbuckets).tolist()
    b_plat = fc.bucketized_column(
        feature_columns['pickup_latitude'], latbuckets)
    b_dlat = fc.bucketized_column(
            feature_columns['dropoff_latitude'], latbuckets)
    b_plon = fc.bucketized_column(
            feature_columns['pickup_longitude'], lonbuckets)
    b_dlon = fc.bucketized_column(
            feature_columns['dropoff_longitude'], lonbuckets)
    ploc = fc.crossed_column(
            [b_plat, b_plon], nbuckets * nbuckets)
    dloc = fc.crossed_column(
            [b_dlat, b_dlon], nbuckets * nbuckets)
    pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4)
    feature_columns['pickup_and_dropoff'] = fc.embedding_column(
            pd_pair, 100)

    return transformed, feature_columns

def rmse(y_true, y_pred):
    return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))

def build_dnn_model(nbuckets, nnsize):
    # input layer is all float except for pickup_datetime which is a string
    STRING_COLS = ['pickup_datetime']
    NUMERIC_COLS = (
            set(CSV_COLUMNS) - set([LABEL_COLUMN, 'key']) - set(STRING_COLS)
    )
    inputs = {
        colname: Input(name=colname, shape=(), dtype='float32')
        for colname in NUMERIC_COLS
    }
    inputs.update({
        colname: Input(name=colname, shape=(), dtype='string')
        for colname in STRING_COLS
    })

    # transforms
    transformed, feature_columns = transform(
        inputs, NUMERIC_COLS, STRING_COLS, nbuckets=nbuckets)
    dnn_inputs = DenseFeatures(feature_columns.values())(transformed)

    x = dnn_inputs
    for layer, neurons in enumerate(nnsize):
        x = Dense(neurons, activation='relu', name='h{}'.format(layer))(x)
    output = Dense(1, name='fare')(x)

    model = Model(inputs, output)
    model.compile(optimizer='adam', loss='mse', metrics=[rmse, 'mse'])
    return model

def train_and_evaluate(hparams):
    batch_size = hparams['batch_size']
    eval_data_path = hparams['eval_data_path']
    nnsize = hparams['nnsize']
    nbuckets = hparams['nbuckets']
    num_evals = hparams['num_evals']
    num_examples_to_train_on = hparams['num_examples_to_train_on']
    output_dir = hparams['output_dir']
    train_data_path = hparams['train_data_path']

    timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    savedmodel_dir = os.path.join(output_dir, 'export/savedmodel')
    model_export_path = os.path.join(savedmodel_dir, timestamp)
    checkpoint_path = os.path.join(output_dir, 'checkpoints')
    tensorboard_path = os.path.join(output_dir, 'tensorboard')

    if tf.io.gfile.exists(output_dir):
        tf.io.gfile.rmtree(output_dir)

    model = build_dnn_model(nbuckets, nnsize)
    logging.info(model.summary())

    trainds = create_train_dataset(train_data_path, batch_size)
    evalds = create_eval_dataset(eval_data_path, batch_size)

    steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals)

    checkpoint_cb = ModelCheckpoint(
        checkpoint_path,
        save_weights_only=True,
        verbose=1
    )
    tensorboard_cb = TensorBoard(tensorboard_path)

    history = model.fit(
        trainds,
        validation_data=evalds,
        epochs=num_evals,
        steps_per_epoch=max(1, steps_per_epoch),
        verbose=2,  # 0=silent, 1=progress bar, 2=one line per epoch
        callbacks=[checkpoint_cb, tensorboard_cb]
    )

    # Exporting the model with default serving function.
    tf.saved_model.save(model, model_export_path)
    return history


text:
package elasta.orm.delete.ex;

/**
 * Created by sohan on 3/12/2017.
 */
final public class TableDataMapException extends RuntimeException {
    public TableDataMapException(String msg) {
        super(msg);
    }
}


text:
<?php

namespace DIISH\SComDisBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * OutbreakRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class OutbreakRepository extends EntityRepository
{
    /**
     * Save outbreak
     *
     * @param Outbreak $outbreak
     * @throws \InvalidArgumentException
     */
    public function saveOutbreak(Outbreak $outbreak)
    {
        $this->isExist_EX($outbreak);

        $manager = $this->getEntityManager();
        $manager->persist($outbreak);

        foreach ($outbreak->outbreakItems as $item ) {
            $item->setOutbreak($outbreak);
            $manager->persist($item);
        }

        $manager->flush();
    }

    /**
     * Check whether the outbreak already exists or not
     *
     * @param Outbreak $outbreak
     * @return boolean
     */
    public function isExist(Outbreak $outbreak)
    {
        $other = $this->findOneBy(array(
            'weekOfYear'    => $outbreak->getWeekOfYear(),
            'year'          => $outbreak->getYear(),
            'sentinelSite'  => $outbreak->getSentinelSite()->getId(),
            'clinic'        => $outbreak->getClinic()->getId(),
            'syndrome'      => $outbreak->getSyndrome()->getId(),
        ));

        if ($other) {
            if ($other->getId() === $outbreak->getId())
                return false;
            else
                return true;
        }

        return false;
    }

    /**
     * Check whether the outbreak already exists or not
     *
     * @param Outbreak $outbreak
     * @throws \InvalidArgumentException
     */
    public function isExist_EX(Outbreak $outbreak)
    {
        if ($this->isExist($outbreak)) {
            $message = 'Error: This outbreak is already exist. '.
                            $outbreak->getUniqueTitle();
            throw new \InvalidArgumentException($message);
        }
    }

    /**
     * Delete outbreak
     *
     * @param Outbreak $outbreak
     * @throws \InvalidArgumentException
     */
    public function deleteOutbreak($id)
    {
        $outbreak = $this->find($id);
        if (!$outbreak) {
            throw new \InvalidArgumentException('Error: The outbreak is not found.');
        }

        $manager = $this->getEntityManager();

        foreach ($outbreak->outbreakItems as $item ) {
            $manager->remove($item);
        }

        $manager->remove($outbreak);
        $manager->flush();
    }
}


text:
@protocol ILabel;

@protocol ILabels < NSObject>

- (id<ILabel>)addNew:(NSString *)name withNSString:(NSString *)text;

- (void)add:(NSString *)key withILabel:(id<ILabel>)value;
- (void)add:(NSString *)key withILabel:(id<ILabel>)value withInt:(int)index;
- (void)remove:(int)index;
- (void)removeWithNSString:(NSString *)key;
- (NSMutableArray*)getItems;
- (int)getCount;
- (void)clear;
- (BOOL)containsKey:(NSString *)key;
- (BOOL)containsValue:(id<ILabel>)value;
- (id)getEnumerator;
- (id<ILabel>)get___idxWithNSString:(NSString *)key;
- (void)set___idxWithNSString:(NSString *)key withILabel:(id<ILabel>)value;
-(id<ILabel>)get___idxWithId:(id)key ;
-(id)get___idxwithint:(NSNumber *) key;
- (void)set___idxWithId:(NSString *)key withILabel:(id<ILabel>)value;
@end

// _ILabels_H_


text:
import {Component, EventEmitter, Input, Output, OnChanges, ChangeDetectionStrategy} from '@angular/core';
import {toBoolean} from '../util/util';

export type NglPage = { number: number | string, disabled?: boolean };

@Component({
  selector: 'ngl-pagination',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './pagination.pug',
  exportAs: 'nglPagination',
})
export class NglPagination implements OnChanges {

  pages: NglPage[] = [];

  current: number;
  @Input() set page(page: number | string) {
    this.current = +page;
  }
  @Output() pageChange = new EventEmitter<number>();

  @Input() total: number | string;
  @Input() perPage: number | string = 10;
  @Input() limit: number | string = 0;
  @Input() boundaryNumbers: number = 0;
  @Input() firstText = 'First';
  @Input() previousText = 'Previous';
  @Input() nextText = 'Next';
  @Input() lastText = 'Last';

  @Input() set boundaryLinks(boundaryLinks: string | boolean) {
    this._boundaryLinks = toBoolean(boundaryLinks);
  }
  get boundaryLinks() {
    return this._boundaryLinks;
  }

  private totalPages: number;
  private _boundaryLinks = false;

  hasPrevious() {
    return this.current > 1;
  }

  hasNext() {
    return this.current < this.totalPages;
  }

  goto(page: number) {
    if (page === this.current) return;
    this.pageChange.emit(+page);
  }

  ngOnChanges(changes?: any) {
    this.totalPages = Math.ceil(+this.total / +this.perPage);

    const { start, end } = this.limits();

    this.pages = this.getPageArray(start, end);

    if (this.boundaryNumbers > 0) {
      if (start > 1) {
        const preGap = this.getPageArray(1, Math.min(start - 1, this.boundaryNumbers));
        const lastGapNumber = +preGap[preGap.length - 1].number;
        if (lastGapNumber < start - 1) {
          this.pages.unshift(this.getGapPage(lastGapNumber, start));
        }
        this.pages.unshift(...preGap);
      }

      if (end < this.totalPages) {
        const postGap = this.getPageArray(Math.max(this.totalPages - this.boundaryNumbers + 1, end + 1), this.totalPages);
        const firstGapNumber = +postGap[0].number;
        if (firstGapNumber > end + 1) {
          this.pages.push(this.getGapPage(end, firstGapNumber));
        }
        this.pages.push(...postGap);
      }
    }

    if (this.current > this.totalPages) {
      setTimeout(() => this.goto(this.totalPages));
    } else if (!this.current && this.totalPages > 0) {
      setTimeout(() => this.goto(1));
    }
  }

  pageTrackBy(index: number, page: NglPage) {
    return page.number;
  }

  get start(): number {
    return Math.min(Math.max(1 + (+this.current - 1) * +this.perPage, 0), +this.total);
  }

  get end(): number {
    return Math.min(this.start + (+this.perPage - 1), +this.total);
  }

  private getPageArray(start: number, end: number) {
    return Array.apply(null, {length: end - start + 1}).map((value: any, index: number) => this.getPage(start + index));
  }

  private getPage(number: string | number, disabled = false): NglPage {
    return { number, disabled };
  }

  private getGapPage(before: number, after: number) {
    const isConsecutive = before + 1 === after - 1;
    return this.getPage(isConsecutive ? before + 1 : '...', !isConsecutive);
  }

  /**
   * Calculate first and last visible page numbers
   */
  private limits() {
    let start = 1, end = this.totalPages;

    if (this.limit < 1) return {start, end};

    // Current page is displayed in the middle of the visible ones
    start = Math.max(+this.current - Math.floor(+this.limit / 2), 1);
    end = start + +this.limit - 1;

    // Adjust if limit is exceeded
    if (end > this.totalPages) {
      end = this.totalPages;
      start = Math.max(end - +this.limit + 1, 1);
    }

    return {start, end};
  }

}


text:
using System.Web.Http;

namespace SqlFileStreamWebApiDemo
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}


text:
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

#include "frmr/frmrMath.h"

frmr::Vec3f	Camera::GetPosition() const
{
	return position;
}

frmr::Vec2f	Camera::GetRotation() const
{
	return rotation;
}

int16_t Camera::GetZoneNum() const
{
	return zoneNum;
}

Camera::Camera( const frmr::Vec3f &position, const frmr::Vec2f &rotation, const int16_t zoneNum )
	:	position( position ),
		rotation( rotation ),
		zoneNum( zoneNum )
{
}


text:
import React from 'react'

export const NotFound = () => {
  return (

We do not have what you are looking for ...

  )
}


text:
from fontTools.pens.basePen import BasePen
from .flatten import InputContour, OutputContour
from pyClipper import PolyClipper # XXX this isn't the real thing

"""
General Suggestions:
- Contours should only be sent here if they actually overlap.
  This can be checked easily using contour bounds.
- Only perform operations on closed contours.
- contours must have an on curve point
- some kind of a log
"""

class BooleanOperationManager(object):

    def _performOperation(self, operation, contours, outPen):
        # prep the contours
        inputContours = [InputContour(contour) for contour in contours]
        # XXX temporary
        clipperContours = []
        for contour in inputContours:
            clipperContours.append(dict(coordinates=contour.originalFlat))
        clipper = PolyClipper.alloc().init()
        resultContours = clipper.execute_operation_withOptions_(clipperContours, operation, dict(subjectFillType="noneZero", clipFillType="noneZero"))
        # the temporary Clipper wrapper is very, very slow
        # at converting back to Python structures. do it here
        # so that the profiling of this can be isolated.
        convertedContours = []
        for contour in resultContours:
            contour = [tuple(point) for point in contour]
            convertedContours.append(contour)
        resultContours = convertedContours
        # /XXX
        # convert to output contours
        outputContours = [OutputContour(contour) for contour in resultContours]
        # re-curve entire contour
        for inputContour in inputContours:
            for outputContour in outputContours:
                if outputContour.final:
                    break
                if outputContour.reCurveFromEntireInputContour(inputContour):
                    # the input is expired if a match was made,
                    # so stop passing it to the outputs
                    break
        # re-curve segments
        for inputContour in inputContours:
            # skip contours that were comppletely used in the previous step
            if inputContour.used:
                continue
            # XXX this could be expensive if an input becomes completely used
            # it doesn't stop from being passed to the output
            for outputContour in outputContours:
                outputContour.reCurveFromInputContourSegments(inputContour)
        # curve fit
        for outputContour in outputContours:
            outputContour.reCurveSubSegments(inputContours)
        # output the results
        for outputContour in outputContours:
            outputContour.drawPoints(outPen)
        # XXX return?
        return outputContours

    def union(self, contours, outPen):
        # XXX return?
        return self._performOperation("union", contours, outPen)


text:
package gov.nasa.jpf.util;

/**
 * (more efficient?) alternative to Vector<Integer>
 * @author pcd
 */
public final class LongVector {
  public static final int defaultInitCap = 40;

  /** <i>size</i> as in a java.util.Vector. */
  protected int size;

  /** the backing array. */
  protected long[] data;

  /** growth strategy. */
  protected Growth growth;

  public LongVector(Growth initGrowth, int initCap) {
    growth = initGrowth;
    data = new long[initCap];
    size = 0;
  }

  public LongVector(Growth initGrowth) { this(initGrowth,defaultInitCap); }

  public LongVector(int initCap) { this(Growth.defaultGrowth, initCap); }

  public LongVector() { this(Growth.defaultGrowth,defaultInitCap); }

  public void add(long x) {
    if (size+1 > data.length) {
      ensureCapacity(size+1);
    }
    data[size] = x;
    size++;
  }

  public long get(int idx) {
    if (idx >= size) {
      return 0;
    } else {
      return data[idx];
    }
  }

  public void set(int idx, long x) {
    ensureSize(idx + 1);
    data[idx] = x;
  }

  public void squeeze() {
    while (size > 0 && data[size - 1] == 0) size--;
  }

  public void setSize(int sz) {
    if (sz > size) {
      ensureCapacity(sz);
      size = sz;
    } else {
      while (size > sz) {
        size--;
        data[size] = 0;
      }
    }
  }

  public void clear() { setSize(0); }

  public int size() { return size; }

  public void ensureSize(int sz) {
    if (size < sz) {
      ensureCapacity(sz);
      size = sz;
    }
  }

  public void ensureCapacity(int desiredCap) {
    if (data.length < desiredCap) {
      long[] newData = new long[growth.grow(data.length, desiredCap)];
      System.arraycopy(data, 0, newData, 0, size);
      data = newData;
    }
  }

  public static void copy(LongVector src, int srcPos, LongVector dst, int dstPos, int len) {
    if (len == 0) return;
    src.ensureCapacity(srcPos + len);
    dst.ensureSize(dstPos+len);
    System.arraycopy(src.data, srcPos, dst.data, dstPos, len);
  }
}


text:
namespace safe_browsing {

extern const char kGeneratedSafeBrowsingPref[];

// Must be kept in sync with the SafeBrowsing enum located in
// chrome/browser/resources/settings/privacy_page/security_page.js.
enum class SafeBrowsingSetting {
  ENHANCED,
  STANDARD,
  DISABLED,
};

// A generated preference which represents the effective Safe Browsing setting
// state (including non-user management) based on the underlying Safe Browsing
// enhanced, enabled and reporting preferences. This preference allows the
// direct use of WebUI controls without exposing any logic responsible for
// coalescing the underlying Safe Browsing prefs to front-end code.
class GeneratedSafeBrowsingPref
    : public extensions::settings_private::GeneratedPref {
 public:
  explicit GeneratedSafeBrowsingPref(Profile* profile);

  // Generated Preference Interface.
  extensions::settings_private::SetPrefResult SetPref(
      const base::Value* value) override;
  std::unique_ptr<extensions::api::settings_private::PrefObject> GetPrefObject()
      const override;

  // Fired when underlying Safe Browsing preferences are changed.
  void OnSafeBrowsingPreferencesChanged();

 private:
  // Applies the effective management state of Safe Browsing for |profile| to
  // |pref_object|.
  static void ApplySafeBrowsingManagementState(
      const Profile* profile,
      extensions::api::settings_private::PrefObject* pref_object);

  // Weak reference to the profile this preference is generated for.
  const raw_ptr<Profile> profile_;

  PrefChangeRegistrar user_prefs_registrar_;
};

}  // namespace safe_browsing

#endif  // CHROME_BROWSER_SAFE_BROWSING_GENERATED_SAFE_BROWSING_PREF_H_


text:
bower gulp + structure
tag


text: from os_client_config.config import OpenStackConfig  # noqa


text:
package com.rahul.media.adapters;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.rahul.media.R;
import com.rahul.media.model.CustomGallery;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by rahul on 6/5/2016.
 */

public class VideoPreviewAdapter extends PagerAdapter {

    private final Context mContext;
    private LayoutInflater mLayoutInflater;
    private ArrayList<CustomGallery> dataT;
    private int playResId = R.drawable.video_play;

    public VideoPreviewAdapter(Context mContext, HashMap<String, CustomGallery> dataT) {
        this.mContext = mContext;
        this.dataT = new ArrayList<>(dataT.values());
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void setPlayResId(int playResId) {
        this.playResId = playResId;
    }

    public void customNotify(HashMap<String, CustomGallery> dataHashmap) {
        dataT.clear();
        ArrayList<CustomGallery> dataT2 = new ArrayList<CustomGallery>(dataHashmap.values());
        this.dataT.addAll(dataT2);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return dataT.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View itemView = mLayoutInflater.inflate(R.layout.video_image_pager_item, container, false);

        final SimpleDraweeView imageView = (SimpleDraweeView) itemView.findViewById(R.id.full_screen_image);

        final ImageView playIcon = (ImageView) itemView.findViewById(R.id.play_icon);
        playIcon.setImageResource(playResId);

        imageView.setImageURI(Uri.parse("file://" + dataT.get(position).sdcardPath));

        container.addView(itemView);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(dataT.get(position).sdcardPath), "video/*");
                    mContext.startActivity(Intent.createChooser(intent, "Complete action using .."));

                } catch (Exception e) {
                    e.printStackTrace();
                    if (e instanceof ActivityNotFoundException) {
                        Toast.makeText(mContext, "Video Player not found", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((FrameLayout) object);
    }
}


text:
package org.apache.geode.cache.lucene.internal;

import org.junit.Before;
import org.junit.Rule;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;

import org.apache.geode.cache.lucene.LuceneIndex;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.test.fake.Fakes;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class LuceneIndexImplJUnitTest {

  public static final String REGION = "region";
  public static final String INDEX = "index";
  public static final int MAX_WAIT = 30000;

  private InternalCache cache;
  private LuceneIndex index;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Before
  public void createLuceneIndex() {
    cache = Fakes.cache();
    index = new LuceneIndexForPartitionedRegion(INDEX, REGION, cache);
  }

}


text:
package net.batchik.crdt.fiber;

import co.paralleluniverse.common.monitoring.MonitorType;
import co.paralleluniverse.fibers.*;
import co.paralleluniverse.fibers.io.FiberServerSocketChannel;
import co.paralleluniverse.fibers.io.FiberSocketChannel;
import co.paralleluniverse.strands.SuspendableCallable;
import net.batchik.crdt.Service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Main server code implemented using Fibers. Single Fiber that accepts connections and then
 * hands it off to a new fiber for processing.
 */
public class FiberServer extends Service {
    private static Logger log = LogManager.getLogger(FiberServer.class);

    private static final int parallelism = 10000;
    private final FiberScheduler fiberScheduler;
    private final InetSocketAddress address;
    private final HttpRouter router;

    private final AtomicBoolean initialized = new AtomicBoolean(false);
    private final AtomicBoolean shutdown = new AtomicBoolean(false);

    public FiberServer(InetSocketAddress address, HttpRouter router) {
        fiberScheduler = new FiberForkJoinScheduler("web-scheduler", parallelism, MonitorType.METRICS, false);
        this.address = address;
        this.router = router;
    }

    @Override
    public void start() throws Exception {
        if (!initialized.compareAndSet(false, true)) {
            log.error("fiber server has already been initialized");
            throw new Exception("fiber server has already been initialized");
        }
        if (shutdown.get()) {
            log.error("server has already been shut down");
            throw new Exception("server has already been shut down");
        }

        fiberScheduler.newFiber(new SuspendableCallable<Void>() {
            @Override
            public Void run() throws SuspendExecution, InterruptedException {
                try(FiberServerSocketChannel channel = FiberServerSocketChannel.open().bind(address)) {
                    for (;;) {
                        if (shutdown.get()) {
                            log.info("Server was shutdown, exiting server routine.");
                            break;
                        }
                        FiberSocketChannel ch = channel.accept();
                        InetSocketAddress remoteAddress = (InetSocketAddress) ch.getRemoteAddress();
                        fiberScheduler.newFiber(new RequestCallable(router, remoteAddress, ch)).start();
                    }
                } catch (IOException ex) {
                    log.error("io exception while opening socket", ex);
                    shutdown.set(true);
                }
                return null;
            }
        }).start();
    }

    public void close() {
        shutdown.set(true);
    }

}


text:
package com.ymsino.water.view.web.searchAnalysis;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.gmail.xcjava.base.date.DateUtil;
import com.gmail.xcjava.base.hql.QueryCondition;
import com.gmail.xcjava.base.hql.QueryParamWriter;
import com.gmail.xcjava.base.io.FilesTool;
import com.gmail.xcjava.base.io.PropertyReader;
import com.opensymphony.oscache.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;
import com.ymsino.water.service.data.checkingFreezeData.CheckingFreezeDataReturn;
import com.ymsino.water.service.data.checkingFreezeData.CheckingFreezeDataService;
import com.ymsino.water.service.data.checkingFreezeData.QueryParam;
import com.ymsino.water.service.manager.chargingUnit.ChargingUnitReturn;
import com.ymsino.water.service.manager.chargingUnit.ChargingUnitService;
import com.ymsino.water.view.web.common.PageModel;

public class DownloadCheckingFreezeDataList extends ActionSupport {

	private static final long serialVersionUID = 4681544453198372257L;
	private String unitId;//收费单位编号
	private String userId;//客户编号
	private String freezeYear;//年份
	private String freezeMonth;//月份
	private String concHardwareId;//集中器编号
	private String meterHardwareId;//水表编号
	private List<CheckingFreezeDataReturn> list =  new ArrayList<CheckingFreezeDataReturn>();
	private CheckingFreezeDataService checkingFreezeDataService;
	private int recordCount;
	private ChargingUnitService chargingUnitService;
	@Override
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String managerUnitId = (String)session.getAttribute("sessionUnitId");

		String exportCount = PropertyReader.getProperties("config.properties").getProperty("exportCount");

		QueryParamWriter qpw = new QueryParamWriter();

		//根据当前管理员的收费单位查询
		if(!StringUtil.isEmpty(managerUnitId)){
			qpw.addQueryParam("parentUnits", "%|"+managerUnitId+"|%", QueryCondition.QC_LIKE);
		}

		if(!StringUtil.isEmpty(unitId)){
			qpw.addQueryParam("chargingUnitId", unitId, QueryCondition.QC_EQ);
		}
		if(!StringUtil.isEmpty(userId)){
			qpw.addQueryParam("userId", userId, QueryCondition.QC_EQ);
		}
		if(!StringUtil.isEmpty(meterHardwareId)){
			qpw.addQueryParam("meterHardwareId", meterHardwareId, QueryCondition.QC_EQ);
		}
		if(!StringUtil.isEmpty(freezeYear)){
			qpw.addQueryParam("freezeYear", freezeYear, QueryCondition.QC_EQ);
		}
		if(!StringUtil.isEmpty(freezeMonth)){
			qpw.addQueryParam("freezeMonth", freezeMonth, QueryCondition.QC_EQ);
		}
		if(!StringUtil.isEmpty(concHardwareId)){
			qpw.addQueryParam("concHardwareId", concHardwareId, QueryCondition.QC_EQ);
		}
		QueryParam qpm = new QueryParam();
		qpm.setQueryCon(qpw.getQueryCon());
		qpm.setQueryLink(qpw.getQueryLink());
		qpm.setQueryValue(qpw.getQueryValue());
		list = checkingFreezeDataService.getListpager(qpm,0, Integer.MAX_VALUE);
		recordCount = checkingFreezeDataService.getCount(qpm);

		if(recordCount > Integer.parseInt(exportCount)){
			response.getWriter().print("对不起,超出导出数量限制"+exportCount);
			return null;
		}
		LinkedHashMap<String,LinkedHashMap<String,String>> linkedHashMap = new LinkedHashMap<String,LinkedHashMap<String,String>>();
		for(int i = 0; i < list.size();i++){
			CheckingFreezeDataReturn cfd = list.get(i);
			if(cfd == null) continue;
			ChargingUnitReturn chargingUnit = chargingUnitService.getByUnitId(cfd.getChargingUnitId());
			LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();
			map.put("客户编号", StringUtil.isEmpty(cfd.getUserId()) ? "" : cfd.getUserId());
			map.put("集中器编号", StringUtil.isEmpty(cfd.getConcHardwareId()) ? "" : cfd.getConcHardwareId());
			map.put("表计编号", StringUtil.isEmpty(cfd.getMeterHardwareId()) ? "" : cfd.getMeterHardwareId());
			map.put("收费单位", chargingUnit == null ? "" : chargingUnit.getName());
			map.put("冻结时间", StringUtil.isEmpty(cfd.getFreezeYear()+""+cfd.getFreezeMonth()) ? "" : cfd.getFreezeYear()+"年"+cfd.getFreezeMonth()+"月");
			map.put("1日用水量", cfd.getMeterReading1() == null ? "" : cfd.getMeterReading1().toString());
			map.put("2日用水量", cfd.getMeterReading2() == null ? "" : cfd.getMeterReading2().toString());
			map.put("3日用水量", cfd.getMeterReading3() == null ? "" : cfd.getMeterReading3().toString());
			map.put("4日用水量", cfd.getMeterReading4() == null ? "" : cfd.getMeterReading4().toString());
			map.put("5日用水量", cfd.getMeterReading5() == null ? "" : cfd.getMeterReading5().toString());
			map.put("6日用水量", cfd.getMeterReading6() == null ? "" : cfd.getMeterReading6().toString());
			map.put("7日用水量", cfd.getMeterReading7() == null ? "" : cfd.getMeterReading7().toString());
			map.put("8日用水量", cfd.getMeterReading8() == null ? "" : cfd.getMeterReading8().toString());
			map.put("9日用水量", cfd.getMeterReading9() == null ? "" : cfd.getMeterReading9().toString());
			map.put("10日用水量", cfd.getMeterReading10() == null ? "" : cfd.getMeterReading10().toString());
			map.put("11日用水量", cfd.getMeterReading11() == null ? "" : cfd.getMeterReading11().toString());
			map.put("12日用水量", cfd.getMeterReading12() == null ? "" : cfd.getMeterReading12().toString());
			map.put("13日用水量", cfd.getMeterReading13() == null ? "" : cfd.getMeterReading13().toString());
			map.put("14日用水量", cfd.getMeterReading14() == null ? "" : cfd.getMeterReading14().toString());
			map.put("15日用水量", cfd.getMeterReading15() == null ? "" : cfd.getMeterReading15().toString());
			map.put("16日用水量", cfd.getMeterReading16() == null ? "" : cfd.getMeterReading16().toString());
			map.put("17日用水量", cfd.getMeterReading17() == null ? "" : cfd.getMeterReading17().toString());
			map.put("18日用水量", cfd.getMeterReading18() == null ? "" : cfd.getMeterReading18().toString());
			map.put("19日用水量", cfd.getMeterReading19() == null ? "" : cfd.getMeterReading19().toString());
			map.put("20日用水量", cfd.getMeterReading20() == null ? "" : cfd.getMeterReading20().toString());
			map.put("21日用水量", cfd.getMeterReading21() == null ? "" : cfd.getMeterReading21().toString());
			map.put("22日用水量", cfd.getMeterReading22() == null ? "" : cfd.getMeterReading22().toString());
			map.put("23日用水量", cfd.getMeterReading23() == null ? "" : cfd.getMeterReading23().toString());
			map.put("24日用水量", cfd.getMeterReading24() == null ? "" : cfd.getMeterReading24().toString());
			map.put("25日用水量", cfd.getMeterReading25() == null ? "" : cfd.getMeterReading25().toString());
			map.put("26日用水量", cfd.getMeterReading26() == null ? "" : cfd.getMeterReading26().toString());
			map.put("27日用水量", cfd.getMeterReading27() == null ? "" : cfd.getMeterReading27().toString());
			map.put("28日用水量", cfd.getMeterReading28() == null ? "" : cfd.getMeterReading28().toString());
			map.put("29日用水量", cfd.getMeterReading29() == null ? "" : cfd.getMeterReading29().toString());
			map.put("30日用水量", cfd.getMeterReading30() == null ? "" : cfd.getMeterReading30().toString());
			map.put("31日用水量", cfd.getMeterReading31() == null ? "" : cfd.getMeterReading31().toString());
			map.put("创建时间", cfd.getCreateTimestamp() == null ? "" : DateUtil.format(new Date(cfd.getCreateTimestamp()), "yyyy-MM-dd HH:mm:ss"));
			linkedHashMap.put(String.valueOf(i), map);
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename=\"" + "report.xls" + "\"");
			FilesTool.writeToExcel(linkedHashMap, null, response);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public int getRecordCount() {
		return recordCount;
	}
	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
	}
	public String getUnitId() {
		return unitId;
	}
	public void setUnitId(String unitId) {
		this.unitId = unitId;
	}
	public String getConcHardwareId() {
		return concHardwareId;
	}
	public void setConcHardwareId(String concHardwareId) {
		this.concHardwareId = concHardwareId;
	}
	public String getMeterHardwareId() {
		return meterHardwareId;
	}
	public void setMeterHardwareId(String meterHardwareId) {
		this.meterHardwareId = meterHardwareId;
	}
	public void setChargingUnitService(ChargingUnitService chargingUnitService) {
		this.chargingUnitService = chargingUnitService;
	}
	public String getFreezeYear() {
		return freezeYear;
	}
	public void setFreezeYear(String freezeYear) {
		this.freezeYear = freezeYear;
	}
	public String getFreezeMonth() {
		return freezeMonth;
	}
	public void setFreezeMonth(String freezeMonth) {
		this.freezeMonth = freezeMonth;
	}
	public List<CheckingFreezeDataReturn> getList() {
		return list;
	}
	public void setList(List<CheckingFreezeDataReturn> list) {
		this.list = list;
	}
	public void setCheckingFreezeDataService(
			CheckingFreezeDataService checkingFreezeDataService) {
		this.checkingFreezeDataService = checkingFreezeDataService;
	}

}


text:
require "integration/test_helper"
require "azure/blob/blob_service"

describe Azure::Blob::BlobService do
  subject { Azure::Blob::BlobService.new }
  after { TableNameHelper.clean }

  describe '#create_page_blob' do
    let(:container_name) { ContainerNameHelper.name }
    let(:blob_name) { "blobname" }
    let(:complex_blob_name) { 'qa-872053-/*"\'&.({[<+ ' + [ 0x7D, 0xEB, 0x8B, 0xA4].pack('U*') + '_' + "0" }
    let(:length) { 1024 }
    before {
      subject.create_container container_name
    }

    it 'creates a page blob' do
      blob = subject.create_page_blob container_name, blob_name, length
      blob.name.must_equal blob_name
    end

    it 'creates a page blob with complex name' do
      blob = subject.create_page_blob container_name, complex_blob_name, length
      blob.name.must_equal complex_blob_name

      complex_blob_name.force_encoding("UTF-8")
      found_complex_name = false
      result = subject.list_blobs container_name
      result.each { |blob|
        found_complex_name = true if blob.name == complex_blob_name
      }

      found_complex_name.must_equal true
    end

    it 'sets additional properties when the options hash is used' do
      options = {
        :content_type=>"application/xml",
        :content_encoding=>"utf-8",
        :content_language=>"en-US",
        :cache_control=>"max-age=1296000",
        :metadata => { "CustomMetadataProperty"=>"CustomMetadataValue"}
      }

      blob = subject.create_page_blob container_name, blob_name, length, options
      blob = subject.get_blob_properties container_name, blob_name
      blob.name.must_equal blob_name
      blob.properties[:content_type].must_equal options[:content_type]
      blob.properties[:content_encoding].must_equal options[:content_encoding]
      blob.properties[:cache_control].must_equal options[:cache_control]

      blob = subject.get_blob_metadata container_name, blob_name
      blob.name.must_equal blob_name
      blob.metadata["custommetadataproperty"].must_equal "CustomMetadataValue"
    end

    it 'errors if the container does not exist' do
      assert_raises(Azure::Core::Http::HTTPError) do
        subject.create_page_blob ContainerNameHelper.name, blob_name, length
      end
    end

    it 'errors if the length is not 512 byte aligned' do
      assert_raises(Azure::Core::Http::HTTPError) do
        subject.create_page_blob container_name, blob_name, length + 1
      end
    end
  end
end


text:
<!DOCTYPE html>
<html>
<head>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.6.3/coffee-script.min.js"></script>
  <script src="http:///cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
  <script src="http://builds.emberjs.com/tags/v1.8.1/ember.js"></script>
  <script src="../ember-cloaking.js"></script>
  <style>
    .ember-view {
      -webkit-animation: debug .3s;
    }

    @-webkit-keyframes debug {
      0% {
        background-color: yellow;
      }
      100% {
        background-color: inherit;
      }
    }

  </style>
  <script type="text/coffeescript">
    App = Ember.Application.create()
    App.Router.map ->
      @resource 'scroll'

    # random nums for view height
    random_height = ->
      Math.round( Math.random()*100 + 20 )

    # create a lots of crap
    model =  ( { id: i, height: random_height() } for i in [0..500] )
    App.ScrollRoute = Ember.Route.extend
      model: -> model
      actions:
        greeting: -> alert('greeting from route')

    App.ScrollView = Em.View.extend
      templateName: 'scroll'

    App.ItemView = Em.View.extend
      templateName: 'item'

      didInsertElement: ->
        @$().css 'height', @get('context.height')

  </script>
  <title>Ember Cloaking Test</title>
</head>
<body>
  <script type="text/x-handlebars">
    {{#link-to "scroll"}}go to scroll{{/link-to}}
    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="scroll">
    {{cloaked-collection itemViewClass="item" content=model}}
  </script>
    <script type="text/x-handlebars" data-template-name="item">
      <div {{action "greeting"}}>
        #{{id}} ({{height}}px)
      </div>
  </script>
</body>
</html>


text:
module Redde::TreeSortable
  def sort(list)
    Sorter.new(list, self).sort
  end

  class Sorter
    attr_accessor :list, :klass
    def initialize(list, klass)
      @list = list
      @klass = klass
    end

    def sort
      tree.each do |parent, cats|
        i = 1
        if parent == 'root'
          pid = nil
        else
          pid = klass.find(parent).id
        end
        cats.each do |cat|
          klass.find(cat).update(parent_id: pid, position: i)
          i += 1
        end
      end
    end

    def tree
      temp = {}
      list.each do |key, value|
        if temp[value]
          temp[value] << key
        else
          temp[value] = [key]
        end
      end
      temp
    end
  end
end


text:
/**
 * @author - Nicklass Fransson
 * @contact - nicklass.fransson@gmail.com
 * @date - 2/7/17
 */
package com.astir_trotter.atcustom.component;

import java.util.LinkedHashMap;
import java.util.Map;

public class TagFormat {
    private static final String TAG = TagFormat.class.getSimpleName();

    public static TagFormat from(String format) {
        return new TagFormat(format);
    }

    private final String format;
    private final Map<String, Object> tags = new LinkedHashMap<String, Object>();

    public TagFormat(String format) {
        this.format = format;
    }

    public TagFormat with(String key, Object value) {
        tags.put("\\{" + key + "\\}", value);
        return this;
    }

    public String format() {
        String formatted = format;
        for (Map.Entry<String, Object> tag : tags.entrySet()) {
            // bottleneck, creating temporary String objects!
            formatted = formatted.replaceAll(tag.getKey(), tag.getValue().toString());
        }
        return formatted;
    }
}


text:
use libc::c_void;
use leveldb_sys::leveldb_free;
use std;
use libc::c_char;

/// A leveldb error, just containing the error string
/// provided by leveldb.
#[derive(Debug)]
pub struct Error {
    message: String,
}

impl Error {
    /// create a new Error, using the String provided
    pub fn new(message: String) -> Error {
        Error { message: message }
    }

    /// create an error from a c-string buffer.
    ///
    /// This method is `unsafe` because the pointer must be valid and point to heap.
    /// The pointer will be passed to `free`!
    pub unsafe fn new_from_char(message: *const c_char) -> Error {
        use std::str::from_utf8;
        use std::ffi::CStr;

        let err_string = from_utf8(CStr::from_ptr(message).to_bytes()).unwrap().to_string();
        leveldb_free(message as *mut c_void);
        Error::new(err_string)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "LevelDB error: {}", self.message)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }
    fn cause(&self) -> Option<&std::error::Error> {
        None
    }
}


text:
package io.twipple.springframework.data.clusterpoint.convert;

import io.twipple.springframework.data.clusterpoint.mapping.ClusterpointDocument;
import org.springframework.data.convert.EntityReader;

/**
 * Marker interface for the Clusterpoint {@link EntityReader}.
 *
 * @author Olegs Briska
 */
public interface ClusterpointEntityReader extends EntityReader<Object, ClusterpointDocument> {
}


text:
/**
 * Created by Faliherizo on 24/12/2016.
 */

/*
 * Module dependencies
 */

var sio = require('socket.io')
    , parseCookies = require('connect').utils.parseSignedCookies
    , cookie = require('cookie')
    , fs = require('fs');

/**
 * Expose Sockets initialization
 */

module.exports = Sockets;

/**
 * Socket.io
 *
 * @param {Express} app `Express` instance.
 * @param {HTTPServer} server `http` server instance.
 * @api public
 */

function Sockets (app, server) {
    var config = app.get('config');
    var client = app.get('redisClient');
    var sessionStore = app.get('sessionStore');

    var io = sio.listen(server);
    io.set('authorization', function (hsData, accept) {
        if(hsData.headers.cookie) {
            var cookies = parseCookies(cookie.parse(hsData.headers.cookie), config.session.secret)
                , sid = cookies['balloons'];

            sessionStore.load(sid, function(err, session) {
                if(err || !session) {
                    return accept('Error retrieving session!', false);
                }

                hsData.balloons = {
                    user: session.passport.user,
                    room: /\/(?:([^\/]+?))\/?$/g.exec(hsData.headers.referer)[1]
                };

                return accept(null, true);

            });
        } else {
            return accept('No cookie transmitted.', false);
        }
    });

    io.configure(function() {
        io.set('store', new sio.RedisStore({
            redisClient: client,
            redisPub: client,
            redisSub: client
        }));
        io.enable('browser client minification');
        io.enable('browser client gzip');
    });
    io.sockets.on('connection', function (socket) {
        var hs = socket.handshake
            , nickname = hs.balloons.user.username
            , provider = hs.balloons.user.provider
            , userKey = provider + ":" + nickname
            , room_id = hs.balloons.room
            , now = new Date()
            // Chat Log handler
            , chatlogFileName = './chats/' + room_id + (now.getFullYear()) + (now.getMonth() + 1) + (now.getDate()) + ".txt"
        // , chatlogWriteStream = fs.createWriteStream(chatlogFileName, {'flags': 'a'});

        socket.join(room_id);

        client.sadd('sockets:for:' + userKey + ':at:' + room_id, socket.id, function(err, socketAdded) {
            if(socketAdded) {
                client.sadd('socketio:sockets', socket.id);
                client.sadd('rooms:' + room_id + ':online', userKey, function(err, userAdded) {
                    if(userAdded) {
                        client.hincrby('rooms:' + room_id + ':info', 'online', 1);
                        client.get('users:' + userKey + ':status', function(err, status) {
                            io.sockets.in(room_id).emit('new user', {
                                nickname: nickname,
                                provider: provider,
                                status: status || 'available'
                            });
                        });
                    }
                });
            }
        });

        socket.on('my msg', function(data) {
            var no_empty = data.msg.replace("\n","");
            if(no_empty.length > 0) {
                var chatlogRegistry = {
                    type: 'message',
                    from: userKey,
                    atTime: new Date(),
                    withData: data.msg
                }

                // chatlogWriteStream.write(JSON.stringify(chatlogRegistry) + "\n");

                io.sockets.in(room_id).emit('new msg', {
                    nickname: nickname,
                    provider: provider,
                    msg: data.msg
                });
            }
        });

        socket.on('set status', function(data) {
            var status = data.status;

            client.set('users:' + userKey + ':status', status, function(err, statusSet) {
                io.sockets.emit('user-info update', {
                    username: nickname,
                    provider: provider,
                    status: status
                });
            });
        });

        socket.on('history request', function() {
            var history = [];
            var tail = require('child_process').spawn('tail', ['-n', 5, chatlogFileName]);
            tail.stdout.on('data', function (data) {
                var lines = data.toString('utf-8').split("\n");

                lines.forEach(function(line, index) {
                    if(line.length) {
                        var historyLine = JSON.parse(line);
                        history.push(historyLine);
                    }
                });

                socket.emit('history response', {
                    history: history
                });
            });
        });

        socket.on('disconnect', function() {
            // 'sockets:at:' + room_id + ':for:' + userKey
            client.srem('sockets:for:' + userKey + ':at:' + room_id, socket.id, function(err, removed) {
                if(removed) {
                    client.srem('socketio:sockets', socket.id);
                    client.scard('sockets:for:' + userKey + ':at:' + room_id, function(err, members_no) {
                        if(!members_no) {
                            client.srem('rooms:' + room_id + ':online', userKey, function(err, removed) {
                                if (removed) {
                                    client.hincrby('rooms:' + room_id + ':info', 'online', -1);
                                    // chatlogWriteStream.destroySoon();
                                    io.sockets.in(room_id).emit('user leave', {
                                        nickname: nickname,
                                        provider: provider
                                    });
                                }
                            });
                        }
                    });
                }
            });
        });
    });

};


text:
package com.aparapi.codegen.test;

public class IncField {
    int field = 1024;

    public void run() {
        field++;
    }
}
/**{Throws{ClassParseException}Throws}**/