text:
import sys
import os
import re
import inspect
import importlib
from pandas.compat import u, PY3

try:
    raw_input          # Python 2
except NameError:
    raw_input = input  # Python 3

# https://github.com/sphinx-doc/sphinx/pull/2325/files
# Workaround for sphinx-build recursion limit overflow:
# pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL)
#  RuntimeError: maximum recursion depth exceeded while pickling an object
#
# Python's default allowed recursion depth is 1000.
sys.setrecursionlimit(5000)

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.append(os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../sphinxext'))

sys.path.extend([

    # numpy standard doc extensions
    os.path.join(os.path.dirname(__file__),
                 '..', '../..',
                 'sphinxext')

])

# -- General configuration -----------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.  sphinxext.

extensions = ['sphinx.ext.autodoc',
              'sphinx.ext.autosummary',
              'sphinx.ext.doctest',
              'sphinx.ext.extlinks',
              'sphinx.ext.todo',
              'numpydoc',
              'ipython_sphinxext.ipython_directive',
              'ipython_sphinxext.ipython_console_highlighting',
              'IPython.sphinxext.ipython_console_highlighting',  # lowercase didn't work
              'sphinx.ext.intersphinx',
              'sphinx.ext.coverage',
              'sphinx.ext.mathjax',
              'sphinx.ext.ifconfig',
              'sphinx.ext.linkcode',
              'nbsphinx',
              ]

exclude_patterns = ['**.ipynb_checkpoints']

with open("index.rst") as f:
    index_rst_lines = f.readlines()

# only include the slow autosummary feature if we're building the API section
# of the docs

# JP: added from sphinxdocs
autosummary_generate = False

if any(re.match("\s*api\s*", l) for l in index_rst_lines):
    autosummary_generate = True

files_to_delete = []
for f in os.listdir(os.path.dirname(__file__)):
    if (not f.endswith(('.ipynb', '.rst')) or
            f.startswith('.') or os.path.basename(f) == 'index.rst'):
        continue

    _file_basename = os.path.splitext(f)[0]
    _regex_to_match = "\s*{}\s*$".format(_file_basename)
    if not any(re.match(_regex_to_match, line) for line in index_rst_lines):
        files_to_delete.append(f)

if files_to_delete:
    print("I'm about to DELETE the following:\n%s\n" % list(sorted(files_to_delete)))
    sys.stdout.write("WARNING: I'd like to delete those to speed up processing (yes/no)? ")
    if PY3:
        answer = input()
    else:
        answer = raw_input()

    if answer.lower().strip() in ('y','yes'):
        for f in files_to_delete:
            f = os.path.join(os.path.join(os.path.dirname(__file__),f))
            f= os.path.abspath(f)
            try:
                print("Deleting %s" % f)
                os.unlink(f)
            except:
                print("Error deleting %s" % f)
                pass

# Add any paths that contain templates here, relative to this directory.
templates_path = ['../_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
source_encoding = 'utf-8'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u('pandas')
copyright = u('2008-2014, the pandas development team')

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
import pandas

# version = '%s r%s' % (pandas.__version__, svn_version())
version = '%s' % (pandas.__version__)

# The full version, including alpha/beta/rc tags.
release = version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
# unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []

# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'nature_with_gtoc'

# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
# html_style = 'statsmodels.css'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['themes']

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.

# Add redirect for previously existing API pages
# each item is like `(from_old, to_new)`
# To redirect a class and all its methods, see below
# https://github.com/pandas-dev/pandas/issues/16186

moved_api_pages = [
    ('pandas.core.common.isnull', 'pandas.isna'),
    ('pandas.core.common.notnull', 'pandas.notna'),
    ('pandas.core.reshape.get_dummies', 'pandas.get_dummies'),
    ('pandas.tools.merge.concat', 'pandas.concat'),
    ('pandas.tools.merge.merge', 'pandas.merge'),
    ('pandas.tools.pivot.pivot_table', 'pandas.pivot_table'),
    ('pandas.tseries.tools.to_datetime', 'pandas.to_datetime'),
    ('pandas.io.clipboard.read_clipboard', 'pandas.read_clipboard'),
    ('pandas.io.excel.ExcelFile.parse', 'pandas.ExcelFile.parse'),
    ('pandas.io.excel.read_excel', 'pandas.read_excel'),
    ('pandas.io.gbq.read_gbq', 'pandas.read_gbq'),
    ('pandas.io.html.read_html', 'pandas.read_html'),
    ('pandas.io.json.read_json', 'pandas.read_json'),
    ('pandas.io.parsers.read_csv', 'pandas.read_csv'),
    ('pandas.io.parsers.read_fwf', 'pandas.read_fwf'),
    ('pandas.io.parsers.read_table', 'pandas.read_table'),
    ('pandas.io.pickle.read_pickle', 'pandas.read_pickle'),
    ('pandas.io.pytables.HDFStore.append', 'pandas.HDFStore.append'),
    ('pandas.io.pytables.HDFStore.get', 'pandas.HDFStore.get'),
    ('pandas.io.pytables.HDFStore.put', 'pandas.HDFStore.put'),
    ('pandas.io.pytables.HDFStore.select', 'pandas.HDFStore.select'),
    ('pandas.io.pytables.read_hdf', 'pandas.read_hdf'),
    ('pandas.io.sql.read_sql', 'pandas.read_sql'),
    ('pandas.io.sql.read_frame', 'pandas.read_frame'),
    ('pandas.io.sql.write_frame', 'pandas.write_frame'),
    ('pandas.io.stata.read_stata', 'pandas.read_stata'),
]

# Again, tuples of (from_old, to_new)
moved_classes = [
    ('pandas.tseries.resample.Resampler', 'pandas.core.resample.Resampler'),
    ('pandas.formats.style.Styler', 'pandas.io.formats.style.Styler'),
]

for old, new in moved_classes:
    # the class itself...
    moved_api_pages.append((old, new))

    mod, classname = new.rsplit('.', 1)
    klass = getattr(importlib.import_module(mod), classname)
    methods = [x for x in dir(klass)
               if not x.startswith('_') or x in ('__iter__', '__array__')]

    for method in methods:
        # ... and each of its public methods
        moved_api_pages.append(
            ("{old}.{method}".format(old=old, method=method),
             "{new}.{method}".format(new=new, method=method))
        )

html_additional_pages = {
    'generated/' + page[0]: 'api_redirect.html'
    for page in moved_api_pages
}

html_context = {
    'redirects': {old: new for old, new in moved_api_pages}
}

# If false, no module index is generated.
html_use_modindex = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = ''

# Output file base name for HTML help builder.
htmlhelp_basename = 'pandas'

# -- Options for nbsphinx ------------------------------------------------

nbsphinx_allow_errors = True

# -- Options for LaTeX output --------------------------------------------

# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'

# The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '10pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'pandas.tex',
     u('pandas: powerful Python data analysis toolkit'),
     u('Wes McKinney\n\& PyData Development Team'), 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# Additional stuff for the LaTeX preamble.
# latex_preamble = ''

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_use_modindex = True

intersphinx_mapping = {
    'statsmodels': ('http://www.statsmodels.org/devel/', None),
    'matplotlib': ('http://matplotlib.org/', None),
    'python': ('https://docs.python.org/3/', None),
    'numpy': ('https://docs.scipy.org/doc/numpy/', None),
    'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None),
    'py': ('https://pylib.readthedocs.io/en/latest/', None)
}
import glob
autosummary_generate = glob.glob("*.rst")

# extlinks alias
extlinks = {'issue': ('https://github.com/pandas-dev/pandas/issues/%s',
                      'GH'),
            'wiki': ('https://github.com/pandas-dev/pandas/wiki/%s',
                     'wiki ')}

ipython_exec_lines = [
    'import numpy as np',
    'import pandas as pd',
    # This ensures correct rendering on system with console encoding != utf8
    # (windows). It forces pandas to encode its output reprs using utf8
    # wherever the docs are built. The docs' target is the browser, not
    # the console, so this is fine.
    'pd.options.display.encoding="utf8"'
    ]

# Add custom Documenter to handle attributes/methods of an AccessorProperty
# eg pandas.Series.str and pandas.Series.dt (see GH9322)

import sphinx
from sphinx.util import rpartition
from sphinx.ext.autodoc import Documenter, MethodDocumenter, AttributeDocumenter
from sphinx.ext.autosummary import Autosummary

class AccessorDocumenter(MethodDocumenter):
    """
    Specialized Documenter subclass for accessors.
    """

    objtype = 'accessor'
    directivetype = 'method'

    # lower than MethodDocumenter so this is not chosen for normal methods
    priority = 0.6

    def format_signature(self):
        # this method gives an error/warning for the accessors, therefore
        # overriding it (accessor has no arguments)
        return ''

class AccessorLevelDocumenter(Documenter):
    """
    Specialized Documenter subclass for objects on accessor level (methods,
    attributes).
    """

    # This is the simple straightforward version
    # modname is None, base the last elements (eg 'hour')
    # and path the part before (eg 'Series.dt')
    # def resolve_name(self, modname, parents, path, base):
    #     modname = 'pandas'
    #     mod_cls = path.rstrip('.')
    #     mod_cls = mod_cls.split('.')
    #
    #     return modname, mod_cls + [base]

    def resolve_name(self, modname, parents, path, base):
        if modname is None:
            if path:
                mod_cls = path.rstrip('.')
            else:
                mod_cls = None
                # if documenting a class-level object without path,
                # there must be a current class, either from a parent
                # auto directive ...
                mod_cls = self.env.temp_data.get('autodoc:class')
                # ... or from a class directive
                if mod_cls is None:
                    mod_cls = self.env.temp_data.get('py:class')
                # ... if still None, there's no way to know
                if mod_cls is None:
                    return None, []
            # HACK: this is added in comparison to ClassLevelDocumenter
            # mod_cls still exists of class.accessor, so an extra
            # rpartition is needed
            modname, accessor = rpartition(mod_cls, '.')
            modname, cls = rpartition(modname, '.')
            parents = [cls, accessor]
            # if the module name is still missing, get it like above
            if not modname:
                modname = self.env.temp_data.get('autodoc:module')
            if not modname:
                if sphinx.__version__ > '1.3':
                    modname = self.env.ref_context.get('py:module')
                else:
                    modname = self.env.temp_data.get('py:module')
            # ... else, it stays None, which means invalid
        return modname, parents + [base]

class AccessorAttributeDocumenter(AccessorLevelDocumenter, AttributeDocumenter):

    objtype = 'accessorattribute'
    directivetype = 'attribute'

    # lower than AttributeDocumenter so this is not chosen for normal attributes
    priority = 0.6

class AccessorMethodDocumenter(AccessorLevelDocumenter, MethodDocumenter):

    objtype = 'accessormethod'
    directivetype = 'method'

    # lower than MethodDocumenter so this is not chosen for normal methods
    priority = 0.6

class AccessorCallableDocumenter(AccessorLevelDocumenter, MethodDocumenter):
    """
    This documenter lets us removes .__call__ from the method signature for
    callable accessors like Series.plot
    """
    objtype = 'accessorcallable'
    directivetype = 'method'

    # lower than MethodDocumenter; otherwise the doc build prints warnings
    priority = 0.5

    def format_name(self):
        return MethodDocumenter.format_name(self).rstrip('.__call__')

class PandasAutosummary(Autosummary):
    """
    This alternative autosummary class lets us override the table summary for
    Series.plot and DataFrame.plot in the API docs.
    """

    def _replace_pandas_items(self, display_name, sig, summary, real_name):
        # this a hack: ideally we should extract the signature from the
        # .__call__ method instead of hard coding this
        if display_name == 'DataFrame.plot':
            sig = '([x, y, kind, ax, ....])'
            summary = 'DataFrame plotting accessor and method'
        elif display_name == 'Series.plot':
            sig = '([kind, ax, figsize, ....])'
            summary = 'Series plotting accessor and method'
        return (display_name, sig, summary, real_name)

    def get_items(self, names):
        items = Autosummary.get_items(self, names)
        items = [self._replace_pandas_items(*item) for item in items]
        return items

# based on numpy doc/source/conf.py
def linkcode_resolve(domain, info):
    """
    Determine the URL corresponding to Python object
    """
    if domain != 'py':
        return None

    modname = info['module']
    fullname = info['fullname']

    submod = sys.modules.get(modname)
    if submod is None:
        return None

    obj = submod
    for part in fullname.split('.'):
        try:
            obj = getattr(obj, part)
        except:
            return None

    try:
        fn = inspect.getsourcefile(obj)
    except:
        fn = None
    if not fn:
        return None

    try:
        source, lineno = inspect.getsourcelines(obj)
    except:
        lineno = None

    if lineno:
        linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1)
    else:
        linespec = ""

    fn = os.path.relpath(fn, start=os.path.dirname(pandas.__file__))

    if '+' in pandas.__version__:
        return "http://github.com/pandas-dev/pandas/blob/master/pandas/%s%s" % (
            fn, linespec)
    else:
        return "http://github.com/pandas-dev/pandas/blob/v%s/pandas/%s%s" % (
            pandas.__version__, fn, linespec)

# remove the docstring of the flags attribute (inherited from numpy ndarray)
# because these give doc build errors (see GH issue 5331)
def remove_flags_docstring(app, what, name, obj, options, lines):
    if what == "attribute" and name.endswith(".flags"):
        del lines[:]

suppress_warnings = [
    # We "overwrite" autosummary with our PandasAutosummary, but
    # still want the regular autosummary setup to run. So we just
    # suppress this warning.
    'app.add_directive'
]

def setup(app):
    app.connect("autodoc-process-docstring", remove_flags_docstring)
    app.add_autodocumenter(AccessorDocumenter)
    app.add_autodocumenter(AccessorAttributeDocumenter)
    app.add_autodocumenter(AccessorMethodDocumenter)
    app.add_autodocumenter(AccessorCallableDocumenter)
    app.add_directive('autosummary', PandasAutosummary)


text:
require_relative 'model'
require 'pry'

class Deck
  attr_reader :flashcards_from_file, :flashcards, :definition
  attr_accessor :term

  def initialize(flashcards_from_file)
    @flashcards = []
    flashcards_from_file.each_with_index do |element, index|
      if index % 2 == 0
        self.flashcards << Card.new({definition: element})
      else
        self.flashcards.last.term = element
      end
    end
    @flashcards
  end

  def move_card_to_back
    flashcards.push(flashcards.shift)
  end

  def generate_random_card
    flashcards.shuffle
  end #?
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>HgPOS: Membres de classe</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

HgPOS

Mercurepointofsale

Liste de tous les membres de classe documentés avec des liens vers la documentation de classe de chaque membre :

clear()
: Panier

DatabaseManager()
: DatabaseManager

getProduitList()
: DatabaseManager

prod
: Panier

unit
: Panier

~DatabaseManager()
: DatabaseManager

<address class="footer">
Généré par

 1.8.13
</address>


text:
package org.apache.bigtop.bazaar.datagenerator;

import java.util.Random;

import org.apache.bigtop.bazaar.datagenerator.base.Matrix;
import org.apache.bigtop.bazaar.datagenerator.configuration.RecommendationsParameters;
import org.apache.bigtop.bazaar.datagenerator.latentvariablemodel.BoundedBiGaussianMixtureSampler;
import org.apache.bigtop.bazaar.datagenerator.latentvariablemodel.RandomSpaceGenerator;
import org.apache.bigtop.bazaar.datagenerator.latentvariablemodel.Sampler;

public class CustomerWeightsGenerator
{
	RandomSpaceGenerator generator;
	RecommendationsParameters params;

	public CustomerWeightsGenerator(RecommendationsParameters params, Random rng)
	{
		this.params = params;
		Sampler<Double> sampler = new BoundedBiGaussianMixtureSampler(0.0, 1.0, 0.25, 0.75, 0.1, 0.9, 0.2, rng);
		generator = new RandomSpaceGenerator(sampler);
	}

	public Matrix generate(int customers)
	{
		return generator.generate(customers, params.getNumberLatentFactors()).transpose();
	}
}


text:
package net.hasor.website.manager;
import net.hasor.core.Hasor;
import net.hasor.core.Inject;
import net.hasor.core.Singleton;
import net.hasor.website.core.TransactionService;
import net.hasor.website.datadao.ProjectInfoDAO;
import net.hasor.website.datadao.ProjectVersionDAO;
import net.hasor.website.domain.Owner;
import net.hasor.website.domain.ProjectInfoDO;
import net.hasor.website.domain.ProjectVersionDO;
import net.hasor.website.domain.enums.ErrorCodes;
import net.hasor.website.domain.enums.OwnerType;
import net.hasor.website.domain.enums.ProjectStatus;
import net.hasor.website.domain.enums.VersionStatus;
import net.hasor.website.domain.futures.ProjectFutures;
import net.hasor.website.domain.futures.ProjectVersionFutures;
import net.hasor.website.domain.result.Result;
import net.hasor.website.utils.LoggerUtils;
import net.hasor.website.utils.ProjectUtils;
import net.hasor.website.utils.VersionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static net.hasor.website.utils.ResultUtils.failed;
import static net.hasor.website.utils.ResultUtils.success;
/**
 *
 * @version : 2016年1月10日
 * @author 赵永春 (zyc@hasor.net)
 */
@Singleton
public class ProjectManager {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Inject
    private UserManager        userManager;
    @Inject
    private EnvironmentConfig  environmentConfig;
    @Inject
    private ProjectInfoDAO     projectInfoDAO;
    @Inject
    private ProjectVersionDAO  projectVersionDAO;
    @Inject
    private TransactionService transactionService;
    //
    //
    /** 新项目 */
    public Result<Long> newProject(Owner owner, ProjectInfoDO newProject) {
        // .入参判断
        if (owner == null || newProject == null || owner.getOwnerID() < 0 || owner.getOwnerType() == null) {
            logger.error(LoggerUtils.create("ERROR_006_0006").toJson());
            return failed(ErrorCodes.P_OWNER_ERROR);
        }
        // .数据有效性判断
        if (StringUtils.isBlank(newProject.getName())) {
            logger.error(LoggerUtils.create("ERROR_006_0001")//
                    .addLog("ownerID", owner.getOwnerID()) //
                    .addLog("ownerType", owner.getOwnerType().name()) //
                    .addLog("error", "project.name is blank.") //
                    .toJson());
            return failed(ErrorCodes.V_FORM_PROJECT_INVALID);
        }
        // .owner是否真是存在
        Owner ownerFormDB = null;
        if (owner.getOwnerType() == OwnerType.Personal) {
            // -个人
            ownerFormDB = this.userManager.getUserByID(owner.getOwnerID());
        } else if (owner.getOwnerType() == OwnerType.Organization) {
            // -组织
            ownerFormDB = null;//this.userManager.getUserByID(owner.getOwnerID());
        } else {
            // -未知
            logger.error(LoggerUtils.create("ERROR_006_0002")//
                    .addLog("ownerID", owner.getOwnerID()) //
                    .addLog("ownerType", owner.getOwnerType().name()) //
                    .toJson());
            return failed(ErrorCodes.P_OWNER_TYPE_FAILED);
        }
        if (ownerFormDB == null) {
            logger.error(LoggerUtils.create("ERROR_006_0003")//
                    .addLog("ownerID", owner.getOwnerID()) //
                    .addLog("ownerType", owner.getOwnerType().name()) //
                    .toJson());
            return failed(ErrorCodes.P_OWNER_NOT_EXIST);
        }
        //
        // .将project存入owner下
        long projectID = 0L;
        try {
            newProject.setOwnerID(ownerFormDB.getOwnerID());
            newProject.setOwnerType(ownerFormDB.getOwnerType());
            newProject.setCreateTime(new Date());
            newProject.setModifyTime(new Date());
            newProject.setStatus(ProjectStatus.Private);
            projectID = this.projectInfoDAO.insertProject(newProject);
            if (projectID <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0005")//
                        .addLog("ownerID", owner.getOwnerID()) //
                        .addLog("ownerType", owner.getOwnerType().name()) //
                        .toJson());
                return failed(ErrorCodes.P_SAVE_PROJECT_FAILED);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("ownerID", owner.getOwnerID()) //
                    .addLog("ownerType", owner.getOwnerType().name()) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_SAVE_PROJECT_FAILED, e);
        }
        // .返回值
        newProject.setId(projectID);
        return success(projectID);
    }
    /** 查询我的项目列表 */
    public Result<List<ProjectInfoDO>> queryMyProjectList(Owner owner) {
        // .owner判断
        if (owner == null) {
            logger.error(LoggerUtils.create("ERROR_006_0006").toJson());
            return failed(ErrorCodes.P_OWNER_ERROR);
        }
        // .查询数据
        try {
            List<ProjectInfoDO> projectList = this.projectInfoDAO.queryByOwner(owner.getOwnerID(), owner.getOwnerType());
            projectList = (projectList == null) ? new ArrayList<ProjectInfoDO>(0) : projectList;
            return success(projectList);
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("queryType", "projectInfoDAO.queryByOwner") //
                    .addLog("ownerID", owner.getOwnerID()) //
                    .addLog("ownerType", owner.getOwnerType().name()) //
                    .addLog("error", "query error -> " + e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_QUERY_ERROR, e);
        }
    }
    /** 根据项目ID查询项目 */
    public Result<ProjectInfoDO> queryProjectByID(long projectID) {
        try {
            ProjectInfoDO projectInfo = this.projectInfoDAO.queryByID(projectID);
            if (projectInfo == null) {
                return failed(ErrorCodes.P_PROJECT_NOT_EXIST);
            } else {
                return success(projectInfo);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("queryType", "projectInfoDAO.queryByID") //
                    .addLog("projectID", projectID) //
                    .addLog("error", "query error -> " + e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_QUERY_ERROR, e);
        }
    }
    /** 查询首页项目,所有已发布的,按照名字排序。 */
    public Result<List<ProjectInfoDO>> queryTopProjectList() {
        // .查询数据
        try {
            List<ProjectInfoDO> projectList = projectInfoDAO.queryPublishList(0L, null);
            projectList = (projectList == null) ? new ArrayList<ProjectInfoDO>(0) : projectList;
            return success(projectList);
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("queryType", "projectInfoDAO.queryPublishList") //
                    .addLog("ownerID", "all") //
                    .addLog("ownerType", "all") //
                    .addLog("error", "query error -> " + e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_QUERY_ERROR, e);
        }
    }
    /** 更新项目信息(不包含:介绍正文、正文格式) */
    public Result<Boolean> updateProjectWithoutContent(ProjectInfoDO project) {
        // .验证
        boolean test1 = project.getId() <= 0;
        boolean test2 = project.getOwnerID() < 0 || project.getOwnerType() == null;
        boolean test3 = StringUtils.isBlank(project.getName());
        if (test1 || test2 || test3) {
            logger.error(LoggerUtils.create("ERROR_006_0009")//
                    .addLog("ownerID", project.getOwnerID()) //
                    .addLog("ownerType", project.getOwnerType()) //
                    .toJson());
            return failed(ErrorCodes.P_V_PROJECT_INFO_FAILED);
        }
        // .保存
        try {
            int res = this.projectInfoDAO.updateWithoutContent(project);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0007")//
                        .addLog("ownerID", project.getOwnerID()) //
                        .addLog("ownerType", project.getOwnerType()) //
                        .toJson());
                return failed(ErrorCodes.P_SAVE_PROJECT_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("ownerID", project.getOwnerID()) //
                    .addLog("ownerType", project.getOwnerType()) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_SAVE_PROJECT_FAILED, e);
        }
    }
    /** 更新项目信息(仅包含:介绍正文、正文格式) */
    public Result<Boolean> updateProjectContent(ProjectInfoDO project) {
        // .验证
        boolean test1 = project.getId() <= 0;
        boolean test2 = project.getOwnerID() < 0 || project.getOwnerType() == null;
        boolean test4 = project.getContentFormat() == null;
        if (test1 || test2 || test4) {
            logger.error(LoggerUtils.create("ERROR_006_0009")//
                    .addLog("ownerID", project.getOwnerID()) //
                    .addLog("ownerType", project.getOwnerType()) //
                    .toJson());
            return failed(ErrorCodes.P_V_PROJECT_INFO_FAILED);
        }
        // .保存
        try {
            int res = this.projectInfoDAO.updateContent(project);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0008")//
                        .addLog("ownerID", project.getOwnerID()) //
                        .addLog("ownerType", project.getOwnerType()) //
                        .toJson());
                return failed(ErrorCodes.P_SAVE_PROJECT_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("ownerID", project.getOwnerID()) //
                    .addLog("ownerType", project.getOwnerType()) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_SAVE_PROJECT_FAILED, e);
        }
    }
    //
    //
    /** 查询项目的版本列表 */
    public Result<List<ProjectVersionDO>> queryVersionListByProject(long projectID) {
        // .id判断
        if (projectID <= 0) {
            logger.error(LoggerUtils.create("ERROR_006_0010")//
                    .addLog("projectID", projectID) //
                    .toJson());
            return failed(ErrorCodes.P_PROJECT_NOT_EXIST);
        }
        // .查询数据
        try {
            List<ProjectVersionDO> versionList = this.projectVersionDAO.queryByProject(projectID);
            versionList = (versionList == null) ? new ArrayList<ProjectVersionDO>(0) : versionList;
            return success(versionList);
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("queryType", "projectVersionDAO.queryByProject") //
                    .addLog("projectID", projectID) //
                    .addLog("error", "query error -> " + e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_QUERY_ERROR, e);
        }
    }
    /** 根据ID查询版本信息 */
    public Result<ProjectVersionDO> queryVersionByID(long projectID, long versionID) {
        try {
            ProjectVersionDO versionDO = this.projectVersionDAO.queryByID(projectID, versionID);
            if (versionDO == null) {
                return failed(ErrorCodes.P_VERSION_NOT_EXIST);
            } else {
                return success(versionDO);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("queryType", "projectInfoDAO.queryByID") //
                    .addLog("projectID", projectID) //
                    .addLog("versionID", versionID) //
                    .addLog("error", "query error -> " + e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_QUERY_ERROR, e);
        }
    }
    /** 更新版本信息(更新项目版本信息,不会变更版本状态和隶属关系) */
    public Result<Boolean> updateVersionInfo(ProjectVersionDO version) {
        // .保存
        try {
            int res = this.projectVersionDAO.updateVersionInfo(version);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0007")//
                        .addLog("versionID", version.getId()) //
                        .addLog("projectID", version.getProjectID()) //
                        .toJson());
                return failed(ErrorCodes.P_VERSION_UPDATE_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("versionID", version.getId()) //
                    .addLog("projectID", version.getProjectID()) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_VERSION_UPDATE_FAILED, e);
        }
    }
    //
    //
    /** 新增版本 */
    public Result<Long> newVersion(Owner user, long projectID, ProjectVersionDO versionInfoDO) {
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(user, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        //
        // .状态判断
        ProjectInfoDO projectInfoDO = projectByID.getResult();
        if (!ProjectUtils.canVersion(projectInfoDO)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        //
        // .保存
        try {
            versionInfoDO.setProjectID(Hasor.assertIsNotNull(projectInfoDO).getId());
            long versionID = this.projectVersionDAO.insertVersion(versionInfoDO);
            if (versionID <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0014")//
                        .addLog("projectID", projectInfoDO.getId()) //
                        .toJson());
                return failed(ErrorCodes.P_VERSION_SAVE_FAILED);
            } else {
                versionInfoDO.setId(versionID);
                return success(versionID);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("projectID", projectInfoDO.getId()) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_VERSION_SAVE_FAILED, e);
        }
    }
    /** 标记删除版本 */
    public Result<Boolean> deleteVersion(Owner user, long projectID, long versionID) {
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(user, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        Result<ProjectVersionDO> versionByID = this.queryVersionByID(projectID, versionID);
        if (!versionByID.isSuccess()) {
            return failed(versionByID);
        }
        //
        // .状态判断
        ProjectInfoDO projectInfoDO = projectByID.getResult();
        ProjectVersionDO versionInfo = versionByID.getResult();
        if (!ProjectUtils.canVersion(projectInfoDO)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        if (!VersionUtils.canDelete(versionInfo)) {
            return failed(ErrorCodes.P_VERSION_STATUS_FAILED);
        }
        //
        // .删除
        try {
            if (versionInfo.getFutures() == null) {
                versionInfo.setFutures(new ProjectVersionFutures());
            }
            versionInfo.getFutures().setRecoveryStartTime(new Date());
            versionInfo.getFutures().setRecoveryEndTime(this.environmentConfig.getRecoveryTime(new Date()));
            versionInfo.getFutures().setRecoveryStatus(versionInfo.getStatus().name());
            versionInfo.setStatus(VersionStatus.Recovery);
            long res = this.projectVersionDAO.updateStatusAndFutures(projectID, versionInfo);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0014")//
                        .addLog("projectID", projectID) //
                        .addLog("versionID", versionID) //
                        .toJson());
                return failed(ErrorCodes.P_VERSION_UPDATE_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("projectID", projectID) //
                    .addLog("versionID", versionID) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_VERSION_UPDATE_FAILED, e);
        }
    }
    /** 恢复删除的版本 */
    public Result<Boolean> recoverVersion(Owner user, long projectID, long versionID) {
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(user, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        Result<ProjectVersionDO> versionByID = this.queryVersionByID(projectID, versionID);
        if (!versionByID.isSuccess()) {
            return failed(versionByID);
        }
        //
        // .状态判断
        ProjectInfoDO projectInfoDO = projectByID.getResult();
        ProjectVersionDO versionInfo = versionByID.getResult();
        if (!ProjectUtils.canVersion(projectInfoDO)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        if (!VersionUtils.canRecovery(versionInfo)) {
            return failed(ErrorCodes.P_VERSION_STATUS_FAILED);
        }
        //
        // .恢复删除
        try {
            String lastStatus = versionInfo.getFutures().getRecoveryStatus();
            versionInfo.setStatus(VersionStatus.DesignPlan.formName(lastStatus));
            long res = this.projectVersionDAO.updateStatusAndFutures(projectID, versionInfo);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0014")//
                        .addLog("projectID", projectID) //
                        .addLog("versionID", versionID) //
                        .toJson());
                return failed(ErrorCodes.P_VERSION_UPDATE_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("projectID", projectID) //
                    .addLog("versionID", versionID) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_VERSION_UPDATE_FAILED, e);
        }
    }
    /** 版本置为发布状态 */
    public Result<Boolean> publishVersion(Owner user, long projectID, long versionID) {
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(user, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        Result<ProjectVersionDO> versionByID = this.queryVersionByID(projectID, versionID);
        if (!versionByID.isSuccess()) {
            return failed(versionByID);
        }
        //
        // .状态判断
        ProjectInfoDO projectInfoDO = projectByID.getResult();
        ProjectVersionDO versionInfo = versionByID.getResult();
        if (!ProjectUtils.canVersion(projectInfoDO)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        if (!VersionUtils.canPublish(versionInfo)) {
            return failed(ErrorCodes.P_VERSION_STATUS_FAILED);
        }
        //
        // .发布
        try {
            versionInfo.setStatus(VersionStatus.Release);
            long res = this.projectVersionDAO.updateStatus(projectID, versionInfo);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0014")//
                        .addLog("projectID", projectID) //
                        .addLog("versionID", versionID) //
                        .toJson());
                return failed(ErrorCodes.P_VERSION_UPDATE_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("projectID", projectID) //
                    .addLog("versionID", versionID) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_VERSION_UPDATE_FAILED, e);
        }
    }
    //
    //
    /** 标记删除项目 */
    public Result<Boolean> doDeleteProject(Owner operUser, ProjectInfoDO project) {
        long projectID = project.getId();
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(operUser, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        //
        // .状态判断
        ProjectInfoDO projectInfo = projectByID.getResult();
        if (!ProjectUtils.canDelete(projectInfo)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        if (projectInfo.getFutures() == null) {
            projectInfo.setFutures(new ProjectFutures());
        }
        projectInfo.getFutures().setRecoveryStartTime(new Date());
        projectInfo.getFutures().setRecoveryEndTime(this.environmentConfig.getRecoveryTime(new Date()));
        projectInfo.getFutures().setRecoveryStatus(projectInfo.getStatus().name());
        projectInfo.setStatus(ProjectStatus.Recovery);
        //
        // .删除
        return updateStatusAndFutures(projectID, projectInfo);
    }
    /** 恢复删除的项目 */
    public Result<Boolean> doRecoverProject(Owner operUser, ProjectInfoDO project) {
        long projectID = project.getId();
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(operUser, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        // .状态判断
        ProjectInfoDO projectInfo = projectByID.getResult();
        if (!ProjectUtils.canRecovery(projectInfo)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        //
        String lastStatus = projectInfo.getFutures().getRecoveryStatus();
        projectInfo.setStatus(ProjectStatus.Private.formName(lastStatus));
        return updateStatusAndFutures(projectID, projectInfo);
    }
    /** 设置为私有项目 */
    public Result<Boolean> doPrivateProject(Owner operUser, ProjectInfoDO project) {
        //
        long projectID = project.getId();
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(operUser, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        // .状态判断
        ProjectInfoDO projectInfo = projectByID.getResult();
        if (!ProjectUtils.canPrivate(projectInfo)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        projectInfo.setStatus(ProjectStatus.Private);
        return updateStatusAndFutures(projectID, projectInfo);
    }
    /** 设置为公开项目 */
    public Result<Boolean> doPublicProject(Owner operUser, ProjectInfoDO project) {
        //
        long projectID = project.getId();
        Result<ProjectInfoDO> projectByID = this.queryProjectByID(projectID);
        Result<Void> testProject = this.testProjectOwner(operUser, projectByID);
        if (!testProject.isSuccess()) {
            return failed(testProject);
        }
        // .状态判断
        ProjectInfoDO projectInfo = projectByID.getResult();
        if (!ProjectUtils.canPublic(projectInfo)) {
            return failed(ErrorCodes.P_PROJECT_STATUS_FAILED);
        }
        //
        projectInfo.setStatus(ProjectStatus.Public);
        return updateStatusAndFutures(projectID, projectInfo);
    }
    //
    //
    private Result<Void> testProjectOwner(Owner owner, Result<ProjectInfoDO> projectResult) {
        if (!projectResult.isSuccess()) {
            return failed(projectResult);
        }
        if (owner == null) {
            return failed(ErrorCodes.P_OWNER_ERROR);
        }
        ProjectInfoDO projectInfo = projectResult.getResult();
        if (projectInfo == null) {
            return failed(ErrorCodes.P_PROJECT_NOT_EXIST);
        }
        if (projectInfo.getOwnerID() != owner.getOwnerID() || !projectInfo.getOwnerType().equals(owner.getOwnerType())) {
            return failed(ErrorCodes.P_OWNER_NOT_YOU);
        }
        return success(null);
    }
    private Result<Boolean> updateStatusAndFutures(long projectID, ProjectInfoDO projectInfo) {
        try {
            long res = this.projectInfoDAO.updateStatusAndFutures(projectID, projectInfo);
            if (res <= 0) {
                logger.error(LoggerUtils.create("ERROR_006_0014")//
                        .addLog("projectID", projectID) //
                        .toJson());
                return failed(ErrorCodes.P_PROJECT_UPDATE_FAILED);
            } else {
                return success(true);
            }
        } catch (Exception e) {
            logger.error(LoggerUtils.create("ERROR_999_0003")//
                    .addLog("projectID", projectID) //
                    .addLog("error", e.getMessage()) //
                    .toJson(), e);
            return failed(ErrorCodes.P_PROJECT_UPDATE_FAILED, e);
        }
    }
}


text:
using System;
using System.Threading.Tasks;
using Akka.Util;
using ConsoleClient.Application.Products.Add;
using Kuno;
using Kuno.Akka;
using Kuno.Akka.EndPoints;
using Kuno.Akka.Messaging;
using Kuno.Services;

#pragma warning disable 4014

namespace ConsoleClient
{
    //[EndPointHost("home/parent")]
    //public class AC : EndPointHost
    //{
    //    public override int Retries => 2;
    //}

    [EndPoint("go")]
    public class Parent : Function
    {
        public override async Task ReceiveAsync()
        {
            await Task.Delay(1000);

            Console.WriteLine("Hello");
        }
    }

    public class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            Console.Title = "Console Client";

            try
            {
                using (var stack = new KunoStack())
                {
                    stack.UseAkka();

                    for (int i = 0; i < 10; i++)
                    {
                        stack.Send("go");
                    }

                    stack.Shutdown().Wait();
                    Console.ReadKey();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Ginger: tests/GCluster/test_GCheckClusterAssign.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Ginger

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Classes Namespaces Files Functions Variables

Functions

test_GCheckClusterAssign.h File Reference

#include <seqan/basic.h>

#include <seqan/sequence.h>

#include <seqan/GCluster/GCheckClusterAssign.h>

Go to the source code of this file.

Functions

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_dummy)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_lengthExact1)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_lengthExact2)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_lengthTooLong)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_lengthTooShort)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_ScoreExact)

 	SEQAN_DEFINE_TEST (test_GCheckClusterAssign_ScoreTooLow)

Function Documentation

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_dummy
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_lengthExact1
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_lengthExact2
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_lengthTooLong
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_lengthTooShort
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_ScoreExact
          	)

          SEQAN_DEFINE_TEST
          (
          test_GCheckClusterAssign_ScoreTooLow
          	)

tests

GCluster

test_GCheckClusterAssign.h

Generated on Thu May 23 2013 12:46:12 for Ginger by

     1.8.1.2


text:
module Colorbox
  module On
    module Rails
      VERSION = "0.0.2"
    end
  end
end


text:
package io.druid.server.coordinator;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.MoreExecutors;
import io.druid.client.ImmutableDruidDataSource;
import io.druid.client.ImmutableDruidServer;
import io.druid.java.util.common.Intervals;
import io.druid.server.coordination.DruidServerMetadata;
import io.druid.server.coordination.ServerType;
import io.druid.timeline.DataSegment;
import org.easymock.EasyMock;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;

public class DiskNormalizedCostBalancerStrategyTest
{
  private static final Interval day = Intervals.of("2015-01-01T00/2015-01-01T01");

  /**
   * Create Druid cluster with serverCount servers having maxSegments segments each, and 1 server with 98 segment
   * Cost Balancer Strategy should assign the next segment to the server with less segments.
   */
  public static List<ServerHolder> setupDummyCluster(int serverCount, int maxSegments)
  {
    List<ServerHolder> serverHolderList = Lists.newArrayList();
    // Create 10 servers with current size being 3K & max size being 10K
    // Each having having 100 segments
    for (int i = 0; i < serverCount; i++) {
      LoadQueuePeonTester fromPeon = new LoadQueuePeonTester();
      Map<String, DataSegment> segments = Maps.newHashMap();
      for (int j = 0; j < maxSegments; j++) {
        DataSegment segment = getSegment(j);
        segments.put(segment.getIdentifier(), segment);
      }

      serverHolderList.add(
          new ServerHolder(
              new ImmutableDruidServer(
                  new DruidServerMetadata("DruidServer_Name_" + i, "localhost", null, 10000000L, ServerType.HISTORICAL, "hot", 1),
                  3000L,
                  ImmutableMap.of("DUMMY", EasyMock.createMock(ImmutableDruidDataSource.class)),
                  ImmutableMap.copyOf(segments)
              ),
              fromPeon
          ));
    }

    // The best server to be available for next segment assignment has greater max Size
    LoadQueuePeonTester fromPeon = new LoadQueuePeonTester();
    ImmutableDruidServer druidServer = EasyMock.createMock(ImmutableDruidServer.class);
    EasyMock.expect(druidServer.getName()).andReturn("BEST_SERVER").anyTimes();
    EasyMock.expect(druidServer.getCurrSize()).andReturn(3000L).anyTimes();
    EasyMock.expect(druidServer.getMaxSize()).andReturn(100000000L).anyTimes();

    EasyMock.expect(druidServer.getSegment(EasyMock.<String>anyObject())).andReturn(null).anyTimes();
    Map<String, DataSegment> segments = Maps.newHashMap();
    for (int j = 0; j < maxSegments; j++) {
      DataSegment segment = getSegment(j);
      segments.put(segment.getIdentifier(), segment);
      EasyMock.expect(druidServer.getSegment(segment.getIdentifier())).andReturn(segment).anyTimes();
    }
    EasyMock.expect(druidServer.getSegments()).andReturn(segments).anyTimes();

    EasyMock.replay(druidServer);
    serverHolderList.add(new ServerHolder(druidServer, fromPeon));
    return serverHolderList;
  }

  /**
   * Returns segment with dummy id and size 100
   *
   * @param index
   *
   * @return segment
   */
  public static DataSegment getSegment(int index)
  {
    return getSegment(index, "DUMMY", day);
  }

  public static DataSegment getSegment(int index, String dataSource, Interval interval)
  {
    // Not using EasyMock as it hampers the performance of multithreads.
    DataSegment segment = new DataSegment(
        dataSource, interval, String.valueOf(index), new ConcurrentHashMap<>(),
        Lists.<String>newArrayList(), Lists.<String>newArrayList(), null, 0, index * 100L
    );
    return segment;
  }

  @Test
  public void testNormalizedCostBalancerMultiThreadedStrategy() throws InterruptedException
  {
    List<ServerHolder> serverHolderList = setupDummyCluster(10, 20);
    DataSegment segment = getSegment(1000);

    BalancerStrategy strategy = new DiskNormalizedCostBalancerStrategy(
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(4))
    );
    ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList);
    Assert.assertNotNull("Should be able to find a place for new segment!!", holder);
    Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName());
  }

  @Test
  public void testNormalizedCostBalancerSingleThreadStrategy() throws InterruptedException
  {
    List<ServerHolder> serverHolderList = setupDummyCluster(10, 20);
    DataSegment segment = getSegment(1000);

    BalancerStrategy strategy = new DiskNormalizedCostBalancerStrategy(
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1))
    );
    ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList);
    Assert.assertNotNull("Should be able to find a place for new segment!!", holder);
    Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName());
  }
}


