text:
require 'set'
require 'shellwords'

module Sprockets
  # The `DirectiveProcessor` is responsible for parsing and evaluating
  # directive comments in a source file.
  #
  # A directive comment starts with a comment prefix, followed by an "=",
  # then the directive name, then any arguments.
  #
  #     // JavaScript
  #     //= require "foo"
  #
  #     # CoffeeScript
  #     #= require "bar"
  #
  #     /* CSS
  #      *= require "baz"
  #      */
  #
  # This makes it possible to disable or modify the processor to do whatever
  # you'd like. You could add your own custom directives or invent your own
  # directive syntax.
  #
  # `Environment#processors` includes `DirectiveProcessor` by default.
  #
  # To remove the processor entirely:
  #
  #     env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
  #     env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)
  #
  # Then inject your own preprocessor:
  #
  #     env.register_processor('text/css', MyProcessor)
  #
  class DirectiveProcessor
    VERSION = '1'

    # Directives are denoted by a `=` followed by the name, then
    # argument list.
    #
    # A few different styles are allowed:
    #
    #     // =require foo
    #     //= require foo
    #     //= require "foo"
    #
    DIRECTIVE_PATTERN = /
      ^ \W* = \s* (\w+.*?) (\*\/)? $
    /x

    def self.instance
      @instance ||= new(
        # Deprecated: Default to C and Ruby comment styles
        comments: ["//", ["/*", "*/"]] + ["#", ["###", "###"]]
      )
    end

    def self.call(input)
      instance.call(input)
    end

    def initialize(options = {})
      @header_pattern = compile_header_pattern(Array(options[:comments]))
    end

    def call(input)
      dup._call(input)
    end

    def _call(input)
      @environment  = input[:environment]
      @uri          = input[:uri]
      @filename     = input[:filename]
      @dirname      = File.dirname(@filename)
      @content_type = input[:content_type]
      @required     = Set.new(input[:metadata][:required])
      @stubbed      = Set.new(input[:metadata][:stubbed])
      @links        = Set.new(input[:metadata][:links])
      @dependencies = Set.new(input[:metadata][:dependencies])

      data, directives = process_source(input[:data])
      process_directives(directives)

      { data: data,
        required: @required,
        stubbed: @stubbed,
        links: @links,
        dependencies: @dependencies }
    end

    protected
      # Directives will only be picked up if they are in the header
      # of the source file. C style (/* */), JavaScript (//), and
      # Ruby (#) comments are supported.
      #
      # Directives in comments after the first non-whitespace line
      # of code will not be processed.
      def compile_header_pattern(comments)
        re = comments.map { |c|
          case c
          when String
            "(?:#{Regexp.escape(c)}.*\\n?)+"
          when Array
            "(?:#{Regexp.escape(c[0])}(?m:.*?)#{Regexp.escape(c[1])})"
          else
            raise TypeError, "unknown comment type: #{c.class}"
          end
        }.join("|")
        Regexp.compile("\\A(?:(?m:\\s*)(?:#{re}))+")
      end

      def process_source(source)
        header = source[@header_pattern, 0] || ""
        body   = $' || source

        header, directives = extract_directives(header)

        data = ""
        data.force_encoding(body.encoding)
        data << header << "\n" unless header.empty?
        data << body
        # Ensure body ends in a new line
        data << "\n" if data.length > 0 && data[-1] != "\n"

        return data, directives
      end

      # Returns an Array of directive structures. Each structure
      # is an Array with the line number as the first element, the
      # directive name as the second element, followed by any
      # arguments.
      #
      #     [[1, "require", "foo"], [2, "require", "bar"]]
      #
      def extract_directives(header)
        processed_header = ""
        directives = []

        header.lines.each_with_index do |line, index|
          if directive = line[DIRECTIVE_PATTERN, 1]
            name, *args = Shellwords.shellwords(directive)
            if respond_to?("process_#{name}_directive", true)
              directives << [index + 1, name, *args]
              # Replace directive line with a clean break
              line = "\n"
            end
          end
          processed_header << line
        end

        return processed_header.chomp, directives
      end

      # Gathers comment directives in the source and processes them.
      # Any directive method matching `process_*_directive` will
      # automatically be available. This makes it easy to extend the
      # processor.
      #
      # To implement a custom directive called `require_glob`, subclass
      # `Sprockets::DirectiveProcessor`, then add a method called
      # `process_require_glob_directive`.
      #
      #     class DirectiveProcessor < Sprockets::DirectiveProcessor
      #       def process_require_glob_directive
      #         Dir["#{dirname}/#{glob}"].sort.each do |filename|
      #           require(filename)
      #         end
      #       end
      #     end
      #
      # Replace the current processor on the environment with your own:
      #
      #     env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
      #     env.register_processor('text/css', DirectiveProcessor)
      #
      def process_directives(directives)
        directives.each do |line_number, name, *args|
          begin
            send("process_#{name}_directive", *args)
          rescue Exception => e
            e.set_backtrace(["#{@filename}:#{line_number}"] + e.backtrace)
            raise e
          end
        end
      end

      # The `require` directive functions similar to Ruby's own `require`.
      # It provides a way to declare a dependency on a file in your path
      # and ensures its only loaded once before the source file.
      #
      # `require` works with files in the environment path:
      #
      #     //= require "foo.js"
      #
      # Extensions are optional. If your source file is ".js", it
      # assumes you are requiring another ".js".
      #
      #     //= require "foo"
      #
      # Relative paths work too. Use a leading `./` to denote a relative
      # path:
      #
      #     //= require "./bar"
      #
      def process_require_directive(path)
        @required << resolve(path, accept: @content_type, bundle: false)
      end

      # `require_self` causes the body of the current file to be inserted
      # before any subsequent `require` directives. Useful in CSS files, where
      # it's common for the index file to contain global styles that need to
      # be defined before other dependencies are loaded.
      #
      #     /*= require "reset"
      #      *= require_self
      #      *= require_tree .
      #      */
      #
      def process_require_self_directive
        if @required.include?(@uri)
          raise ArgumentError, "require_self can only be called once per source file"
        end
        @required << @uri
      end

      # `require_directory` requires all the files inside a single
      # directory. It's similar to `path/*` since it does not follow
      # nested directories.
      #
      #     //= require_directory "./javascripts"
      #
      def process_require_directory_directive(path = ".")
        path = expand_relative_dirname(:require_directory, path)
        require_paths(*@environment.stat_directory_with_dependencies(path))
      end

      # `require_tree` requires all the nested files in a directory.
      # Its glob equivalent is `path/**/*`.
      #
      #     //= require_tree "./public"
      #
      def process_require_tree_directive(path = ".")
        path = expand_relative_dirname(:require_tree, path)
        require_paths(*@environment.stat_sorted_tree_with_dependencies(path))
      end

      # Allows you to state a dependency on a file without
      # including it.
      #
      # This is used for caching purposes. Any changes made to
      # the dependency file will invalidate the cache of the
      # source file.
      #
      # This is useful if you are using ERB and File.read to pull
      # in contents from another file.
      #
      #     //= depend_on "foo.png"
      #
      def process_depend_on_directive(path)
        resolve(path)
      end

      # Allows you to state a dependency on an asset without including
      # it.
      #
      # This is used for caching purposes. Any changes that would
      # invalid the asset dependency will invalidate the cache our the
      # source file.
      #
      # Unlike `depend_on`, the path must be a requirable asset.
      #
      #     //= depend_on_asset "bar.js"
      #
      def process_depend_on_asset_directive(path)
        load(resolve(path))
      end

      # Allows dependency to be excluded from the asset bundle.
      #
      # The `path` must be a valid asset and may or may not already
      # be part of the bundle. Once stubbed, it is blacklisted and
      # can't be brought back by any other `require`.
      #
      #     //= stub "jquery"
      #
      def process_stub_directive(path)
        @stubbed << resolve(path, accept: @content_type, bundle: false)
      end

      # Declares a linked dependency on the target asset.
      #
      # The `path` must be a valid asset and should not already be part of the
      # bundle. Any linked assets will automatically be compiled along with the
      # current.
      #
      #   /*= link "logo.png" */
      #
      def process_link_directive(path)
        @links << load(resolve(path)).uri
      end

      # `link_directory` links all the files inside a single
      # directory. It's similar to `path/*` since it does not follow
      # nested directories.
      #
      #     //= link_directory "./fonts"
      #
      # Use caution when linking against JS or CSS assets. Include an explicit
      # extension or content type in these cases
      #
      #     //= link_directory "./scripts" .js
      #
      def process_link_directory_directive(path = ".", accept = nil)
        path = expand_relative_dirname(:link_directory, path)
        accept = expand_accept_shorthand(accept)
        link_paths(*@environment.stat_directory_with_dependencies(path), accept)
      end

      # `link_tree` links all the nested files in a directory.
      # Its glob equivalent is `path/**/*`.
      #
      #     //= link_tree "./images"
      #
      # Use caution when linking against JS or CSS assets. Include an explicit
      # extension or content type in these cases
      #
      #     //= link_tree "./styles" .css
      #
      def process_link_tree_directive(path = ".", accept = nil)
        path = expand_relative_dirname(:link_tree, path)
        accept = expand_accept_shorthand(accept)
        link_paths(*@environment.stat_sorted_tree_with_dependencies(path), accept)
      end

    private
      def expand_accept_shorthand(accept)
        if accept.nil?
          nil
        elsif accept.include?("/")
          accept
        elsif accept.start_with?(".")
          @environment.mime_exts[accept]
        else
          @environment.mime_exts[".#{accept}"]
        end
      end

      def require_paths(paths, deps)
        resolve_paths(paths, deps, accept: @content_type, bundle: false) do |uri|
          @required << uri
        end
      end

      def link_paths(paths, deps, accept)
        resolve_paths(paths, deps, accept: accept) do |uri|
          @links << load(uri).uri
        end
      end

      def resolve_paths(paths, deps, options = {})
        @dependencies.merge(deps)
        paths.each do |subpath, stat|
          next if subpath == @filename || stat.directory?
          uri, deps = @environment.resolve(subpath, options.merge(compat: false))
          @dependencies.merge(deps)
          yield uri if uri
        end
      end

      def expand_relative_dirname(directive, path)
        if @environment.relative_path?(path)
          path = File.expand_path(path, @dirname)
          stat = @environment.stat(path)

          if stat && stat.directory?
            path
          else
            raise ArgumentError, "#{directive} argument must be a directory"
          end
        else
          # The path must be relative and start with a `./`.
          raise ArgumentError, "#{directive} argument must be a relative path"
        end
      end

      def load(uri)
        asset = @environment.load(uri)
        @dependencies.merge(asset.metadata[:dependencies])
        asset
      end

      def resolve(path, options = {})
        # Prevent absolute paths in directives
        if @environment.absolute_path?(path)
          raise FileOutsidePaths, "can't require absolute file: #{path}"
        end

        uri, deps = @environment.resolve!(path, options.merge(base_path: @dirname))
        @dependencies.merge(deps)
        uri
      end
  end