text:
package com.jpamodeler.embeddable;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.ElementCollection;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;

@Embeddable

public class Address implements Serializable {

    @ElementCollection
    private Collection<String> phone;

    @Embedded
    private Zipcode zipcode;

    @Basic
    private String street;

    @Basic
    private String state;

    @Basic
    private String country;

    @Basic
    private String city;

    public Address() {

    }

    public Collection<String> getPhone() {
        return this.phone;
    }

    public void setPhone(Collection<String> phone) {
        this.phone = phone;
    }

    public Zipcode getZipcode() {
        return this.zipcode;
    }

    public void setZipcode(Zipcode zipcode) {
        this.zipcode = zipcode;
    }

    public String getStreet() {
        return this.street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return this.country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}


text:
class AddTokensUpdatedOn < ActiveRecord::Migration
  def self.up
    add_column :tokens, :updated_on, :timestamp
    Token.update_all("updated_on = created_on")
  end

  def self.down
    remove_column :tokens, :updated_on
  end
end


text:
package jskills;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * Helper class for working with a single team.
 */
public class Team extends HashMap<IPlayer, Rating> implements ITeam {

    /**
     * Generated UID for serialization
     **/
    private static final long serialVersionUID = -5274158841312594600L;

    /**
     * Constructs a new team.
     */
    public Team() {
    }

    /**
     * Constructs a Team and populates it with the specified player.
     *
     * @param player The player to add.
     * @param rating The rating of the player.
     */
    public Team(IPlayer player, Rating rating) {
        addPlayer(player, rating);
    }

    /**
     * Adds the player to the team.
     *
     * @param player The player to add.
     * @param rating The rating of the player
     * @return The instance of the team (for chaining convenience).
     */
    public Team addPlayer(IPlayer player, Rating rating) {
        put(player, rating);
        return this;
    }

    /**
     * Concatenates multiple teams into a list of teams.
     *
     * @param teams The teams to concatenate together.
     * @return A sequence of teams.
     */
    public static Collection<ITeam> concat(ITeam... teams) {
        List<ITeam> teamsList = new ArrayList<>();
        teamsList.addAll(Arrays.asList(teams));
        return teamsList;
    }
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Druid;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;

@SuppressWarnings("rawtypes")
public class Chant_LightningWard extends Chant
{
	@Override public String ID() { return "Chant_LightningWard"; }
	private final static String localizedName = CMLib.lang().L("Lightning Ward");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Lightning Ward)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int abstractQuality(){return Ability.QUALITY_BENEFICIAL_SELF;}
	@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_PRESERVING;}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;
		if(canBeUninvoked())
			mob.tell(L("Your organic protection withers."));