end


text:
# Endpoint.DomainId Property

Domain Id of the endpoint

**Namespace:** Bandwidth.Net.Api
**Assembly:** Bandwidth.Net (in Bandwidth.Net.dll) Version: 3.0.3

## Syntax

**C#**

``` C#
public string DomainId { get; set; }
```

#### Property Value
Type: String

## See Also

#### Reference
Endpoint Class
Bandwidth.Net.Api Namespace

redpajama_set_name: RedPajamaGithub


text:
import bz2
import gzip
import multiprocessing
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import time
from contextlib import contextmanager
from copy import deepcopy
from datetime import datetime, timedelta, tzinfo
from functools import wraps
from subprocess import check_call

from genestack.genestack_exceptions import GenestackException
from genestack import environment
from genestack.environment import PROGRAMS_DIRECTORY

DEFAULT_CPU_COUNT = 8

def join_program_path(*args):
    """
    Return path with prepended PROGRAMS_DIRECTORY. Same as:
    ``os.path(PROGRAMS_DIRECTORY, *args)``

    For example to get samtools executable:
    ``join_program_path('samtools', '0.1.19' 'samtools')``

    :param args: list of related paths from PROGRAMS_DIRECTORY
    :return: absolute path
    :rtype: str
    """
    return os.path.abspath(os.path.join(PROGRAMS_DIRECTORY, *args))

def to_list(obj):
    """
    Wrap object to list if it is not list.

    :param obj: object for wrapping
    :return: list
    """
    if type(obj) == list:
        return obj
    return [obj]

def makedirs_p(path):
    """
    Create directories recursively.

    :param path: path for folder to create
    :return: None
    """
    path = os.path.abspath(path)
    if not os.path.isdir(path):
        try:
            os.makedirs(path)
        except os.error:
            # double-check on case directory was created between the first check
            # and a call to os.makedirs(path)
            if not os.path.isdir(path):
                raise

def remove_file(path):
    """
    Remove file or directory.

    :param path: path to remove
    :type path: str
    :return: None
    """
    if os.path.exists(path) or os.path.islink(path):
        if os.path.isdir(path) and not os.path.islink(path):
            shutil.rmtree(path)
        else:
            os.remove(path)

@contextmanager
def opener(filename, mode='r'):
    """
    Context manager for opening regular and compressed files.
    ``gzip`` and ``bzip2`` compression are supported.
    Always opens files in binary mode.

    Looks like best way to check if file is gzipped is to check extension:
    http://stackoverflow.com/a/3703300/1310066

    :param filename: name of file
    :type filename: str
    :param mode: is either 'r' or 'w' ('r' by default)
    :type mode: str
    """
    # avoid circular imports
    # noinspection PyProtectedMember
    from genestack.compression import _get_file_compression_unchecked, GZIP, BZIP2, UNCOMPRESSED

    if mode not in ['r', 'w']:
        raise GenestackException('Invalid mode: %s' % repr(mode))
    mode = '%sb' % mode

    compression = _get_file_compression_unchecked(filename)

    compression_map = {
        GZIP: gzip.open,
        BZIP2: bz2.BZ2File,
        UNCOMPRESSED: open,
    }

    _open = compression_map.get(compression)
    if _open is None:
        raise GenestackException('Compression is not supported: %s' % compression)

    f = _open(filename, mode=mode)
    try:
        yield f
    finally:
        f.close()

def is_empty_file(file_path):
    """
    Return True if file is empty.
    Gziped files always contains header and has non zero size.

    :param file_path: path to file
    :type file_path: str
    :return: boolean value if file is empty.
    :rtype: bool
    """
    if file_path.endswith('.gz'):
        with opener(file_path, 'r') as f:
            return not bool(f.read(1))
    else:
        return not os.path.getsize(file_path)

def concatenate_files(paths, output_path):
    """
    Concatenate files analog for: cat paths > output_path.

    :param paths: list of paths
    :type paths: list
    :param output_path: path of result file
    :type output_path: str
    :return: output_path
    """
    # TODO: should we check if output file already exists? -- Klas
    (_, inter_path) = tempfile.mkstemp(dir='.')
    with open(inter_path, 'wb') as result_file:
        for path in paths:
            with opener(path) as to_read:
                shutil.copyfileobj(to_read, result_file)
    shutil.move(inter_path, output_path)
    return output_path

def get_cpu_count():
    """
    Counts number of CPU on worker.

    :return: number of CPU
    """
    try:
        return multiprocessing.cpu_count()
    except NotImplemented:
        return DEFAULT_CPU_COUNT

def get_size(src):
    """
    Return size for file or folder.

    :param src: valid path
    :type src: str
    :return: size in bytes
    :rtype: int
    """
    if os.path.isfile(src):
        return os.path.getsize(src)
    size = 0
    for base, folders, files in os.walk(src):
        size += sum(os.path.getsize(os.path.join(base, f)) for f in files)
    return size

def unbuffer_stdout():
    """
    Make stdout stream unbuffered, so that ``print`` appear in e.g. logs at
    once rather than who knows when.

    :return: None
    """
    class UnbufferedStream(object):
        """
        Wrapper class for stream
        """
        def __init__(self, stream):
            self.stream = stream

        def write(self, data):
            self.stream.write(data)
            self.stream.flush()

        def __getattr__(self, attr):
            return getattr(self.stream, attr)

    # real ``stdout`` is kept in sys.__stdout__
    sys.stdout = UnbufferedStream(sys.stdout)

def format_tdelta(tdelta):
    """
    Convert seconds to human friendly string.

    :param tdelta: seconds
    :type tdelta: float
    :return: human friendly string
    :rtype: str
    """
    if tdelta >= 60:
        tdelta_s = str(timedelta(seconds=round(tdelta)))
    else:
        tdelta_s = '%.2f sec' % tdelta
    return tdelta_s

def _join_messages(messages):
    return ' '.join(str(msg) for msg in messages)

def log_info(*messages):
    """
    Join messages with space and log them with current date and time to stdout.

    Non-string messages will be converted to string.
    """
    _log_with_timestamp(_join_messages(messages), sys.stdout)

def log_warning(*messages):
    """
    Join messages with space and log them with current date and time to stderr.

    Non-string messages will be converted to string.
    """
    _log_with_timestamp(_join_messages(messages), sys.stderr)

class UTC(tzinfo):
    """tzinfo subclass for UTC"""
    ZERO = timedelta(0)

    def utcoffset(self, dt):
        return self.ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return self.ZERO

utc_tz = UTC()

def _log_with_timestamp(msg, stream):
    # ``time.timezone`` stores offset to UTC in seconds
    utcnow = datetime.utcnow().replace(tzinfo=utc_tz)
    stream.write('{} - {}\n'.format(utcnow.strftime('%Y-%m-%d %H:%M:%S %Z'),
                                    msg))

def sort_file(path, save_path=None):
    if save_path is None:
        save_path = path
    if path.endswith('.gz'):
        command = 'gunzip -c "%s" | LC_ALL=C sort --output="%s"' % (path, save_path)
    else:
        command = 'LC_ALL=C sort "%s" --output="%s"' % (path, save_path)
    check_call(command, shell=True)

def normalize_contig_name(contig_name):
    """
    Returns normalized contig name. If normalized name is empty string return CHROMOSOME
    This function has java implementation in GenomeInterval. Both must return same result.

    This is used in current realization. Need to discuss to avoid this.
    One of possible solution:

        - Not normalize in reference genome
        - Add check for bed files: if contig in BED file can't be normilized to one of Reference genome contgs: fail.

    :type contig_name: str
    :param contig_name: raw name of contig
    """
    contig_name_normalized = contig_name.upper().replace('CHROMOSOME', '').replace('CHROM', '').replace('CHR', '').strip()
    return contig_name_normalized or contig_name

def get_script(name):
    """
    Returns path to script located in application script directory.

    :param name: name of the script
    :type name: str
    :return: path to script
    :rtype: str
    """
    directory = os.path.dirname(sys.argv[0])
    return os.path.join(directory, name)

class DumpData(object):
    def __init__(self):
        self.format = []
        self.data = []
        self.size = 0

    def _put_number(self, val, fmt):
        bytes_number = struct.calcsize(fmt)
        mask = ~(-1 << (bytes_number * 8))
        self.format.append(fmt)
        self.data.append(val & mask)
        self.size += bytes_number

    def _put(self, val, fmt):
        self.format.append(fmt)
        self.data.append(val)
        self.size += struct.calcsize(fmt)

    def put_int(self, val):
        self._put_number(val, 'I')

    def put_long(self, val):
        self._put_number(val, 'Q')

    def put_byte(self, val):
        self._put_number(val, 'B')

    def put_fixed_text(self, val, length):
        self._put(val, '%ss' % length)

    def put_text(self, val):
        length = len(val)
        if length > 255:
            length = 255
            val = val[:255]

        self.put_byte(length)
        self._put(val, '%ss' % length)

    def put_float(self, val):
        self._put(val, 'f')

    def to_binary(self):
        return struct.pack(">%s" % "".join(self.format), *self.data)

    def __str__(self):
        step = 4
        return ', '.join('%s: %s' % item for item in zip(self.format[:step], self.data[:step]))

    # TODO: return size of data written + remove self.size field?
    def dump_to_file(self, fs):
        fs.write(self.to_binary())

UNITS = ('B', 'KB', 'MB', 'GB', 'TB')

def _determine_units(num, step=0):
    """Finds the best unit and number to display size."""
    if num < 1000 or step >= len(UNITS) - 1:
        return num, step
    else:
        return _determine_units(int(num / 1000), step+1)

def prettify_size(size):
    """Prettyformats size."""
    num, unit_no = _determine_units(size)
    return '%s %s' % (num, UNITS[unit_no])