		super.unInvoke();

	}

	@Override
	public void affectCharStats(MOB affectedMOB, CharStats affectedStats)
	{
		super.affectCharStats(affectedMOB,affectedStats);
		affectedStats.setStat(CharStats.STAT_SAVE_ELECTRIC,affectedStats.getStat(CharStats.STAT_SAVE_ELECTRIC)+100);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		MOB target=mob;
		if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
			target=(MOB)givenTarget;

		if(target.fetchEffect(this.ID())!=null)
		{
			mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already warding lightning."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("An organic field of protection appears around <T-NAME>."):L("^S<S-NAME> chant(s) for a shimmering organic field of protection around <T-NAMESELF>.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) for protection from lightning, but fail(s)."));

		return success;
	}
}


text:
# @api-group

Name of the group that this action should be grouped under when generating documentation.

## Syntax
```php
@api-group groupName
```

## Requirements
| Required? | Needs a visibility | Supports versioning | Supports deprecation |
| :--- | :--- | :--- | :--- |
| ✓ | × | × | × |

## Breakdown
| Tag | Optional | Description |
| :--- | :--- | :--- |
| groupName | × | Group name |

## Examples
On a resource action:

```php
/**
 * @api-label Update data on a group of users.
 * @api-operationid updateUsers
 * @api-group Users
 *
 * @api-path:public /users
 *
 * ...
 */
public function PATCH()
{
    ...
}
```


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: String.prototype.match (regexp)
es5id: 15.5.4.10_A1_T5
description: Call match (regexp) function with null argument of function object
---*/

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
//since ToString(null) evaluates to "null" match(null) evaluates to match("null")
if (function(){return "gnulluna"}().match(null)[0] !== "null") {
  $ERROR('#1: function(){return "gnulluna"}().match(null)[0] === "null". Actual: '+function(){return "gnulluna"}().match(null)[0] );
}
//
//////////////////////////////////////////////////////////////////////////////


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "category".
 *
 * @property integer $id
 * @property integer $parent_id
 * @property string $name
 * @property string $keywords
 * @property string $description
 */