def optional_args_decorator(func):
    """
    Decorator that is used to decorate other decorators, so that they can take optional arguments and still be used
    without braces.

    :Example:

    >>> @optional_args_decorator
    >>> def decorated_decorator(function_to_decorate, optional_arguments...)
    >>>     # usual decorator code
    """
    @wraps(func)
    def wrapper(*args):
        if len(args) == 1 and callable(args[0]):
            return func(args[0])
        else:
            def actual(function_to_decorate):
                return func(function_to_decorate, *args)
            return actual
    return wrapper

@optional_args_decorator
def deprecated(func, message=''):
    """
    Decorator that prints a deprecation warning with the provided message to stderr.

    :Example:

    >>> @deprecated('use "bar" instead')
    >>> def deprecated_function():
    >>>  ...

    :param func: function to decorate
    :param message: deprecation message
    :return: wrapped function
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        msg = ', ' + message if message else ''
        sys.stderr.write('WARNING: %s is deprecated%s\n' % (func.__name__, msg))
        return func(*args, **kwargs)
    return wrapper

class FormatPattern(object):
    def __init__(self, format_maps):
        """
        Format pattern is a list of format maps.

        You can specify all required formats in constructor or add them from other format pattern with ``add`` method

        :param format_maps: list of dicts
        :return:
        """
        if format_maps is None:
            format_maps = [{}]
        if not isinstance(format_maps, (list, tuple)):
            raise GenestackException('Format map should be list or tuple')
        map(self.validate, format_maps)
        self.__list = deepcopy(format_maps)

    def to_list(self):
        return self.__list

    @staticmethod
    def check_contains(pattern, item):
        if not set(pattern).issubset(item):
            return False
        return all(item[k] in value for k, value in pattern.items())

    def __contains__(self, item):
        if not isinstance(item, dict):
            raise GenestackException('Cannot check containing for not dict')
        return any(self.check_contains(pattern, item) for pattern in self.__list)

    @staticmethod
    def validate(format_map):
        if isinstance(format_map, dict):
            if all(isinstance(k, basestring) and isinstance(v, (list, tuple)) for k, v in format_map.items()):
                return
        message = 'Incorrect formats schema, expect dict(str:[str, ...], ...) got: %s'
        raise GenestackException(message % format_map)

    def __repr__(self):
        items_as_string = ['; '.join(['%s: %s' % (k, '|'.join(v)) for k, v in sorted(x.items())]) for x in self.__list]
        return 'Patterns %s' % ', '. join('%s) %s' % x for x in enumerate(items_as_string, start=1))

    def add(self, format_pattern):
        """Add other format patterns."""
        if not isinstance(format_pattern, self.__class__):
            raise GenestackException('Cannot add "%s" to format pattern' % type(format_pattern))
        self.__list.extend(format_pattern.to_list())

@deprecated('use "compression.gzip_file" instead')
def gzip_file(path, dest_folder=None):
    from compression import gzip_file
    return gzip_file(path, dest_folder=dest_folder)

@deprecated('use "compression.decompress_file" instead')
def decompress_file(path, dest_folder=None):
    from compression import decompress_file
    return decompress_file(path, dest_folder=dest_folder)

def validate_type(value, value_type, accept_none=False):
    """
    Validates a value against given types.

    :param value: value to validate
    :type value: object
    :param value_type: types to validate against
    :type value_type: class-or-type-or-tuple
    :param accept_none: indicates whether None value is acceptable.
        Providing None with accept_none=True will not raise an exception
    :type accept_none: bool
    :return: None, if validation was successful
    :raise GenestackException: if validation was unsuccessful
    """
    if accept_none and value is None:
        return
    if not isinstance(value, value_type):
        raise GenestackException('Parameter must be of type %s, not %s' % (value_type, type(value)))

def get_java_tool(jar_name):
    """
    Returns path to the executable jar from the 'tools' folder, specified by the given name.

    :param jar_name: name of the tool
    :type jar_name: str
    :return: path to the tool
    :rtype: str
    """
    return os.path.join(environment.TASK_LIBRARY_ROOT, 'tools', '%s.jar' % jar_name)

def run_java_tool(tool, *args):
    """
    Runs the java tool with the provided path and parameters and logs the process.

    :param tool: path to the java tool
    :type tool: str
    :param args: tool arguments
    :type args: list[str]
    """
    tool_name = os.path.basename(os.path.normpath(tool))
    start_msg = 'Start %s' % tool_name
    log_info(start_msg)
    log_warning(start_msg)
    start_time = time.time()

    params = ['java', '-jar', tool]
    params.extend(args)
    subprocess.check_call(params)

    tdelta = format_tdelta(time.time() - start_time)
    exit_msg = 'Finish %s in %s' % (tool_name, tdelta)
    log_info(exit_msg)
    log_warning(exit_msg)

def truncate_sequence_str(sequence, limit=10):
    """
    Return string representation of the sequence,
    if sequence have more elements than limit, truncate output and print total number.

    >>> truncate_sequence_str(['a', 'b', 'c'], limit=1)
    ['a', ... and 2 more]

    :param sequence: sequence to print
    :type sequence: list|tuple|set|frozenset|dict
    :param limit: max number of items to print
    :type limit: int

    :return: None
    """
    delimiter = ', '

    # convert types and select proper braces
    # set -> sorted list
    # dict -> list of items

    if isinstance(sequence, list):
        braces = '[]'
    elif isinstance(sequence, (set, frozenset)):
        sequence = sorted(sequence)
        braces = '{}'
    elif isinstance(sequence, dict):
        sequence = sorted(sequence.items())
        braces = '[]'
    else:
        braces = '()'

    size = len(sequence)
    if size > limit:
        suffix = '%s... and %s more' % (delimiter, size - limit)
    else:
        suffix = ''

    result = [
        braces[0],
        delimiter.join(repr(x) for x in sequence[:limit]),
        suffix,
        braces[1]
    ]
    return ''.join(result)

def get_unique_name(output):
    """
    Returns path to the new unique file name if output already exists.

    :param output: path
    :type output: str
    :return: path to the new unique file name if output is already exists
    :rtype: str
    """
    if os.path.exists(output):
        folder, basename = os.path.split(output)
        descriptor, output = tempfile.mkstemp(suffix='_%s' % basename, prefix='', dir=folder)
        os.close(descriptor)
    return output

def escape_quotation(value_string):
    """
    Returns a given string with escaped quotations.

    :param value_string: string to be escaped
    :type output: str
    :return: string with escaped quotations
    :rtype: str
    """
    special_characters = ['(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=']
    if any(char in value_string for char in special_characters):
        escaped = value_string.replace('\\', '\\\\').replace('"', '\\"')
        return '"' + escaped + '"'
    return value_string


text:
""" Models for displaying maps in Bokeh plots.