class Category extends \yii\db\ActiveRecord
{

    public function behaviors()
    {
        return [
            'image' => [
                'class' => 'rico\yii2images\behaviors\ImageBehave',
            ]
        ];
    }

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

    public function getProduct()
    {
        return $this->hasMany(Product::className(), ['category_id' => 'id']);
    }

    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'parent_id']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['parent_id'], 'integer'],
            [['name'], 'required'],
            [['name', 'keywords', 'description'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '№ категории',
            'parent_id' => 'Родительская категория',
            'name' => 'Название',
            'keywords' => 'Ключевые слова',
            'description' => 'Мета-описание',
        ];
    }

    /**
     * @inheritdoc
     * @return CategoryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }
}


text:
package com.zkzong.mybatis.service.impl;

import com.zkzong.mybatis.domain.User;
import com.zkzong.mybatis.mapper.UserMapper;
import com.zkzong.mybatis.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by zong on 17-5-31.
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserMapper userMapper;

    @Override
    public int insertUser(String name, int age) {
        return userMapper.insertUser(name, age);
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>BRRelutionCampaignService Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				BlueRange SDK

				M-Way Solutions GmbH

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Instance Methods">

		<option value="//api/name/addActionListener:">- addActionListener:</option>

		<option value="//api/name/addDebugActionListener:">- addDebugActionListener:</option>

		<option value="//api/name/initWithScanner:andRelution:">- initWithScanner:andRelution:</option>

		<option value="//api/name/start">- start</option>

		<option value="//api/name/stop">- stop</option>

	</optgroup>

</select>

BRRelutionCampaignService Class Reference

	Inherits from
	NSObject

	Declared in
	BRRelutionCampaignService.h
BRRelutionCampaignService.m

Overview

A Relution campaign service can trigger actions defined in a Relution campaign. Internally
this class uses the {@link BRBeaconMessageActionTrigger} of the SDK’s core layer. The action
registry obtains all action informations from the Relution system. To start the trigger, just
call the {@link #start} method. The start method will periodically update a list of iBeacons
each 10 seconds. In future versions actions will also be triggered when Relution tags will be
received..

– initWithScanner:andRelution:

- (id)initWithScanner:(BRIBeaconMessageScanner *)scanner andRelution:(BRRelution *)relution

– start

- (void)start

– stop

- (void)stop

– addActionListener:

- (void)addActionListener:(NSObject<BRBeaconActionListener> *)listener

– addDebugActionListener:

- (void)addDebugActionListener:(NSObject<BRBeaconActionDebugListener> *)listener

Copyright © 2017 M-Way Solutions GmbH. All rights reserved. Updated: 2017-09-15

Generated by appledoc 2.2.1 (build 1334).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ResidentialManager
{
    /// <summary>
    /// Interaction logic for GeneralMeetingWindow.xaml
    /// </summary>
    public partial class GeneralMeetingWindow : Window
    {
        public GeneralMeetingWindow()
        {
            InitializeComponent();
        }

        internal GeneralMeetingWindow(GeneralMeeting eventToView)
            : this()
        {
            Conveners.ItemsSource = eventToView.Conveners;
            Attendees.ItemsSource = eventToView.Attendees;
            Agenda.ItemsSource = eventToView.Agenda;
            Votings.ItemsSource = eventToView.Votings;
        }

        public GeneralMeetingWindow(string title)
            : this()
        {
            this.Title = title;
        }

        private void ConvenersButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void AttendeesButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void AgendaButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void VotingsButton_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}


text:
FOUNDATION_EXPORT double Pods_CarDashVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CarDashVersionString[];


text:
@implementation BottomShadowView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
		self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
	self = [super initWithCoder:aDecoder];
	if (self) {
		self.backgroundColor = [UIColor clearColor];
	}
	return self;
}

- (void)drawRect:(CGRect)rect {
	CGContextRef context = UIGraphicsGetCurrentContext();

	CGContextSaveGState(context);

	CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 4, [UIColor blackColor].CGColor);

	CGContextFillRect(context, CGRectMake(-1, -10, rect.size.width+2, 10));

	CGContextRestoreGState(context);
}

@end


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

namespace Benchmark
{
	internal static class Factories
	{
		public static DateTime Now = DateTime.Now;
		public static DateTime Today = DateTime.Today;

		private static byte[] GuidBytes = new byte[8];

		public static Guid GetGuid(int i)
		{
			return new Guid(i, (short)i, (byte)i, GuidBytes);
		}

		public static void NewSimple(dynamic post, int i)
		{
			post.id = GetGuid(i);
			post.title = "title " + i;
			post.created = Today.AddDays(i);
		}
		public static void UpdateSimple(dynamic post, int i)
		{
			post.title = post.title + "!";
		}

		public static void NewStandard<TItem>(dynamic inv, int i) where TItem : new()
		{
			inv.number = i.ToString();
			inv.total = 100 + i;
			inv.dueDate = Today.AddDays(i / 2);
			inv.paid = i % 3 == 0 ? (DateTime?)Today.AddDays(i) : null;
			inv.reference = i % 7 == 0 ? i.ToString() : null;
			inv.tax = 15 + i % 10;
			inv.version = i;
			inv.canceled = i % 5 == 0;
			for (int j = 0; j < i % 10; j++)
			{
				dynamic item = new TItem();
				item.product = "prod " + i + " - " + j;
				item.cost = (i + j * j) / 100m;
				item.discount = i % 3 == 0 ? i % 10 + 5 : 0;
				item.quantity = i / 100 + j / 2 + 1;
				item.taxGroup = 5 + i % 20;
				inv.items.Add(item);
			}
		}
		public static void UpdateStandard(dynamic invoice, int i)
		{
			invoice.paid = Now.AddMilliseconds(i);
			var len = invoice.items.Count / 3;
			foreach (var it in invoice.items)
			{
				len--;
				if (len < 0)
					return;
				it.product += " !";
			}
		}

		private static void FillDict(int i, Dictionary<string, string> dict)
		{
			for (int j = 0; j < i / 3 % 10; j++)
				dict["key" + j] = "value " + i;
		}

		public static void NewComplex<TAccount, TTransaciton>(dynamic scrape, int i)
			where TAccount : new()
			where TTransaciton : new()
		{
			scrape.id = i;
			bool failed;
			try
			{
				scrape.website = new Uri("https://dsl-platform.com/benchmark/" + i);
				scrape.tags = new HashSet<string>(Enumerable.Range(i % 20, i % 6).Select(it => "tag" + it));
				scrape.info = new Dictionary<string, string>();
				FillDict(i, scrape.info);
				failed = false;
			}
			catch
			{
				failed = true;
				scrape.website = "https://dsl-platform.com/benchmark/" + i;
			}
			scrape.externalId = i % 3 != 0 ? i.ToString() : null;
			scrape.ranking = i;
			scrape.createdAt = Now.AddMinutes(i);
			for (int j = 0; j < i % 10; j++)
			{
				dynamic acc = new TAccount();
				acc.balance = 55m + i / (j + 1) - j * j;
				acc.name = "acc " + i + " - " + j;
				acc.number = i + "-" + j;
				acc.notes = "some notes " + (i.ToString()).PadLeft(j * 10, 'x');
				scrape.accounts.Add(acc);
				for (int k = 0; k < (i + j) % 300; k++)
				{
					dynamic tran = new TTransaciton();
					tran.amount = i / (j + k + 100);
					if (!failed)
						tran.currency = (Complex.Currency)(k % 3);
					tran.date = Today.AddDays(i + j + k);
					tran.description = "transaction " + i + " at " + k;
					acc.transactions.Add(tran);
				}
			}
		}
		public static void UpdateComplex(dynamic scrape, int i)
		{
			scrape.at = Now.AddMilliseconds(i);
			var lenAcc = scrape.accounts.Count / 3;
			foreach (var acc in scrape.accounts)
			{
				lenAcc--;
				if (lenAcc < 0)
					return;
				acc.balance += 10;
				var lenTran = acc.transactions.Count / 5;
				foreach (var tran in acc.transactions)
				{
					lenTran--;
					if (lenTran < 0)
						break;
					tran.amount += 5;
				}
			}
		}
	}
}


text:
@implementation GetOrderDetailOperator
- (id)initWithParamsDic:(NSDictionary *)params{
    if(self = [super initWithParamsDic:params]){
        self.action = @"home/Api/manageopenapi";
        self.order = [[Order alloc]init];
        self.order.productArr = [NSMutableArray array];
    }
    return self;
}
-(void)parseJson:(BaseModel *)baseModel{
    NSDictionary* dataDict = baseModel.data;

    NSDictionary* orderDict = [dataDict objectForKey:@"order"];
    _order.orderId = [orderDict objectForKey:@"orderid"];
    _order.total_fee = [NSString stringWithFormat:@"%.2f", [[orderDict objectForKey:@"pay_price"] doubleValue]/100];
    _order.payWay = [orderDict objectForKey:@"pay_way"];
//    _order.description = [orderDict objectForKey:@"title"];
    _order.time = [orderDict objectForKey:@"time"];
    _order.status = [orderDict objectForKey:@"status"];

    NSArray* dataArr = [dataDict objectForKey:@"order_detail"];
    for (NSDictionary* productDict in dataArr) {
        Product* product = [[Product alloc]init];

        product.detailId = [productDict objectForKey:@"detailid"];
        product.title = [productDict objectForKey:@"title"];
        product.orderId = [productDict objectForKey:@"orderid"];
        product.gid = [productDict objectForKey:@"gid"];
        product.countStr = [productDict objectForKey:@"count"];
        product.price = [NSString stringWithFormat:@"%.2f", [[productDict objectForKey:@"price"] doubleValue]/100];
        product.src = [NSString stringWithFormat:@"http://www.taojiuhui.cn/upload/%@",[productDict objectForKey:@"src"]];
        product.msg = [productDict objectForKey:@"msg"];
        [_order.productArr addObject:product];
    }

    NSDictionary* addressDict = [dataDict objectForKey:@"user_address"];
    AddressModel* addressModel = [[AddressModel alloc]init];
    addressModel.aid = [addressDict objectForKey:@"aid"];
    addressModel.region = [addressDict objectForKey:@"region"];
    addressModel.city = [addressDict objectForKey:@"city"];
    addressModel.qu = [addressDict objectForKey:@"qu"];
    addressModel.fullAddress = [addressDict objectForKey:@"full_adress"];
    addressModel.name = [addressDict objectForKey:@"name"];
    addressModel.phone = [addressDict objectForKey:@"phone"];
    addressModel.isUse = [addressDict objectForKey:@"is_use"];
    addressModel.isDefault = [addressDict objectForKey:@"is_default"];
    _order.defaultAddress = addressModel;

}

@end


text:
@interface BusView : UIView

@property (nonatomic, strong) Bus* bus;
@property (nonatomic, strong) GMSPanoramaView *panoView_;

-(id) initWithFrame:(CGRect)frame andBus:(Bus*)bus;

@end


text:
# does the quickest output of brew --prefix possible for the basic cases:
# - `brew --prefix` (output HOMEBREW_PREFIX)
# - `brew --prefix <formula>` (output HOMEBREW_PREFIX/opt/<formula>)
# anything else? delegate to the slower cmd/--prefix.rb
# HOMEBREW_PREFIX and HOMEBREW_REPOSITORY are set by brew.sh
# shellcheck disable=SC2154
homebrew-prefix() {
  while [[ "$#" -gt 0 ]]
  do
    case "$1" in
      # check we actually have --prefix and not e.g. --prefixsomething
      --prefix)
        local prefix="1"
        shift
        ;;
      # reject all other flags
      -*) return 1 ;;
      *)
        [[ -n "${formula}" ]] && return 1
        local formula="$1"
        shift
        ;;
    esac
  done
  [[ -z "${prefix}" ]] && return 1
  [[ -z "${formula}" ]] && echo "${HOMEBREW_PREFIX}" && return 0

  local formula_path
  if [[ -f "${HOMEBREW_REPOSITORY}/Library/Taps/homebrew/homebrew-core/Formula/${formula}.rb" ]]
  then
    formula_path="${HOMEBREW_REPOSITORY}/Library/Taps/homebrew/homebrew-core/Formula/${formula}.rb"
  else
    formula_path="$(
      shopt -s nullglob
      echo "${HOMEBREW_REPOSITORY}/Library/Taps"/*/*/{Formula/,HomebrewFormula/,}"${formula}.rb"
    )"
  fi
  [[ -z "${formula_path}" ]] && return 1

  echo "${HOMEBREW_PREFIX}/opt/${formula}"
  return 0
}


text:
package com.studio.smartbutler.utils;

import android.graphics.Typeface;
import android.widget.TextView;

import com.studio.smartbutler.application.BaseApplication;

/**
 * project name: SmartButler
 * package name: com.studio.smartbutler.utils
 * file name: UtilTools
 * creator: WindFromFarEast
 * created time: 2017/7/11 10:57
 * description: 常用工具类
 */

public class UtilTools
{
    //设置字体
    public static void setTypeface(TextView textView)
    {
        Typeface typeface=Typeface.createFromAsset(BaseApplication.getContext().getAssets(),"fonts/FONT.TTF");
        textView.setTypeface(typeface);
    }
}


text:
package com.sequenceiq.cloudbreak.core.flow2.cluster.provision;

import com.sequenceiq.cloudbreak.core.flow2.FlowState;
import com.sequenceiq.cloudbreak.core.flow2.RestartAction;
import com.sequenceiq.cloudbreak.core.flow2.restart.FillInMemoryStateStoreRestartAction;

public enum ClusterCreationState implements FlowState {
    INIT_STATE,
    CLUSTER_CREATION_FAILED_STATE,
    BOOTSTRAPPING_MACHINES_STATE,
    COLLECTING_HOST_METADATA_STATE,
    STARTING_AMBARI_SERVICES_STATE,
    REGISTER_PROXY_STATE,
    STARTING_AMBARI_STATE,
    INSTALLING_CLUSTER_STATE,
    CLUSTER_CREATION_FINISHED_STATE,
    FINAL_STATE;