"""
from __future__ import absolute_import

from ..properties import HasProps, abstract
from ..properties import Enum, Float, Instance, Int, JSON
from ..enums import MapType
from ..validation.warnings import MISSING_RENDERERS, NO_GLYPH_RENDERERS
from ..validation.errors import REQUIRED_RANGE
from .. import validation

from .plots import Plot

@abstract
class MapOptions(HasProps):
    """ Abstract base class for map options' models.

    """

    lat = Float(help="""
    The latitude where the map should be centered.
    """)

    lng = Float(help="""
    The longitude where the map should be centered.
    """)

    zoom = Int(12, help="""
    The initial zoom level to use when displaying the map.
    """)

@abstract
class MapPlot(Plot):
    """ Abstract base class for map plot models.

    """

    map_options = Instance(MapOptions, help="""
    Options for displaying the plot.
    """)

class GMapOptions(MapOptions):
    """ Options for GMapPlot objects.

    """

    map_type = Enum(MapType, help="""
    The `map type`_ to use for the GMapPlot.

    .. _map type: https://developers.google.com/maps/documentation/javascript/reference#MapTypeId

    """)

    styles = JSON(help="""
    A JSON array of `map styles`_ to use for the GMapPlot. Many example styles can
    `be found here`_.

    .. _map styles: https://developers.google.com/maps/documentation/javascript/reference#MapTypeStyle
    .. _be found here: https://snazzymaps.com

    """)

class GMapPlot(MapPlot):
    """ A Bokeh Plot with a `Google Map`_ displayed underneath.

    Data placed on this plot should be specified in decimal lat long coordinates e.g. 37.123, -122.404.
    It will be automatically converted into the web mercator projection to display properly over
    google maps tiles.

    .. _Google Map: https://www.google.com/maps/

    """

    # TODO (bev) map plot might not have these
    @validation.error(REQUIRED_RANGE)
    def _check_required_range(self):
        pass
    @validation.warning(MISSING_RENDERERS)
    def _check_missing_renderers(self):
        pass
    @validation.warning(NO_GLYPH_RENDERERS)
    def _check_no_glyph_renderers(self):
        pass

    map_options = Instance(GMapOptions, help="""
    Options for displaying the plot.
    """)

class GeoJSOptions(MapOptions):
    """ Options for GeoJSPlot objects.

    """

class GeoJSPlot(MapPlot):
    """ A Bokeh Plot with a `GeoJS Map`_ displayed underneath.

    .. warning::
        GeoJSPlot support should be considered experimental, a subject
        to revision or removal.

    .. _GeoJS Map: https://github.com/OpenGeoscience/geojs

    """

    # TODO (bev) map plot might not have these
    @validation.error(REQUIRED_RANGE)
    def _check_required_range(self):
        pass
    @validation.warning(MISSING_RENDERERS)
    def _check_missing_renderers(self):
        pass
    @validation.warning(NO_GLYPH_RENDERERS)
    def _check_no_glyph_renderers(self):
        pass

    map_options = Instance(GeoJSOptions, help="""
    Options for displaying the plot.
    """)


text:
package fr.jetlag.blogwithj.social;

import java.util.List;

/**
 * Created by vince on 04/06/15.
 */
public class SocialStats {

  private List<Comment> comments;

  private int views;

  private int likeCounts;

}


text:
# withLatestFrom

#### 函数签名: `withLatestFrom(other: Observable, project: Function): Observable`

## 还提供另一个 observable 的最新值。

---

:bulb: 如果你希望每当任意 observable 发出值时各个 observable 的最新值,请尝试 [combinelatest](combinelatest.md)!

---

### 示例

##### 示例 1: 发出频率更快的第二个 source 的最新值

(
[StackBlitz](https://stackblitz.com/edit/typescript-tznzbj?file=index.ts&devtoolsheight=100)
| [jsBin](http://jsbin.com/fitekeseru/1/edit?js,console) |
[jsFiddle](https://jsfiddle.net/btroncone/9c3pfgpk/) )

```js
// RxJS v6+
import { withLatestFrom, map } from 'rxjs/operators';
import { interval } from 'rxjs';

// 每5秒发出值
const source = interval(5000);
// 每1秒发出值
const secondSource = interval(1000);
const example = source.pipe(
  withLatestFrom(secondSource),
  map(([first, second]) => {
    return `First Source (5s): ${first} Second Source (1s): ${second}`;
  })
);
/*
  输出:
  "First Source (5s): 0 Second Source (1s): 4"
  "First Source (5s): 1 Second Source (1s): 9"
  "First Source (5s): 2 Second Source (1s): 14"
  ...
*/
const subscribe = example.subscribe(val => console.log(val));
```

##### 示例 2: 第二个 source 发出频率更慢一些

(
[StackBlitz](https://stackblitz.com/edit/typescript-gigsdv?file=index.ts&devtoolsheight=100)
| [jsBin](http://jsbin.com/vujekucuxa/1/edit?js,console) |
[jsFiddle](https://jsfiddle.net/btroncone/bywLL579/) )

```js
// RxJS v6+
import { withLatestFrom, map } from 'rxjs/operators';
import { interval } from 'rxjs';

// 每5秒发出值
const source = interval(5000);
// 每1秒发出值
const secondSource = interval(1000);
// withLatestFrom 的 observable 比源 observable 慢
const example = secondSource.pipe(
  // 两个 observable 在发出值前要确保至少都有1个值 (需要等待5秒)
  withLatestFrom(source),
  map(([first, second]) => {
    return `Source (1s): ${first} Latest From (5s): ${second}`;
  })
);
/*
  "Source (1s): 4 Latest From (5s): 0"
  "Source (1s): 5 Latest From (5s): 0"
  "Source (1s): 6 Latest From (5s): 0"
  ...
*/
const subscribe = example.subscribe(val => console.log(val));
```

### 相关食谱

- [进度条](../../recipes/progressbar.md)
- [游戏循环](../../recipes/gameloop.md)

### 其他资源

- [withLatestFrom](https://cn.rx.js.org/class/es6/Observable.js~Observable.html#instance-method-withLatestFrom) :newspaper: - 官方文档
- [组合操作符: withLatestFrom](https://egghead.io/lessons/rxjs-combination-operator-withlatestfrom?course=rxjs-beyond-the-basics-operators-in-depth) :video_camera: :dollar: - André Staltz

---
> :file_folder: 源码:  [https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.ts](https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/withLatestFrom.ts)


text:
define([
    './defaultValue',
    './defined',
    './defineProperties',
    './deprecationWarning',
    './DeveloperError'
], function(
    defaultValue,
    defined,
    defineProperties,
    deprecationWarning,
    DeveloperError) {
    'use strict';

    var nextCreditId = 0;
    var creditToId = {};

    /**
     * A credit contains data pertaining to how to display attributions/credits for certain content on the screen.
     * @param {Object} [options] An object with the following properties
     * @param {String} [options.text] The text to be displayed on the screen if no imageUrl is specified.
     * @param {String} [options.imageUrl] The source location for an image
     * @param {String} [options.link] A URL location for which the credit will be hyperlinked
     * @param {String} [options.showOnScreen=false] If true, the credit will be visible in the main credit container.  Otherwise, it will appear in a popover
     *
     * @alias Credit
     * @constructor
     *
     * @example
     * //Create a credit with a tooltip, image and link
     * var credit = new Cesium.Credit('Cesium', '/images/cesium_logo.png', 'http://cesiumjs.org/');
     */
    function Credit(options, imageUrl, link) {
        var text;
        var showOnScreen;
        if (typeof options !== 'object') {
            deprecationWarning('Credit parameters', 'The Credit text, imageUrl and link parameters have been replaced by a single options object parameter with text, imageUrl and link properties. Use of the old parameters will be removed in Cesium 1.41');
            text = options;
            showOnScreen = false;
        } else {
            text = options.text;
            imageUrl = options.imageUrl;
            link = options.link;
            showOnScreen = defaultValue(options.showOnScreen, false);
        }

        var hasLink = (defined(link));
        var hasImage = (defined(imageUrl));
        var hasText = (defined(text));

        //>>includeStart('debug', pragmas.debug);
        if (!hasText && !hasImage && !hasLink) {
            throw new DeveloperError('text, imageUrl or link is required');
        }
        //>>includeEnd('debug');

        if (!hasText && !hasImage) {
            text = link;
        }

        this._text = text;
        this._imageUrl = imageUrl;
        this._link = link;
        this._hasLink = hasLink;
        this._hasImage = hasImage;
        this._showOnScreen = showOnScreen;

        // Credits are immutable so generate an id to use to optimize equal()
        var id;
        var key = JSON.stringify([text, imageUrl, link]);

        if (defined(creditToId[key])) {
            id = creditToId[key];
        } else {
            id = nextCreditId++;
            creditToId[key] = id;
        }

        this._id = id;
    }

    defineProperties(Credit.prototype, {
        /**
         * The credit text
         * @memberof Credit.prototype
         * @type {String}
         * @readonly
         */
        text : {
            get : function() {
                return this._text;
            }
        },

        /**
         * The source location for the image.
         * @memberof Credit.prototype
         * @type {String}
         * @readonly
         */
        imageUrl : {
            get : function() {
                return this._imageUrl;
            }
        },

        /**
         * A URL location for the credit hyperlink
         * @memberof Credit.prototype
         * @type {String}
         * @readonly
         */
        link : {
            get : function() {
                return this._link;
            }
        },

        /**
         * @memberof Credit.prototype
         * @type {Number}
         * @readonly
         *
         * @private
         */
        id : {
            get : function() {
                return this._id;
            }
        },

        /**
         * Whether the credit should be displayed on screen or in a lightbox
         * @memberof Credit.prototype
         * @type {Boolean}
         * @readonly
         */
        showOnScreen : {
            get : function() {
                return this._showOnScreen;
            }
        }
    });

    /**
     * Returns true if the credit has an imageUrl
     *
     * @returns {Boolean}
     */
    Credit.prototype.hasImage = function() {
        return this._hasImage;
    };

    /**
     * Returns true if the credit has a link
     *
     * @returns {Boolean}
     */
    Credit.prototype.hasLink = function() {
        return this._hasLink;
    };

    /**
     * Returns true if the credits are equal
     *
     * @param {Credit} left The first credit
     * @param {Credit} right The second credit
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Credit.equals = function(left, right) {
        return (left === right) ||
               ((defined(left)) &&
                (defined(right)) &&
                (left._id === right._id));
    };

    /**
     * Returns true if the credits are equal
     *
     * @param {Credit} credit The credit to compare to.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Credit.prototype.equals = function(credit) {
        return Credit.equals(this, credit);
    };

    return Credit;
});


text:
'use strict';

angular.module('feeds-services', []).factory('feedService', ['$q', '$sce', 'feedCache', function ($q, $sce, feedCache) {

    function sanitizeFeedEntry(feedEntry) {
      feedEntry.title = $sce.trustAsHtml(feedEntry.title);
      feedEntry.contentSnippet = $sce.trustAsHtml(feedEntry.contentSnippet);
      feedEntry.content = $sce.trustAsHtml(feedEntry.content);
      feedEntry.publishedDate = new Date(feedEntry.publishedDate).getTime();
      return feedEntry;
    }

    function sanitizeEntries(entries) {
      for (var i = 0; i < entries.length; i++) {
        sanitizeFeedEntry(entries[i]);
      }
    }

    var getFeeds = function (feedURL, count) {
      var deferred = $q.defer();

      if (feedCache.hasCache(feedURL)) {
        var entries = feedCache.get(feedURL);
        sanitizeEntries(entries);
        deferred.resolve(entries);
      }

      var feed = new google.feeds.Feed(feedURL);
      if (count) {
        feed.includeHistoricalEntries();
        feed.setNumEntries(count);
      }

      feed.load(function (response) {
        if (response.error) {
          deferred.reject(response.error);
        }
        else {
          feedCache.set(feedURL, response.feed.entries);
          sanitizeEntries(response.feed.entries);
          deferred.resolve(response.feed.entries);
        }
      });
      return deferred.promise;
    };

    return {
      getFeeds: getFeeds
    };
  }])
  .factory('feedCache', function () {
    var CACHE_INTERVAL = 1000 * 60 * 5; //5 minutes

    function cacheTimes() {
      if ('CACHE_TIMES' in localStorage) {
        return angular.fromJson(localStorage.getItem('CACHE_TIMES'));
      }
      return {};
    }

    function hasCache(name) {
      var CACHE_TIMES = cacheTimes();
      return name in CACHE_TIMES && name in localStorage && new Date().getTime() - CACHE_TIMES[name] < CACHE_INTERVAL;
    }

    return {
      set: function (name, obj) {
        localStorage.setItem(name, angular.toJson(obj));
        var CACHE_TIMES = cacheTimes();
        CACHE_TIMES[name] = new Date().getTime();
        localStorage.setItem('CACHE_TIMES', angular.toJson(CACHE_TIMES));
      },
      get: function (name) {
        if (hasCache(name)) {
          return angular.fromJson(localStorage.getItem(name));
        }
        return null;
      },
      hasCache: hasCache
    };
  });


text:
import argparse, re, time
from assume_role_lib import log, sts
from assume_role_lib.util import unwrap
from datetime import datetime, timedelta

__version__ = '0.1'
logger = None

def add_arguments(argument_parser):
    argument_parser.add_argument(
        '--version', '-V',
        action  = 'version',
        version = '%(prog)s {0}'.format(__version__),
        help    = 'Show version information and exit.',
    )

    argument_parser.add_argument(
        '--describe-instances-filter',
        metavar = 'FILTER',
        action  = 'append',
        default = [ 'Name=instance-state-name,Values=pending,running' ],
        help    = unwrap("""
            Filters to apply when searching for instances whose logs will be
            searched. At the very least you should add a filter for the
            StackPrefix: Name=tag:StackPrefix,Values=<stack_prefix>.
        """)
    )
    argument_parser.add_argument(
        '--log-group',
        metavar = 'NAME',
        default = '/var/log/cloud-init-output.log',
        help    = 'The log group to search in.',
    )
    argument_parser.add_argument(
        '--timeout',
        metavar = 'TIME',
        default = '15m',
        help    = unwrap("""
            Stack timeout: XXn; for n - d = days, h = hour, m = mins, s =
            seconds.
        """)
    )

def parse_filter(filter):
    logger.debug('parse_filter: Parsing %r', filter)
    match = re.match(r'^Name=(?P<Name>[^,]+),Values=(?P<Values>.*)$', filter)
    if match:
        filters = match.groupdict()
        return filters['Name'], filters['Values'].split(',')
    else:
        return ()

def parse_timeout(timeout):
    days, hours, minutes, seconds = 0, 0, 0, 0
    findall = re.findall(r'([0-9]+)([dhms])', timeout.lower())
    for number, unit in findall:
        number = int(number)
        if unit == 'd':
            days = number
        elif unit == 'h':
            hours = number
        elif unit == 'm':
            minutes = number
        elif unit == 's':
            seconds = number
    return timedelta(days, seconds, 0, 0, minutes, hours)

def find_instances(ec2, args):
    filters = dict((
        parse_filter(f) for f in args.describe_instances_filter
    ))
    logger.debug('Filters: %r', filters)

    instances = list(ec2.instances.filter(
        Filters = [ {'Name': k, 'Values': v} for k,v in filters.items() ]
    ))

    return ( instance(i) for i in instances )

class instance(object):
    _component = None
    def __init__(self, instance_info):
        self._info = instance_info

    def __repr__(self):
        return 'instance(id = {0}, component = {1})'.format(self.id, self.component)

    @property
    def id(self):
        return self._info.id

    @property
    def component(self):
        if self._component is None:
            component = {
                t['Key']: t['Value'] for t in self._info.tags
            }.get('Component', 'unknown')
            self._component = component
        return self._component

serverspec_re = re.compile(r'(?P<examples>[0-9]+) examples?, (?P<failures>[0-9]+) failures?')
def parse_event_message(message):
    for line in message.splitlines():
        match = serverspec_re.match(line)
        if match:
            d = match.groupdict()
            examples = int(d['examples'])
            failures = int(d['failures'])
            return line, examples, failures
    return None, None, None

def main():
    global logger
    p = argparse.ArgumentParser(
        description=unwrap("""
            Tail CloudWatch Logs for a stack, looking for ServerSpec test
            output lines. Will exit non-zero if ServerSpec test failures are
            detected.
        """),
    )
    sts.add_arguments(p)
    log.add_arguments(p)
    add_arguments(p)
    args = p.parse_args()

    logger = log.get_logger(args)
    logger.debug('Args: %r', args)
    session = sts.get_session(args)

    ec2 = session.resource('ec2')
    instances = { i.id: i for i in find_instances(ec2, args) }
    logger.info(
        'Found %d instances: %r', len(instances), instances
    )
    instance_ids = set( instances.keys() )
    complete_instance_ids = set()

    cwlogs = session.client('logs')
    filter_log_events_args = dict(
        logGroupName = args.log_group,
        filterPattern = 'example',
    )
    all_examples, all_failures = 0, 0
    remaining_instance_ids = instance_ids - complete_instance_ids
    timeout = datetime.now() + parse_timeout(args.timeout)
    while remaining_instance_ids:
        logger.info('Waiting for %d instances to complete ServerSpec tests.', len(remaining_instance_ids))
        logger.debug('%r', remaining_instance_ids)
        filter_log_events_args['logStreamNames'] = list(remaining_instance_ids)
        try:
            filtered_events = cwlogs.filter_log_events(**filter_log_events_args)
            events = filtered_events['events']
        except:
            logger.exception('Caught an exception while polling for log events.')
            events = []
        for event in events:
            instance = instances[event['logStreamName']]
            matched, ex, fa = parse_event_message(event['message'])
            if matched:
                complete_instance_ids.add(event['logStreamName'])
                all_examples += ex
                all_failures += fa
                if fa > 0:
                    logger.error(
                        'Error in ServerSpec for %r - %s',
                        instance, matched
                    )
                else:
                    logger.info(
                        'ServerSpec complete for %r - %s',
                        instance, matched
                    )
        remaining_instance_ids = instance_ids - complete_instance_ids
        if datetime.now() > timeout:
            logger.error('Timeout waiting for stack to complete. %d instances have not completed.', len(remaining_instance_ids))
            for instance in remaining_instance_ids:
                logger.error('ServerSpec did not complete on %r', instances[instance])
            raise SystemExit(2)
        if len(events) == 0:
            time.sleep(10)
        else:
            time.sleep(1)

        # corner case: an existing instance might be replaced by a new one
        current_instances = {i.id: i for i in find_instances(ec2, args)}
        new_instances = [x for x in list(current_instances.items()) if x[0] not in instance_ids]
        if len(new_instances) > 0:
            logger.info(
                'Found %d new instances %r', len(new_instances), new_instances
            )
            instances = current_instances
            instance_ids = set(current_instances.keys())
            remaining_instance_ids = instance_ids - complete_instance_ids

    if all_failures > 0:
        raise SystemExit(1)

if __name__ == '__main__':
    main()


text:
const _ = require('lodash');
const ghostBookshelf = require('./base');

const candidates = [];

_.each(ghostBookshelf.registry.models, (model) => {
    candidates.push([model, model.prototype.tableName.replace(/s$/, '')]);
});

const Action = ghostBookshelf.Model.extend({
    tableName: 'actions',

    actor() {
        return this.morphTo('actor', ['actor_type', 'actor_id'], ...candidates);
    },

    resource() {
        return this.morphTo('resource', ['resource_type', 'resource_id'], ...candidates);
    },

    toJSON(unfilteredOptions) {
        const options = Action.filterOptions(unfilteredOptions, 'toJSON');
        const attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options);

        // @TODO: context is not implemented yet
        delete attrs.context;

        return attrs;
    }
}, {
    orderDefaultOptions: function orderDefaultOptions() {
        return {
            created_at: 'DESC'
        };
    },

    add(data, unfilteredOptions = {}) {
        const options = this.filterOptions(unfilteredOptions, 'add');
        return ghostBookshelf.Model.add.call(this, data, options);
    }
});

module.exports = {
    Action: ghostBookshelf.model('Action', Action)
};


text:
void xt_core_iobject_init(xt_core_iobject_t *iobject,
    xt_core_object_compare_f compare,
    xt_core_object_compare_equal_f compare_equal,
    xt_core_object_copy_f copy, xt_core_object_destroy_f destroy,
    xt_core_object_get_as_string_f get_as_string, xt_core_object_mod_f mod)
{
  assert(iobject);

  iobject->compare = compare;
  iobject->compare_equal = compare_equal;
  iobject->copy = copy;
  iobject->destroy = destroy;
  iobject->get_as_string = get_as_string;
  iobject->mod = mod;
}


text:
> Launcher for Internet Explorer.

## Installation

The easiest way is to keep `karma-ie-launcher` as a devDependency in your `package.json`.
```json
{
  "devDependencies": {
    "karma": "~0.10",
    "karma-ie-launcher": "~0.1"
  }
}
```

You can simple do it by:
```bash
npm install karma-ie-launcher --save-dev
```

## Configuration
```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    browsers: ['IE']
  });
};
```

You can pass list of browsers as a CLI argument too:
```bash
karma start --browsers IE
```

----

For more information on Karma see the [homepage].

[homepage]: http://karma-runner.github.com


text:
<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = 'Logins';
$this->params['breadcrumbs'][] = $this->title;
?>

            <?php $form = ActiveForm::begin([
					'options'=>['class' => 'sign-box'],

					]); ?>

				Sign In
                <?= $form->field($model, 'email')->textInput(['autofocus' => true]) ?>

                <?= $form->field($model, 'password')->passwordInput() ?>

                        <input type="checkbox" id="signed-in"/>
                        Keep me signed in

                        Reset Password

                    <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>

            <?php ActiveForm::end(); ?>


text:
angular.module('rome-angular')
  .directive('rome', romeDirective);

romeDirective.$inject = ['romeConfig'];

function romeDirective(romeConfigProvider) {
  return {
    restrict: 'A',
    scope: {
      rome: '=',
      romeChange: '&',
      romeOptions: '='
    },
    link: function(scope, element, attrs, ctrl, $parse) {
      // getting the default options set up via romeConfigProvider
      this.options = (typeof (romeConfigProvider.defaults) == 'object') ?
        angular.copy(romeConfigProvider.defaults) : {};
      // getting the options defined for this element via scope.romeOptions
      // they will override the options set up via romeConfigProvider
      if (typeof (scope.romeOptions) == 'object') {
        for (var item in scope.romeOptions) {
          if (scope.romeOptions.hasOwnProperty(item)) {
            this.options[item] = scope.romeOptions[item];
          }
        }
      }
      // getting the initialValue, priority being :
      // 1. from options (i.e. via romeConfigProvider or via romeOptions)
      // 2. from scope.rome
      // 3. new Date()
      if (typeof (this.options.initialValue) == typeof undefined) {
        this.options.initialValue = (typeof (scope.rome) == typeof undefined) ?
          new Date() : new Date(scope.rome);
      }
      // initializing rome
      var cal = rome(element[0], this.options);
      // storing the oldDate somewhere to avoid triggering changes too often
      cal.oldDate = angular.copy(cal.getDate());
      // catching rome updating the value
      // unfortunately, value = cal.getDateString() which is not interesting for us
      // we're working with javascript dates which are provided by cal.getDate()
      cal.on('data', function(value) {
        var newDate = cal.getDate();
        // only if date changed since last time
        if (newDate.toString() != cal.oldDate) {
          // triggering scope update and storing oldDate for the next change
          scope.$apply(function() {
            scope.rome = newDate;
            cal.oldDate = angular.copy(newDate);
          }, true);
          // triggering change function
          if (typeof (scope.romeChange) == 'function') {
            scope.$apply(function() {
              scope.romeChange();
            }, true);
          }
        }
      });
      // on angular programmatically updating rome's underlying value
      scope.$watch('rome', function(newValue, oldValue) {
        // only if date changed since last time
        if (typeof (newValue) != typeof undefined &&
          newValue.toString() != cal.oldDate) {
          // updating rome object + the element value (displayed to the user)
          cal.setValue(newValue);
          element[0].value = cal.getDateString();
          // triggering change function
          if (typeof (scope.romeChange) == 'function') {
            scope.romeChange();
          }
        }
      }, true);
    }
  };
}


text:
package com.amazonaws.services.lambda.model.transform;

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

import com.amazonaws.services.lambda.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * GetFunctionResult JSON Unmarshaller
 */
public class GetFunctionResultJsonUnmarshaller implements
        Unmarshaller<GetFunctionResult, JsonUnmarshallerContext> {

    public GetFunctionResult unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        GetFunctionResult getFunctionResult = new GetFunctionResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Configuration", targetDepth)) {
                    context.nextToken();
                    getFunctionResult
                            .setConfiguration(FunctionConfigurationJsonUnmarshaller
                                    .getInstance().unmarshall(context));
                }
                if (context.testExpression("Code", targetDepth)) {
                    context.nextToken();
                    getFunctionResult
                            .setCode(FunctionCodeLocationJsonUnmarshaller
                                    .getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return getFunctionResult;
    }

    private static GetFunctionResultJsonUnmarshaller instance;

    public static GetFunctionResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new GetFunctionResultJsonUnmarshaller();
        return instance;
    }
}


text:
<?php
namespace Attendee;

class Module {
    function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}


text:
package com.neucrack.tool;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Session {
	static private HashMap<Object, Object> mAttribute = new HashMap<Object, Object>();//¼Ç¼¼üÖµ
	static private Map<Object,Long> mTime = new HashMap<Object, Long>();//¼Ç¼ʱ¼ä´Á
	static private ArrayList<Object> mKeys= new ArrayList<Object>();
	static private long mMaxInactiveInterval = 7776000;//ÉèÖó¬Ê±Ê±¼ä 90Ìì(7776000s)
	static private long mAutoClearInterval = 7776000;//×Ô¶¯Çå³ýʧЧµÄsession

	public Session() {
		mMaxInactiveInterval = 1800000;//30·ÖÖÓ
		mAutoClearInterval = mMaxInactiveInterval;
	}

	static public Object getAttribute(Object key) {
		if(!mAttribute.containsKey(key))
			return null;
		if(System.currentTimeMillis() - mTime.get(key) > mMaxInactiveInterval)
			return null;
		return mAttribute.get(key);
	}

	static public Object setAttribute(Object key, Object value) {
		mTime.put(key, System.currentTimeMillis());
		mKeys.add(key);
		return mAttribute.put(key, value);

	}
	static public void invalidate() {
		mAttribute.clear();
	}

	static public long getMaxInactiveInterval() {
		return mMaxInactiveInterval;
	}

	static public void setMaxInactiveInterval(long maxInactiveInterval) {
		mMaxInactiveInterval = maxInactiveInterval;
	}

	static public long getmAutoClearInterval() {
		return mAutoClearInterval;
	}

	static public void setmAutoClearInterval(long mAutoClearInterval) {
		mAutoClearInterval = mAutoClearInterval;
	}

	public void EnableAutoClear() {
		AutoClear autoClear = new AutoClear();
		autoClear.start();
	}
	private class AutoClear extends Thread{

		@Override
		public void run() {
			super.run();
			while(true){
				for(int i=0;i<mAttribute.size();++i){
					if(System.currentTimeMillis() - mTime.get(mKeys.get(i)) > mMaxInactiveInterval)
						mAttribute.remove(mKeys.get(i));
				}
				try {
					Thread.sleep(mAutoClearInterval);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}


text:
#ifndef CORE_CONST_H
#define CORE_CONST_H
#include <string>

typedef int Uid; //object in world id
typedef int Tid; //agent class id
typedef std::string Tex;
typedef std::string Id; //database id

#endif // CORE_CONST_H


text:
<?php

namespace Ridwan\EntityBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Ridwan\EntityBundle\Entity\Skills;
use Ridwan\EntityBundle\Form\SkillsType;

/**
 * Skills controller.
 *
 * @Route("/skills")
 */
class SkillsController extends Controller
{

    /**
     * Lists all Skills entities.
     *
     * @Route("/", name="skills")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('RidwanEntityBundle:Skills')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Skills entity.
     *
     * @Route("/", name="skills_create")
     * @Method("POST")
     * @Template("RidwanEntityBundle:Skills:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Skills();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('skills_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Skills entity.
     *
     * @param Skills $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Skills $entity)
    {
        $form = $this->createForm(new SkillsType(), $entity, array(
            'action' => $this->generateUrl('skills_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Skills entity.
     *
     * @Route("/new", name="skills_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Skills();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Skills entity.
     *
     * @Route("/{id}", name="skills_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RidwanEntityBundle:Skills')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Skills entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Skills entity.
     *
     * @Route("/{id}/edit", name="skills_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RidwanEntityBundle:Skills')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Skills entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Skills entity.
    *
    * @param Skills $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Skills $entity)
    {
        $form = $this->createForm(new SkillsType(), $entity, array(
            'action' => $this->generateUrl('skills_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Skills entity.
     *
     * @Route("/{id}", name="skills_update")
     * @Method("PUT")
     * @Template("RidwanEntityBundle:Skills:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('RidwanEntityBundle:Skills')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Skills entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('skills_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Skills entity.
     *
     * @Route("/{id}", name="skills_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('RidwanEntityBundle:Skills')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Skills entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('skills'));
    }

    /**
     * Creates a form to delete a Skills entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('skills_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>My first article title</title>
    <link href="themes/default/theme.css" rel="stylesheet" type="text/css">

<input id="q" name="q" placeholder="Search here ...">

                    php
                     programming
                    phpstorm
                     debug
                     xdebug
                     zend debugger
                     php

My first article title

<time datetime=""></time>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum commodo tortor, luctus gravida ipsum blandit eu.
    Pellentesque molestie enim elementum, maximus velit quis, facilisis risus. Cras mollis diam orci, ut vulputate augue faucibus malesuada.
    Nam quis pellentesque metus. Sed euismod, ipsum sit amet pellentesque pulvinar, ipsum mauris finibus metus, vitae sodales nulla nulla ut quam.
    Sed tellus lorem, ultrices in arcu in, rhoncus faucibus lectus. Nam eu felis ac orci bibendum placerat sed et enim. Morbi et nulla in elit egestas
    accumsan quis eu massa. Sed eu lacus a velit bibendum malesuada eu nec libero. Donec ut nibh laoreet, malesuada ipsum eu, iaculis metus.
    Morbi imperdiet ultricies gravida. Morbi eget nunc libero.

Vivamus id varius ligula. Donec nec justo vitae massa feugiat aliquam. Aliquam molestie turpis non efficitur bibendum. Aenean ac sagittis turpis.
        Proin eget malesuada odio, ac fringilla ipsum. Etiam quis lacinia eros, ut aliquet urna. Sed gravida a felis consectetur interdum.
        Nam id tortor sed nunc cursus feugiat a venenatis justo. In laoreet augue sed hendrerit tempor. Morbi faucibus tempus ornare.

    php,  programming


text:
package com.cardpay.pccredit.manager.service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cardpay.pccredit.customer.model.CustomerInfor;
import com.cardpay.pccredit.customer.model.CustomerManagerTarget;
import com.cardpay.pccredit.customer.service.CustomerInforService;
import com.cardpay.pccredit.manager.constant.ManageLederPeriod;
import com.cardpay.pccredit.manager.constant.ManagerTargetType;
import com.cardpay.pccredit.manager.dao.StatisticsManagerDao;
import com.cardpay.pccredit.manager.model.DailyAccountManager;
import com.cardpay.pccredit.manager.model.LedgerAccountManager;
import com.cardpay.pccredit.manager.model.WeeklyAccountManager;
import com.cardpay.pccredit.manager.web.AccountManagerParameterForm;
import com.cardpay.pccredit.manager.web.WeeklyAccountManagerForm;
import com.cardpay.pccredit.system.model.SystemConfiguration;
import com.cardpay.pccredit.system.service.SystemConfigurationService;
import com.wicresoft.util.date.DateHelper;

/**
 * 客户经理统计 周/月/年
 *
 * @author Evans zhang
 *
 * 2014-11-18 下午2:09:26
 */
@Service
public class StatisticsScheduleService {

	@Autowired
	private StatisticsManagerDao statisticsManagerDao;

	@Autowired
	private AccountManagerParameterService accountManagerParameterService;

	@Autowired
	private WeeklyAccountService weeklyAccountService;

	@Autowired
	private DailyAccountService dailyAccountService;

	@Autowired
	private ManagerBelongMapService  managerBelongMapService;

	@Autowired
	private CustomerInforService customerInforService;

	@Autowired
	private LedgerAccountManagerService ledgerAccountManagerService;

	@Autowired
	private SystemConfigurationService systemConfigurationService;

	/**
	 * 判断系统是否按那个周期统计
	 */
	public boolean isLedger(ManagerTargetType managerTargetType){
		List<SystemConfiguration> systemConfigurationList=systemConfigurationService.findSystemConfigurationByCode(ManageLederPeriod.period);
		if(systemConfigurationList!=null&&systemConfigurationList.size()>0){
		if(managerTargetType.name().equals(systemConfigurationList.get(0).getSysValues())){
			return true;
		}
		}
		return false;
	}

	/**
	 * 统计客户经理生成上星期周报信息统计客户经理 授信额度 、进件数 、拜访次数、拜访客户数 、组进件数、组授信额度 。下个星期日报信息(星期天晚上生成)
	 */
	public void insertWeekSchedule(){
		try{
		Map<String, Integer> mapCountApply=new HashMap<String, Integer>();
		Map<String, Integer> mapCountApplication=new HashMap<String, Integer>();
		Map<String, Integer> mapCountNumber=new HashMap<String, Integer>();
		Map<String, Integer> mapCountCustomer=new HashMap<String, Integer>();

		  Date startTime=null;
		  Calendar date=Calendar.getInstance(Locale.CHINA);
		  date.setTime(new Date());
		  date.add(Calendar.DAY_OF_MONTH, -7);
		  startTime=date.getTime();

		  Calendar nextdate=Calendar.getInstance(Locale.CHINA);
		  nextdate.setTime(new Date());
		  nextdate.add(Calendar.WEEK_OF_MONTH, 1);
		  nextdate.set(Calendar.DAY_OF_WEEK, nextdate.getActualMinimum(Calendar.DAY_OF_WEEK));
		  nextdate.add(Calendar.DATE, 1);
		  String startDate=DateHelper.getDateFormat(nextdate.getTime(), "yyyy-MM-dd");
		  nextdate.add(Calendar.DATE, 4);
		  String endDate=DateHelper.getDateFormat(nextdate.getTime(), "yyyy-MM-dd");

		  String startMonthTime=null;
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			cal.set(Calendar.DAY_OF_MONTH,cal.getActualMinimum(Calendar.DAY_OF_MONTH));
			String startTimeStr=DateHelper.getDateFormat(cal.getTime(), "yyyy-MM-dd");
			startMonthTime=startTimeStr+" 00:00:00";

		//查找所有客户经理
		List<AccountManagerParameterForm> managerList=accountManagerParameterService.findAccountManagerParameterAll();
		for(AccountManagerParameterForm accountManagerParameterForm:managerList){
			//插入下星期周报和日报
			try{
			String title=accountManagerParameterForm.getDisplayName()+"("+startDate+"到"+endDate+")周报";
			WeeklyAccountManager weeklyAccountManager=new WeeklyAccountManager();
			weeklyAccountManager.setCustomerManagerId(accountManagerParameterForm.getUserId());
			weeklyAccountManager.setTitle(title);
			weeklyAccountManager.setCreatedTime(new Date());
			weeklyAccountManager.setModifiedTime(new Date());
			weeklyAccountService.insertWeeklyAccount(weeklyAccountManager);
			for(int i=1;i<=5;i++){
				DailyAccountManager dailyAccountManager=new DailyAccountManager();
				dailyAccountManager.setWeeklyId(weeklyAccountManager.getId());
				dailyAccountManager.setWhatDay(i);
				dailyAccountManager.setCreatedTime(new Date());
				dailyAccountManager.setModifiedTime(new Date());
				dailyAccountService.insertDailyAccount(dailyAccountManager);
			}

			//统计上周的客户信息 授信额度
			Integer totalApplyQuota=statisticsManagerDao.findCustomerApplyQuota(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
			mapCountApply.put(accountManagerParameterForm.getUserId(),totalApplyQuota);
			//统计上周的客户信息 进件数
			Integer totalApplicationNumber=statisticsManagerDao.findCountCustomer(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
			mapCountApplication.put(accountManagerParameterForm.getUserId(), totalApplicationNumber);
			//统计拜访次数
			List<Map<String, Object>> mapList=statisticsManagerDao.findVisitCustomerActionCount(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());

			Integer totalVisitCount=0;
 			for(Map<String, Object> map:mapList){
	 				if(map.get("visitCount")!=null){
	 					totalVisitCount=totalVisitCount+Integer.parseInt(map.get("visitCount").toString());
	 				}
 			}

 			mapCountNumber.put(accountManagerParameterForm.getUserId(), totalVisitCount);

 			//统计拜访客户数
 			Integer countCustomer=statisticsManagerDao.findCountVisitCustomer(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
 			mapCountCustomer.put(accountManagerParameterForm.getUserId(), countCustomer);
			}catch(Exception e){
				System.out.println("======================1"+accountManagerParameterForm.getUserId());
			}
		}

		for(AccountManagerParameterForm accountManagerParameterForm:managerList){
			try{
			//查询客户经理目标数
			CustomerManagerTarget customerManagerTarget=accountManagerParameterService.getcustomerManagerTargetBymanagerIdDate(accountManagerParameterForm.getUserId(),ManagerTargetType.year.name());
			if(customerManagerTarget!=null){
			//统计本月的客户信息 授信额度
			Integer totalMonthApplyQuota=statisticsManagerDao.findCustomerApplyQuota(startMonthTime,DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
			//统计本月的客户信息 进件数
			Integer totalMonthApplicationNumber=statisticsManagerDao.findCountCustomer(startMonthTime,DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());

			//统计组的授信额度
			Integer groupApply=0;
			Integer groupApplication=0;
			List<AccountManagerParameterForm> list=managerBelongMapService.findSubListManagerByManagerId(accountManagerParameterForm.getUserId());
			for(AccountManagerParameterForm chirdManager:list){
				groupApply=groupApply+mapCountApply.get(chirdManager.getUserId());
				groupApplication=groupApplication+mapCountApplication.get(chirdManager.getUserId());
			}

			List<WeeklyAccountManagerForm> listWeekly=weeklyAccountService.findWeeklyAccountByManagerId(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());

			WeeklyAccountManagerForm weeklyAccountManagerForm=null;
			if(listWeekly!=null){
				weeklyAccountManagerForm=listWeekly.get(0);
				WeeklyAccountManager weeklyAccountManager=new WeeklyAccountManager();
				weeklyAccountManager.setActualCredit(String.valueOf(mapCountApply.get(accountManagerParameterForm.getUserId())));
				weeklyAccountManager.setActualNumber(mapCountApplication.get(accountManagerParameterForm.getUserId()));
				weeklyAccountManager.setActualNumberCustomers(mapCountCustomer.get(accountManagerParameterForm.getUserId()));
				weeklyAccountManager.setActualNumberVisit(mapCountNumber.get(accountManagerParameterForm.getUserId()));
				weeklyAccountManager.setGroupCredit(String.valueOf(groupApply));
				weeklyAccountManager.setGroupNumber(groupApplication);
				weeklyAccountManager.setMonthlyCredit(String.valueOf(totalMonthApplyQuota/Integer.parseInt(customerManagerTarget.getTargetCredit())));
				weeklyAccountManager.setMonthlyNumber(String.valueOf(totalMonthApplicationNumber/customerManagerTarget.getTargetNumber()));
				weeklyAccountManager.setId(weeklyAccountManagerForm.getId());
				weeklyAccountService.updateWeeklyAccount(weeklyAccountManager);
			}
			}
			//台账
			if(isLedger(ManagerTargetType.weekly)){
			LedgerAccountManager  ledgerAccountManager=new LedgerAccountManager();
			 List<CustomerInfor> customerList=customerInforService.findCustomerByManagerId(accountManagerParameterForm.getUserId());
			ledgerAccountManager.setTubeNumber(String.valueOf(customerList.size())); //管户数
			ledgerAccountManager.setManagementCycle(ManagerTargetType.weekly.name());
			//客户拜访数 (营销、维护、催收)
			Integer countCustomer=statisticsManagerDao.findCountVisitCustomer(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerVisitNumber(String.valueOf(countCustomer));

			//客户维护数 (营销、维护)
			Integer countCustomerYw=statisticsManagerDao.findCountVisitCustomerYw(DateHelper.getDateFormat(startTime,"yyyy-MM-dd HH:mm:ss"),DateHelper.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"),accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerMaintenanceNumber(String.valueOf(countCustomerYw));

			ledgerAccountManager.setCreatedTime(DateHelper.normalizeDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
			ledgerAccountManagerService.insertLedgerAccountManager(ledgerAccountManager);

			}

			}catch(Exception e){
				System.out.println("=======================2"+accountManagerParameterForm.getUserId());
				e.printStackTrace();
			}
		}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void insertMonthSchedule(){
		//台账
		if(isLedger(ManagerTargetType.month)){
		String startTime=null;
		String endTime=null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		cal.set(Calendar.DAY_OF_MONTH,cal.getActualMinimum(Calendar.DAY_OF_MONTH));
		String startTimeStr=DateHelper.getDateFormat(cal.getTime(), "yyyy-MM-dd");
		startTime=startTimeStr+" 00:00:00";
		cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		endTime=DateHelper.getDateFormat(cal.getTime(), "yyyy-MM-dd")+" 23:59:59";
		//查找所有客户经理
		List<AccountManagerParameterForm> managerList=accountManagerParameterService.findAccountManagerParameterAll();
		for(AccountManagerParameterForm accountManagerParameterForm:managerList){
			LedgerAccountManager  ledgerAccountManager=new LedgerAccountManager();
			 List<CustomerInfor> customerList=customerInforService.findCustomerByManagerId(accountManagerParameterForm.getUserId());
			ledgerAccountManager.setTubeNumber(String.valueOf(customerList.size())); //管户数
			ledgerAccountManager.setManagementCycle(ManagerTargetType.month.name());
			//客户拜访数 (营销、维护、催收)
			Integer countCustomer=statisticsManagerDao.findCountVisitCustomer(startTime,endTime,accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerVisitNumber(String.valueOf(countCustomer));

			//客户维护数 (营销、维护)
			Integer countCustomerYw=statisticsManagerDao.findCountVisitCustomerYw(startTime,endTime,accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerMaintenanceNumber(String.valueOf(countCustomerYw));

			ledgerAccountManager.setCreatedTime(DateHelper.normalizeDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
			ledgerAccountManagerService.insertLedgerAccountManager(ledgerAccountManager);
		}
		}
	}

	public void insertYearSchedule(){
		//台账
		if(isLedger(ManagerTargetType.year)){
		String startTime=null;
		String endTime=null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.YEAR, -1);
		startTime=cal.get(Calendar.YEAR)+"-01-01 00:00:00";
		endTime=cal.get(Calendar.YEAR)+"-12-31 23:59:59";

		endTime=DateHelper.getDateFormat(cal.getTime(), "yyyy-MM-dd")+" 23:59:59";
		//查找所有客户经理
		List<AccountManagerParameterForm> managerList=accountManagerParameterService.findAccountManagerParameterAll();
		for(AccountManagerParameterForm accountManagerParameterForm:managerList){
			LedgerAccountManager  ledgerAccountManager=new LedgerAccountManager();
			 List<CustomerInfor> customerList=customerInforService.findCustomerByManagerId(accountManagerParameterForm.getUserId());
			ledgerAccountManager.setTubeNumber(String.valueOf(customerList.size())); //管户数
			ledgerAccountManager.setManagementCycle(ManagerTargetType.year.name());
			//客户拜访数 (营销、维护、催收)
			Integer countCustomer=statisticsManagerDao.findCountVisitCustomer(startTime,endTime,accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerVisitNumber(String.valueOf(countCustomer));

			//客户维护数 (营销、维护)
			Integer countCustomerYw=statisticsManagerDao.findCountVisitCustomerYw(startTime,endTime,accountManagerParameterForm.getUserId());
			ledgerAccountManager.setCustomerMaintenanceNumber(String.valueOf(countCustomerYw));

			ledgerAccountManager.setCreatedTime(DateHelper.normalizeDate(new Date(),"yyyy-MM-dd HH:mm:ss"));

			ledgerAccountManagerService.insertLedgerAccountManager(ledgerAccountManager);
		}
		}
	}
	public Integer findCustomerApplyQuota(String customerManagerId){
		return statisticsManagerDao.findCustomerApplyQuota(null, null, customerManagerId);
	}
}


text:
import { createStore, applyMiddleware, Middleware, GenericStoreEnhancer, compose } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';
import { createLogicMiddleware } from 'redux-logic';
import { rootReducer } from './reducers';
import { initialState as defaultInitialState } from './state';
import apolloClient from './apolloClient';
import rootLogic from './logic';
import axios from 'axios';

const isClient = typeof document !== 'undefined';

declare var window: { __INITIAL_STATE__: {} };
const initialState = isClient ? window.__INITIAL_STATE__ : defaultInitialState;

function createThunkMiddleware() {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState);
    }

    return next(action);
  };
}

const dependencies = {
  httpClient: axios,
};

const thunk = createThunkMiddleware();
const logicMiddleware = createLogicMiddleware(rootLogic, dependencies);
const apolloClientMiddleware = apolloClient.middleware();

const middlewares: Middleware[] = [
  thunk,
  apolloClientMiddleware,
  logicMiddleware,
];

const enhancers: GenericStoreEnhancer[] = [
  applyMiddleware(...middlewares),
];

const ReduxExtentionComposeName: string = '__REDUX_DEVTOOLS_EXTENSION_COMPOSE__';
const composeEnhancers =
  process.env.NODE_ENV !== 'production' &&
  typeof window === 'object' &&
    window[ReduxExtentionComposeName] ?
    window[ReduxExtentionComposeName] : compose;

const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(...enhancers),
);

export const history = isClient ?
  syncHistoryWithStore(browserHistory, store) : undefined;

export default store;


text:
<?php

namespace Mmoreram\TranslationServer\Command;

use Exception;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Mmoreram\TranslationServer\Command\Abstracts\AbstractTranslationServerCommand;

/**
 * Class SortCommand
 */
class SortCommand extends AbstractTranslationServerCommand
{
    /**
     * configure
     */
    protected function configure()
    {
        $this
            ->setName('translation:server:sort')
            ->setDescription('Sort translations');

        parent::configure();
    }

    /**
     * Execute command
     *
     * @param InputInterface  $input  Input
     * @param OutputInterface $output Output
     *
     * @return int|null|void
     *
     * @throws Exception
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->startCommand($output, false);
        $this
            ->createProject($input)
            ->sort()
            ->save();

        $this
            ->printMessage(
                $output,
                'Trans Server',
                'Your translations have been sorted successfuly'
            );

        $this->finishCommand($output);
    }
}


text:
module.exports = (req, res) => {
  res.end(req.query.endpoint);
};


text:
package com.bitbunker;

import com.bitbunker.api.Client;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * File represents a file stored in BitBunker
 *
 * @author Chris Umbel
 * @version     %I%, %G%
 *
 */
public class File extends BitBunkerObject {
    public enum Status {
        QUEUED,
        PULLING,
        RECEIVED,
        PULL_FAILED,
        UNKNOWN
    };

    public enum Durability {
        PARTIAL,
        COMPLETE,
        UNKOWN
    };

    private Date created;
    private boolean received;
    private boolean inCache;
    private Durability durability;
    private Status status;

    /**
     * create a File object representing a file in BitBunker and connect it
     * to the service
     *
     * @param path          path to the file in BitBunker
     * @param client        client used for authentication and connectivity
     *
     */
    public File(String path, Client client) {
        this(path);
        this.setClient(client);
    }

    /**
     * create a File object representing a file in BitBunker at a given path
     *
     * @param path          path to the file in BitBunker
     *
     */
    public File(String path) {
        super(path);
        this.name = new java.io.File(path).getName();
    }

    /**
     * create a File object representing a file in BitBunker
     */
    public File() {
        super();
    }

    /**
     * set the transfer status of the File
     *
     * @param statusString   transfer status of the file. parsed into an item
     *                       from the File.Status enum
     */
    public void setStatus(String statusString) {
        this.setStatus(File.parseStatus(statusString));
    }

    /**
     * parse a transfer status string into an item from the File.Status enum enum
     *
     * @param statusString      string representation of a transfer status
     * @return an item from the File.Status enum enum
     */
    public static File.Status parseStatus(String statusString) {
        if(statusString.equals("Received"))
            return File.Status.RECEIVED;
        else if(statusString.equals("PullFailed"))
            return File.Status.PULL_FAILED;
        else if(statusString.equals("Pulling"))
            return File.Status.PULLING;
        else if(statusString.equals("Queued"))
            return File.Status.QUEUED;
        else
            return File.Status.UNKNOWN;
    }

    private boolean handleStatusAttribute(StringBuilder attributes) {
        switch (this.getStatus()) {
            case QUEUED:
                attributes.append("Q");
                break;
            case PULLING:
                attributes.append("P");
                break;
            case RECEIVED:
                attributes.append("R");
                break;
            default:
                attributes.append("err");
                return false;
        }

        return true;
    }

    private void handleDurabilityAttribute(StringBuilder attributes) {
        switch(this.getDurability()) {
            case COMPLETE:
                attributes.append("D");
                break;
            case PARTIAL:
                attributes.append("d");
                break;
            default:
                attributes.append("-");
        }
    }

    /**
     * get a summary string of the attributes of a file
     *
     */
    public String getAttributes() {
        StringBuilder attributes = new StringBuilder();

        if(this.handleStatusAttribute(attributes)) {
            attributes.append(this.isInCache() ? "C" : "-");
            this.handleDurabilityAttribute(attributes);
        }

        return attributes.toString();
    }

    /**
     * see if the file is stored in ephemeral disk cache
     *
     * @return weather the file is stored in ephemeral disk cache
     *
     */
    public boolean isInCache() {
        return inCache;
    }

    /**
     * see if the file is stored in ephemeral disk cache
     *
     * @return weather the file is stored in ephemeral disk cache
     *
     */
    public void setInCache(boolean inCache) {
        this.inCache = inCache;
    }

    /**
     * get the transfer status of the file
     *
     * @return the transfer status of the file
     *
     */
    public Status getStatus() {
        return status;
    }

    /**
     * get a string representing the transfer status of a file
     *
     * @return a string representing the transfer status of a file
     *
     */
    public String getStatusString() {
        switch(status) {
            case QUEUED:
                return "Queued";
            case RECEIVED:
                return "Received";
            case PULLING:
                return "Pulling";
            case PULL_FAILED:
                return "PullFailed";
        }

        return "Unkown";
    }

    /**
     * set the transfer status of a File
     *
     * @param status        transfer status of the file
     */
    public void setStatus(Status status) {
        this.status = status;
    }

    /**
     * determine weather or not the file achieved the desired durability (has
     * it been copied to as many volumes as the user desired)
     *
     * @return weather or not the file achieved the desired durability if known
     *
     */
    public Durability getDurability() {
        return this.durability;
    }

    /**
     * set weather or not the file achieved the desired durability (has
     * it been copied to as many volumes as the user desired)
     *
     * @param durability            weather or not the file achieved the desired
     *                              durability if known
     */
    public void setDurability(Durability durability) {
        this.durability = durability;
    }

    /**
     * determine if the file was received over the network from the user
     *
     * @return  if the file was received over the network from the user
     *
     */
    public boolean isReceived() {
        return received;
    }

    /**
     * if the file was received over the network from the user
     *
     * @param received          if the file was received over the network
     *                          from the user
     */
    public void setReceived(boolean received) {
        this.received = received;
    }

    /**
     * get the date/time the file was created in BitBunker
     *
     * @return the date/time the file was created in BitBunker
     *
     */
    public Date getCreated() {
        return created;
    }

    /**
     * set the date/time the file was created in BitBunker
     *
     * @param created           the date/time the file was created in BitBunker
     *
     */
    public void setCreated(Date created) {
        this.created = created;
    }

    /**
     * get the file form BitBunker and store it on the local filesystem at a
     * specified path
     *
     * @param localPath             location on the local filesystem to store the
     *                              file
     * @throws BitBunkerException
     *
     */
    public void get(String localPath) throws BitBunkerException {
        checkConnected();
        this.getClient().get(this, localPath);
    }

    /**
     * get the file from BitBunker and hand off a stream to caller to handle
     * the data transmission
     *
     * @return                      stream of the file's data form BitBunker
     * @throws BitBunkerException
     *
     */
    public InputStream openStream() throws BitBunkerException {
        checkConnected();
        return this.getClient().getStream(this);
    }

    /**
     * get the file from BitBunker, save it, and return a java.io.File pointer
     * to it
     *
     * @param localPath             location on the local filesystem to store
     *                              the file
     * @return                      java.io.File pointer to the file
     * @throws BitBunkerException
     *
     */
    public java.io.File getfile(String localPath) throws BitBunkerException {
        checkConnected();
        return this.getClient().getFile(this, localPath);
    }

    /**
     * get the file from BitBunker and store it as the specified remote location
     *
     * @param address               remote address at which to store the file
     * @throws BitBunkerException
     *
     */
    public void getTo(String address) throws BitBunkerException {
        checkConnected();
        this.getClient().getTo(this, address);
    }

    /**
     * get the file from BitBunker and store it as the specified remote location
     *
     * @param url                   remote address at which to store the file
     * @throws BitBunkerException
     *
     */
    public void getTo(URL url) throws BitBunkerException {
        checkConnected();
        this.getClient().getTo(this, url);
    }

    /**
     * delete the file from BitBunker
     *
     * @throws BitBunkerException
     *
     */
    public void delete() throws BitBunkerException {
        checkConnected();
        this.getClient().delete(this);
    }

    /**
     * put a file into BitBunker
     *
     * @param localPath             location on the local filesystem of the file
     *                              to store in BitBunker
     * @throws BitBunkerException
     *
     */
    public void put(String localPath) throws BitBunkerException {
        checkConnected();
        this.getClient().put(localPath, this);
    }

    /**
     * put a file into BitBunker
     *
     * @param localFile             file on the local filesystem to store in
     *                              BitBunker.
     * @throws BitBunkerException
     *
     */
    public void put(java.io.File localFile) throws BitBunkerException {
        checkConnected();
        this.getClient().put(localFile, this);
    }

    /**
     * put a file into BitBunker
     *
     * @param is                    stream of data to store in BitBunker
     * @throws BitBunkerException
     *
     */
    public void put(InputStream is) throws BitBunkerException {
        checkConnected();
        this.getClient().put(is, this);
    }

    /**
     * put a file into BitBunker from a remote location
     *
     * @param address               URL of remote file to store in BitBunker
     * @throws BitBunkerException
     *
     */
    public void putFrom(String address) throws BitBunkerException {
        checkConnected();
        this.getClient().putFrom(address, this);
    }

    /**
     * put a file into BitBunker from a remote location
     *
     * @param url                   URL of remote file to store in BitBunker
     * @throws BitBunkerException
     *
     */
    public void putFrom(URL url) throws BitBunkerException {
        checkConnected();
        this.getClient().putFrom(url, this);
    }
}