    private Class<? extends RestartAction> restartAction = FillInMemoryStateStoreRestartAction.class;

    @Override
    public Class<? extends RestartAction> restartAction() {
        return restartAction;
    }
}


text:
export const F_NAME_ASC  = 'First name ascending';
export const F_NAME_DESC = 'First name descending';
export const L_NAME_ASC  = 'Last name ascending';
export const L_NAME_DESC = 'Last name descending';
export const PHONE_ASC   = 'Phone ascending';
export const PHONE_DESC  = 'Phone descending';
export const CUSTOM      = 'Custom order';

// Contact properties
export const F_NAME      = 'firstName';
export const L_NAME      = 'lastName';
export const PHONE       = 'phone';
export const IS_FAVORITE = 'isFavorite';

// Actions
export const ADD_CONTACT           = 'Add a contact';
export const UPDATE_CONTACT        = 'Update a contact';
export const DELETE_CONTACT        = 'Delete a contact';
export const UPDATE_SORT_PROP      = 'Update sort property';
export const UPDATE_FILTER_VALUE   = 'Update filter value';
export const TOGGLE_FAVORITES_ONLY = 'Toggle favorites only';
export const HIDE_CONTACT_FORM     = 'Hide add contact form';
export const SHOW_CONTACT_FORM     = 'Show add contact form';
export const UPDATE_CUSTOM_SORT    = 'Update custom sort order';
export const SET_CURRENT_CONTACT   = 'Set current contact';
export const CLEAR_CURRENT_CONTACT = 'Clear current contact';


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

    <string name="app_name">tracnghiemdaihocvatly</string>
    <string name="action_settings">Settings</string>
    <string name="app_id">665164660218141</string>
    <string name="cancelled">Cancelled</string>
    <string name="permission_not_granted">Unable to perform selected action because permissions were not granted.</string>
    <string name="ok">OK</string>
    <string name="hello_user">Hello %1$s!</string>
    <string name="success">Success</string>
    <string name="successfully_posted_post">Successfully posted \'%1$s\'.\nPost ID: %2$s</string>
    <string name="error">Error</string>
    <string name="status_update">Updating status for %1$s at %2$s</string>
    <string name="photo_post">Photo Post</string>
    <string name="you_picked">You picked:</string>
    <string name="no_friends_selected"><No friends selected></string>
    <string name="no_place_selected"><No place selected></string>
    <string name="pick_seattle_place">Pick a Seattle Place</string>
    <string name="app_id">665164660218141</string>
    <string name="exception">Exception: %1$s</string>
    <string name="title_activity_home_main">HomeMainActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_my_expandable_list_adapter">MyExpandableListAdapter</string>
    <string name="title_activity_chuyende">ChuyendeActivity</string>
    <string name="title_activity_list_de_thi">List_de_thi</string>

</resources>


text:
#import "JSBaseProjection.h"

#import "Constants.h"
#import "proj_api.h"

@implementation JSBaseProjection

@synthesize tileSize = tileSize_;

- (id)initWithTileSize:(int)tileSize projectionString:(NSString *)params {
  self = [super init];

  if (self) {
    JSLog(@"initWithString:'%@'", params);
    tileSize_ = tileSize;
    destinationProjection_ = pj_init_plus([params UTF8String]);
    sourceProjection_ = pj_init_plus([@"+proj=latlong +ellps=WGS84" UTF8String]);
    sourceIsLatLon_ = pj_is_latlong(sourceProjection_);
    destIsLatLon_ = pj_is_latlong(destinationProjection_);

    if (destinationProjection_ == nil || sourceProjection_ == nil) {
      JSLog(@"Unhandled error creating projection. %d - %d", destinationProjection_ == nil, sourceProjection_ == nil);
      [self release];
      return nil;
    }
  }

  return self;
}

- (void)dealloc {
  if (destinationProjection_) {
    pj_free(destinationProjection_);
  }

  if (sourceProjection_) {
    pj_free(sourceProjection_);
  }

  [super dealloc];
}

- (CLLocationCoordinate2D)transform:(CLLocationCoordinate2D)point {
  if (sourceIsLatLon_) {
		point.latitude *= DEG_TO_RAD;
		point.longitude *= DEG_TO_RAD;
	}

  int retCode = pj_transform(sourceProjection_, destinationProjection_, 1, 0, &point.longitude, &point.latitude, NULL);
  if (retCode != 0) {
    JSLog(@"Crapas - retCode: %d");
  }

  if (destIsLatLon_) {
		point.latitude *= RAD_TO_DEG;
		point.longitude *= RAD_TO_DEG;
	}

  return point;
}

- (CLLocationCoordinate2D)inverseTransform:(CLLocationCoordinate2D)point {
  if (destIsLatLon_) {
		point.latitude *= DEG_TO_RAD;
		point.longitude *= DEG_TO_RAD;
	}

  int retCode = pj_transform(destinationProjection_, sourceProjection_, 1, 0, &point.longitude, &point.latitude, NULL);
  if (retCode != 0) {
    JSLog(@"Crapas - retCode: %d", retCode);
  }

  if (sourceIsLatLon_) {
		point.latitude *= RAD_TO_DEG;
		point.longitude *= RAD_TO_DEG;
	}

  return point;
}

@end


text:
import pytest
import requests_mock

from isign.client import ISignClient
from isign.connection import ISignConnection
from isign.environment import ISignEnvironment
from isign.error import ISignError
from isign.model import (
    file,
    files,
    MobileCertificateResponse,
    MobileLoginResponse,
    MobileLoginStatusResponse,
    MobileSignResponse,
    MobileSignStatusResponse,
    pdf,
)

def test_client_constructor() -> None:
    env = ISignEnvironment("foo", "foo.isign.io", "http")
    conn = ISignConnection("acctkn", "constructor_test", env)
    client = ISignClient(conn)
    assert client.connection == conn

def test_client_mobile_certificate() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_certificate", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.post("https://foo.isign.io/mobile/certificate.json?access_token=acctkn",
                request_headers={"User-Agent": "test_client_mobile_certificate"},
                json={"status": "ok", "signing_certificate": {}, "authentication_certificate": {}},
                status_code=200)
        response = client.mobile_certificate("+37060000007", "51001091072")
    assert isinstance(response, MobileCertificateResponse)
    assert response.raw == {"status": "ok", "signing_certificate": {}, "authentication_certificate": {}}
    assert response.status == "ok"

def test_client_mobile_certificate_raises_when_status_not_good() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_certificate_raises_when_status_not_good", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.post("https://foo.isign.io/mobile/certificate.json?access_token=acctkn",
                request_headers={"User-Agent": "test_client_mobile_certificate_raises_when_status_not_good"},
                json={"status": "error"},
                status_code=400)
        pytest.raises(ISignError, client.mobile_certificate, "+37060000007", "51001091072")

def test_client_mobile_login() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_login", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.post("https://foo.isign.io/mobile/login.json?access_token=acctkn",
                request_headers={"User-Agent": "test_client_mobile_login"},
                json={"status": "ok", "certificate": {}, "token": "0123456789", "control_code": "1337"},
                status_code=200)
        response = client.mobile_login("+37060000007", "51001091072", language="EN", message="Login!")
    assert isinstance(response, MobileLoginResponse)
    assert response.raw == {"status": "ok", "certificate": {}, "token": "0123456789", "control_code": "1337"}
    assert response.status == "ok"

def test_client_mobile_login_raises_when_status_not_good() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_login_raises_when_status_not_good", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.post("https://foo.isign.io/mobile/login.json?access_token=acctkn",
                request_headers={"User-Agent": "test_client_mobile_login_raises_when_status_not_good"},
                json={"status": "error"},
                status_code=400)
        pytest.raises(ISignError, client.mobile_login, "+37060000007", "51001091072")

def test_client_mobile_login_status() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_login_status", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.get("https://foo.isign.io/mobile/login/status/1234567890.json?access_token=acctkn",
               request_headers={"User-Agent": "test_client_mobile_login_status"},
               json={"status": "waiting"},
               status_code=200)
        response = client.mobile_login_status("1234567890")
    assert isinstance(response, MobileLoginStatusResponse)
    assert response.raw == {"status": "waiting"}
    assert response.status == "waiting"

def test_client_mobile_login_status_raises_when_status_not_good() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_login_status_raises_when_status_not_good", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.get("https://foo.isign.io/mobile/login/status/1234567890.json?access_token=acctkn",
               request_headers={"User-Agent": "test_client_mobile_login_status_raises_when_status_not_good"},
               json={"status": "error"},
               status_code=400)
        pytest.raises(ISignError, client.mobile_login_status, "1234567890")

def test_client_mobile_sign_raises_when_type_is_unrecognized() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_sign", env)
    client = ISignClient(conn)
    assert pytest.raises(ValueError, client.mobile_sign, "+37060000007", "51001091072", "EN", "Login!", type="dummy")

def test_client_mobile_sign_raises_when_pdf_not_set_and_type_is_pdf() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_sign", env)
    client = ISignClient(conn)
    assert pytest.raises(ValueError, client.mobile_sign, "+37060000007", "51001091072", "EN", "Login!", type="pdf")

def test_client_mobile_sign() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_sign", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.post("https://foo.isign.io/mobile/sign.json?access_token=acctkn",
                request_headers={"User-Agent": "test_client_mobile_sign"},
                json={"status": "ok", "token": "0123456789", "control_code": "1337"},
                status_code=200)
        p = pdf(contact="Foo Bar",
                location="Vilnius",
                files=files(file("foo.pdf", "foo-digest", "foo-content")))
        response = client.mobile_sign("+37060000007", "51001091072", "EN", "Login!", pdf=p)
    assert isinstance(response, MobileSignResponse)
    assert response.raw == {"status": "ok", "token": "0123456789", "control_code": "1337"}
    assert response.status == "ok"

def test_client_mobile_sign_status() -> None:
    env = ISignEnvironment("foo", "foo.isign.io")
    conn = ISignConnection("acctkn", "test_client_mobile_login_status", env)
    client = ISignClient(conn)
    with requests_mock.mock() as rm:
        rm.get("https://foo.isign.io/mobile/sign/status/1234567890.json?access_token=acctkn",
               request_headers={"User-Agent": "test_client_mobile_login_status"},
               json={"status": "waiting"},
               status_code=200)
        response = client.mobile_sign_status("1234567890")
    assert isinstance(response, MobileSignStatusResponse)
    assert response.raw == {"status": "waiting"}
    assert response.status == "waiting"