text:
package org.apache.druid.query.aggregation.tdigestsketch.sql;

import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlFunctionCategory;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.type.OperandTypes;
import org.apache.calcite.sql.type.ReturnTypes;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.tdigestsketch.TDigestSketchAggregatorFactory;
import org.apache.druid.query.aggregation.tdigestsketch.TDigestSketchUtils;
import org.apache.druid.segment.VirtualColumn;
import org.apache.druid.sql.calcite.aggregation.Aggregation;
import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
import org.apache.druid.sql.calcite.expression.DruidExpression;
import org.apache.druid.sql.calcite.expression.Expressions;
import org.apache.druid.sql.calcite.planner.PlannerContext;
import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
import org.apache.druid.sql.calcite.table.RowSignature;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

public class TDigestGenerateSketchSqlAggregator implements SqlAggregator
{
  private static final SqlAggFunction FUNCTION_INSTANCE = new TDigestGenerateSketchSqlAggregator.TDigestGenerateSketchSqlAggFunction();
  private static final String NAME = "TDIGEST_GENERATE_SKETCH";

  @Override
  public SqlAggFunction calciteFunction()
  {
    return FUNCTION_INSTANCE;
  }

  @Nullable
  @Override
  public Aggregation toDruidAggregation(
      final PlannerContext plannerContext,
      final RowSignature rowSignature,
      final VirtualColumnRegistry virtualColumnRegistry,
      final RexBuilder rexBuilder,
      final String name,
      final AggregateCall aggregateCall,
      final Project project,
      final List<Aggregation> existingAggregations,
      final boolean finalizeAggregations
  )
  {
    final RexNode inputOperand = Expressions.fromFieldAccess(
        rowSignature,
        project,
        aggregateCall.getArgList().get(0)
    );
    final DruidExpression input = Expressions.toDruidExpression(
        plannerContext,
        rowSignature,
        inputOperand
    );
    if (input == null) {
      return null;
    }

    final AggregatorFactory aggregatorFactory;
    final String aggName = StringUtils.format("%s:agg", name);

    Integer compression = TDigestSketchAggregatorFactory.DEFAULT_COMPRESSION;
    if (aggregateCall.getArgList().size() > 1) {
      RexNode compressionOperand = Expressions.fromFieldAccess(
          rowSignature,
          project,
          aggregateCall.getArgList().get(1)
      );
      if (!compressionOperand.isA(SqlKind.LITERAL)) {
        // compressionOperand must be a literal in order to plan.
        return null;
      }
      compression = ((Number) RexLiteral.value(compressionOperand)).intValue();
    }

    // Look for existing matching aggregatorFactory.
    for (final Aggregation existing : existingAggregations) {
      for (AggregatorFactory factory : existing.getAggregatorFactories()) {
        if (factory instanceof TDigestSketchAggregatorFactory) {
          final TDigestSketchAggregatorFactory theFactory = (TDigestSketchAggregatorFactory) factory;
          final boolean matches = TDigestSketchUtils.matchingAggregatorFactoryExists(
              input,
              compression,
              existing,
              (TDigestSketchAggregatorFactory) factory
          );

          if (matches) {
            // Found existing one. Use this.
            return Aggregation.create(
                theFactory
            );
          }
        }
      }
    }

    // No existing match found. Create a new one.
    final List<VirtualColumn> virtualColumns = new ArrayList<>();

    if (input.isDirectColumnAccess()) {
      aggregatorFactory = new TDigestSketchAggregatorFactory(
          aggName,
          input.getDirectColumn(),
          compression
      );
    } else {
      VirtualColumn virtualColumn = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(
          plannerContext,
          input,
          SqlTypeName.FLOAT
      );
      virtualColumns.add(virtualColumn);
      aggregatorFactory = new TDigestSketchAggregatorFactory(
          aggName,
          virtualColumn.getOutputName(),
          compression
      );
    }

    return Aggregation.create(
        virtualColumns,
        aggregatorFactory
    );
  }

  private static class TDigestGenerateSketchSqlAggFunction extends SqlAggFunction
  {
    private static final String SIGNATURE_WITH_COMPRESSION = "'" + NAME + "(column, compression)'\n";

    TDigestGenerateSketchSqlAggFunction()
    {
      super(
          NAME,
          null,
          SqlKind.OTHER_FUNCTION,
          ReturnTypes.explicit(SqlTypeName.OTHER),
          null,
          OperandTypes.or(
              OperandTypes.ANY,
              OperandTypes.and(
                  OperandTypes.sequence(SIGNATURE_WITH_COMPRESSION, OperandTypes.ANY, OperandTypes.LITERAL),
                  OperandTypes.family(SqlTypeFamily.ANY, SqlTypeFamily.NUMERIC)
              )
          ),
          SqlFunctionCategory.USER_DEFINED_FUNCTION,
          false,
          false
      );
    }
  }
}


text:
package org.apache.yoko.orb.OBPortableServer;

//
// IDL:orb.yoko.apache.org/OBPortableServer/POAManager:1.0
//
/**
 *
 * This interface is a proprietary extension to the standard POAManager.
 *
 * @see PortableServer::POAManager
 *
 **/

public interface POAManagerOperations extends org.omg.PortableServer.POAManagerOperations
{
    //
    // IDL:orb.yoko.apache.org/OBPortableServer/POAManager/get_acceptors:1.0
    //
    /**
     *
     * Retrieve the acceptors associated with this POAManager.
     *
     * @return The acceptors.
     *
     **/

    org.apache.yoko.orb.OCI.Acceptor[]
    get_acceptors()
        throws org.omg.PortableServer.POAManagerPackage.AdapterInactive;
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/iot-roborunner/model/CreateWorkerFleetResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::IoTRoboRunner::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

CreateWorkerFleetResult::CreateWorkerFleetResult()
{
}

CreateWorkerFleetResult::CreateWorkerFleetResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

CreateWorkerFleetResult& CreateWorkerFleetResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("arn"))
  {
    m_arn = jsonValue.GetString("arn");

  }

  if(jsonValue.ValueExists("id"))
  {
    m_id = jsonValue.GetString("id");

  }

  if(jsonValue.ValueExists("createdAt"))
  {
    m_createdAt = jsonValue.GetDouble("createdAt");

  }

  if(jsonValue.ValueExists("updatedAt"))
  {
    m_updatedAt = jsonValue.GetDouble("updatedAt");

  }

  return *this;
}


text:
from __future__ import print_function, unicode_literals
from builtins import bytes

from lxml import etree
import sys, os, bz2

if len(sys.argv) < 2:
    input_filename = 'siconos-srcml.xml.bz2'
    output_filename = 'siconos-srcml.mse.bz2'
else:
    input_filename = sys.argv[1]
    ext = os.path.splitext(input_filename)
    if ext[1] in ['.bz2', '.gzip']:
        output_filename = os.path.splitext(ext[0])[0]
        bz = bz2.BZ2File
        bzext = '.bz2'
    else:
        output_filename = ext[0]
        bz = open
        bzext = ''
    output_filename += '.mse' + bzext

package_name = 'Siconos'
if len(sys.argv) >= 4:
    if sys.argv[2] == '--package':
        package_name = sys.argv[3]
    else:
        print('Unknown option "{}"'.format(sys.argv[2]))
        sys.exit(1)

print('Loading',input_filename,'...')
tree = etree.parse(bz(input_filename))

ns = {'src': u'http://www.srcML.org/srcML/src',
      'cpp': u'http://www.srcML.org/srcML/cpp'}

id_counter=0

class mseRef(object):
    def __init__(self, ref):
        self.ref = ref
    def __str__(self):
        return "(ref: %d)"%self.ref.id

class mseId(object):
    def __init__(self, val_id):
        self.value = val_id
    def __str__(self):
        return "(id: %d)"%self.value

class mseString(object):
    def __init__(self, s):
        self.string = s
        if self.string is not None and "'" in self.string:
            raise ValueError('mseString contains "\'": "%s"'%self.string)
    def __str__(self):
        return "'%s'"%self.string

class mseBoolean(object):
    def __init__(self, b):
        self.value = b
    def __str__(self):
        return ['false','true'][self.value]

class mseInteger(object):
    def __init__(self, i):
        self.value = i
    def __str__(self):
        return str(self.value)

class Node(object):
    def __init__(self, mse_node_type):
        global id_counter
        self.id = id_counter
        self.mse_node_type = mse_node_type
        self.sourceAnchor = None
        id_counter += 1
    def add_sourceAnchor(self, unit, startline=None, endline=None):
        fa = FileAnchor(self, unit, startline, endline)
        self.sourceAnchor = fa
        nodes.append(fa)
    def add_sourceUnitXML(self, xml):
        unit = xml.xpath('./ancestor::src:unit[@filename][1]', namespaces=nspc)
        if unit is not None and len(unit)>0:
            try:
                u = units_by_path[unit[0].attrib['filename']]
                self.add_sourceAnchor(u,
                                      startline=None, # TODO, possible from SrcML?
                                      endline=None)
            except KeyError:
                print('Could not resolve sourceAnchor', unit[0].attrib['filename'],
                      'for', self.id)
    def to_mse(self):
        attribs = self.mse_attribs()
        if self.sourceAnchor is not None:
            attribs.append(('sourceAnchor', mseRef(self.sourceAnchor)))
        mse = '\t(%s '%self.mse_node_type
        mse += str(mseId(self.id))
        for name, val in attribs:
            mse += '\n\t\t(%s %s)'%(name, str(val))
        mse += ')'
        return mse

class Package(Node):
    def __init__(self, name):
        Node.__init__(self, 'FAMIX.Package')
        self.name = name
    def mse_attribs(self):
        return [('name', mseString(self.name))]

class CompilationUnit(Node):
    def __init__(self, filepath, lang):
        Node.__init__(self, 'FAMIX.CompilationUnit')
        self.filepath = filepath
        self.filename = os.path.split(filepath)[1]
        self.language = lang
        self.includes = []
    def add_include(self, header):
        i = Include(self, header)
        self.includes.append(i)
        nodes.append(i)
    def mse_attribs(self):
        return [('filepath', mseString(self.filepath)),
                ('name', mseString(self.filename)),
                ('language', mseString(self.language))]

class Header(Node):
    def __init__(self, filepath, lang):
        Node.__init__(self, 'FAMIX.Header')
        self.filepath = filepath
        self.filename = os.path.split(filepath)[1]
        self.language = lang
        self.includes = []
    def add_include(self, header):
        i = Include(self, header)
        self.includes.append(i)
        nodes.append(i)
    def mse_attribs(self):
        return [('filepath', mseString(self.filepath)),
                ('name', mseString(self.filename)),
                ('language', mseString(self.language))]

class Include(Node):
    def __init__(self, includingfile, includedfile):
        Node.__init__(self, 'FAMIX.Include')
        self.includingfile = includingfile
        self.includedfile = includedfile
    def mse_attribs(self):
        return [('source', mseRef(self.includingfile)),
                ('target', mseRef(self.includedfile))]

class FileAnchor(Node):
    def __init__(self, element, unit, startline=None, endline=None):
        Node.__init__(self, 'FAMIX.FileAnchor')
        self.element = element
        self.unit = unit
        self.startline = startline
        self.endline = endline
    def mse_attribs(self):
        result = [('element', mseRef(self.element)),
                  ('unit', mseRef(self.unit)),
                  ('fileName', mseString(self.unit.filename))]
        if self.startline is not None:
            result.append(('startLine', mseInteger(self.startline)))
        if self.endline is not None:
            result.append(('endLine', mseInteger(self.endline)))
        return result

class Class(Node):
    def __init__(self, package, name):
        Node.__init__(self, 'FAMIX.Class')
        self.package = package
        self.name = name
        self.methods = []
        self.variables = []
        self.sourceAnchor = None
        self.supers = []
        self.inheritances = {}
    def add_method(self, name, sig, returnType=None):
        met = Method(name, self, sig, returnType)
        self.methods.append(met)
        nodes.append(met)
    def add_variable(self, name, typename):
        attr = Attribute(name, typename, self)
        self.variables.append(attr)
        nodes.append(attr)
    def add_superclass(self, name):
        self.supers.append(name)
    def add_inheritance(self, superclass):
        inh = Inheritance(self, superclass)
        self.inheritances[superclass.name] = inh
        nodes.append(inh)
    def add_call(self, name, args):
        pass
    def mse_attribs(self):
        return [('name', mseString(self.name)),
                ('belongsToPackage', mseRef(self.package))]

class Inheritance(Node):
    def __init__(self, subclass, superclass):
        Node.__init__(self, 'FAMIX.Inheritance')
        self.subclass = subclass
        self.superclass = superclass
    def mse_attribs(self):
        return [('subclass', mseRef(self.subclass)),
                ('superclass', mseRef(self.superclass))]

class Method(Node):
    def __init__(self, name, classclass, signature, returnType=None):
        Node.__init__(self, 'FAMIX.Method')
        self.declaredType = None
        if returnType is not None:
            self.declaredType = UnresolvedType(returnType, self)
        self.name = name
        self.classclass = classclass
        self.signature = signature
    def mse_attribs(self):
        result = [('name', mseString(self.name)),
                  ('signature', mseString(self.signature)),
                  ('parentType', mseRef(self.classclass))]
        decl = self.declaredType
        if decl is not None and not type(decl)==UnresolvedType:
            result.append(('declaredType', mseRef(self.declaredType)))
        return result

class Attribute(Node):
    def __init__(self, name, declaredType, classclass):
        Node.__init__(self, 'FAMIX.Attribute')
        self.name = name
        self.declaredType = UnresolvedType(declaredType, self)
        self.classclass = classclass
    def mse_attribs(self):
        result = [('name', mseString(self.name)),
                  ('parentType', mseRef(self.classclass))]
        decl = self.declaredType
        if decl is not None and not type(decl)==UnresolvedType:
            result.append(('declaredType', mseRef(self.declaredType)))
        return result

class Function(Node):
    def __init__(self, name, signature, returnType=None):
        Node.__init__(self, 'FAMIX.Function')
        self.name = name
        self.signature = signature
        self.declaredType = None
        if returnType is not None:
            self.declaredType = UnresolvedType(returnType, self)
    def mse_attribs(self):
        result = [('name', mseString(self.name)),
                  ('signature', mseString(self.signature))]
        decl = self.declaredType
        if decl is not None and not type(decl)==UnresolvedType:
            result.append(('declaredType', mseRef(self.declaredType)))
        return result

class Invocation(Node):
    def __init__(self, signature, sender, receiver=None):
        Node.__init__(self, 'FAMIX.Invocation')
        self.signature = signature
        if "'" in self.signature:
            raise ValueError('Invocation signature contains "\'": "%s"'%self.signature)
        self.sender = sender
        self.receiver = receiver
    def mse_attribs(self):
        result = [('signature', mseString(self.signature)),
                  ('sender', mseRef(self.sender))]
        if self.receiver is not None:
            results.append(('receiver', mseRef(self.receiver)))
        return result

class UnresolvedType(Node):
    def __init__(self, name, attr):
        Node.__init__(self, None)
        self.name = name
        self.attr = attr
        unresolved.append(self)
    def resolve(self, classclass):
        self.attr.declaredType = classclass

def make_signature(name, args, ty=None, removeQuote=False):
    etree.strip_elements(args, '{*}comment')
    etree.strip_elements(args, '{*}init')
    signature = '%s%s'%(name.xpath('string()'),
                        args.xpath('string()'))
    if ty is not None:
        signature = '%s %s'%(ty.xpath('string()'),
                             signature)
    r = ['',"'"][removeQuote]
    if not removeQuote and "'" in signature:
        raise ValueError('Signature contains "\'": "%s"'%signature)
    return ' '.join(signature.replace(r,'').split())

# Reset collections
nodes = []
classes = {}
functions = {}
units_by_name = {}
units_by_path = {}
headers = {}
invocations = []
unresolved = []

# Find interesting parts of the SrcML XML
siconos = Package(package_name)
nodes.append(siconos)

for unit in tree.findall('//{*}unit'):
    path = unit.attrib['filename']
    lang = unit.attrib['language']
    ext = os.path.splitext(path)[1]
    if ext=='.i':
        lang = 'SWIG'
    if ext in ['.h', '.hpp', '.i']:
        u = Header(path, lang)
        headers[u.filename] = u
    else:
        u = CompilationUnit(path, lang)
    nodes.append(u)
    units_by_name[u.filename] = u
    units_by_path[u.filepath] = u
print('Found',len(units_by_name),'units')
print('Found',len(headers),'headers')

# Resolve #include relations
nspc = {'cpp': 'http://www.srcML.org/srcML/cpp',
        'src': 'http://www.srcML.org/srcML/src'}
n_includes = 0
n_unresolved_includes = 0
for unit in tree.findall('//{*}unit'):
    path = unit.attrib['filename']
    lang = unit.attrib['language']
    ext = os.path.splitext(path)[1]
    name = os.path.split(path)[1]
    if ext=='.i':
        lang = 'SWIG'
    if lang == 'SWIG':
        includes = unit.xpath(
            './/src:literal[following::src:name][following::src:operator]',
            namespaces=nspc)
        for i in includes:
            p = i.getprevious()
            if p is not None:
                p2 = p.getprevious()
                if (p2 is not None
                    and p.xpath('string()')=='include'
                    and p2.xpath('string()')=='%'):

                    fn = i.xpath('string()').split('"')
                    if len(fn)==3:
                        fn = fn[1]
                    elif len(fn)==1:
                        fn = fn[0]
                    u = None
                    try:
                        u = units_by_name[name]
                        h = units_by_name[fn]
                    except KeyError:
                        # make node for header marked as external?
                        h = None
                        n_unresolved_includes += 1
                    if u is not None and h is not None:
                        u.add_include(h)
                        n_includes += 1

    if lang in ('C','C++','SWIG'):
        includes = unit.xpath('.//cpp:include/cpp:file',namespaces=nspc)
        for i in includes:
            fn = i.xpath('string()')
            fn = fn.replace('>','').replace('<','').replace('"','')
            try:
                u = units_by_name[name]
                h = units_by_name[fn]
            except KeyError:
                # make node for header marked as external?
                u = None
                h = None
                n_unresolved_includes += 1
            if u is not None and h is not None:
                u.add_include(h)
                n_includes += 1
print('Resolved',n_includes,'includes')
print('Could not resolved',n_unresolved_includes,'includes (probably external libs)')

for cl in tree.findall('//{*}class'):
    p = cl.getparent()
    language = None
    while p is not None:
        if 'language' in p.attrib:
            language = p.attrib['language']
            break
        p = p.getparent()
    if language not in ('C', 'C++'):
        continue
    classname = cl.find('{*}name')
    if classname == None:
        continue
    node = Class(siconos, classname.text)
    supers = cl.findall('./{*}super/{*}name')
    decls = cl.findall('.//{*}decl/{*}name')
    methods = cl.findall('.//{*}function_decl')
    node.add_sourceUnitXML(cl)
    if supers:
        for s in supers:
            node.add_superclass(s.xpath('string()'))
    if methods:
        for m in methods:
            name = m.find('./{*}name')
            ty = m.find('./{*}type')
            args = m.find('./{*}parameter_list')
            signature = make_signature(name, args, ty)
            node.add_method(name.xpath('string()'),
                            signature,
                            ty.xpath('string()') if ty else None)
    if decls:
        for d in decls:
            typename = None
            if d.getprevious() is not None and 'type' in d.getprevious().tag:
                typeelem = d.getprevious().find('{*}name')
                if typeelem is not None:
                    names = typeelem.findall('{*}name')
                    if len(names)>1 and names[0].text == 'SP':
                        typename = names[-1].xpath('string()')
                    else:
                        typename = typeelem.xpath('string()')
            node.add_variable(d.xpath('string()'), typename)
    nodes.append(node)
    classes[classname.text] = node
print('Found',len(classes),'classes')

# Make inheritance nodes
for cl in classes.values():
    for s in cl.supers:
        if s in classes:
            cl.add_inheritance(classes[s])

# Find non-class functions
funcs = tree.findall('//{*}function')
if funcs:
    for func in funcs:
        cl = next((x for x in func.iterancestors()
                   if 'class' in x.tag), None)
        if cl is not None:
            continue
        name = func.find('./{*}name')
        if name is None:
            continue
        if name.xpath('string()')[0]=='$':  # skip some templates in LAPACK
            continue
        if (len(name.getchildren())==3
            and 'operator' in name.getchildren()[1].tag):
            if name.getchildren()[1].xpath('string()')=='::':
                continue
        args = func.find('./{*}parameter_list')
        if args is None:
            continue
        ty = func.find('./{*}type')
        if ty is not None:
            tyname = ty.xpath('string()')
        else:
            tyname = None
        signature = make_signature(name, args, ty, removeQuote=True)
        if signature not in functions:
            functions[signature] = Function(name.xpath('string()'),
                                            signature, tyname)
            nodes.append(functions[signature])
print('Found',len(functions),'non-class functions')

# Resolve unresolved types
count = 0
for t in unresolved:
    if t.name is not None:
        if t.name in classes:
            count += 1
            t.resolve(classes[t.name])
        # else:
        #     print 'Cannot resolve', repr(t.name)
print('Resolved',count,'types')

# Find function calls
calls = tree.findall('//{*}call')
if calls:
    for c in calls:
        name = c.find('./{*}name')
        args = c.find('./{*}argument_list')
        unit = next((x for x in c.iterancestors()
                     if 'unit' in x.tag), None)
        if unit is None or unit.attrib['filename'][-2:]=='.i':
            continue
        cl = next((x for x in c.iterancestors()
                   if 'class' in x.tag), None)
        func = next((x for x in c.iterancestors()
                     if 'function' in x.tag), None)
        sender = None
        if cl is not None:
            # In a class definition
            # Find the class and sender is the method
            clname = cl.find('./{*}name')
            const = next((x for x in c.iterancestors()
                          if 'constructor' in x.tag), None)
            funcdecl = next((x for x in c.iterancestors()
                             if 'function' in x.tag), None)
            if clname is not None and clname.xpath('string()') in classes:
                cl = classes[clname.xpath('string()')]
                if const is not None:
                    pass #TODO constructors
                elif funcdecl is not None:
                    if funcdecl.find('{*}name') is not None:
                        methname = funcdecl.find('{*}name').xpath('string()')
                        method = next((x for x in cl.methods
                                       if x.name == methname), None)
                        sender = method
        elif func is not None:

            p = func
            while p is not None:
                if 'language' in p.attrib:
                    language = p.attrib['language']
                    break
                p = p.getparent()
            if language not in ('C','C++'):
                continue

            # In a function implementation: If implementation of a
            # method, find the class and sender is the method.
            # Otherwise, sender is the function, if found.
            caller_name = func.find('./{*}name')
            caller_args = func.find('./{*}parameter_list')
            caller_type = func.find('./{*}type')

            # skip some templates in LAPACK
            if caller_name.xpath('string()')[0]=='$':
                continue

            caller_sig = make_signature(caller_name, caller_args,
                                        caller_type)
            if caller_sig in functions:
                sender = functions[caller_sig]
            else:
                if (len(caller_name.getchildren())==3 and
                    caller_name.getchildren()[1].xpath('string()')=='::'):
                    class_name = caller_name.getchildren()[0].xpath('string()')
                    method_name = caller_name.getchildren()[2].xpath('string()')
                    if class_name in classes:
                        cl = classes[class_name]
                        sender = next((x for x in cl.methods
                                       if x.name==method_name), None)
        if sender:
            inv = Invocation(signature=c.xpath('string()').replace("'",''),
                             sender=sender)
            invocations.append(inv)
            nodes.append(inv)
print('Found',len(invocations),'invocations')

# Print MSE to output file
output_file = bz(output_filename, 'wb')
output_file.write(bytes(u'(\n', 'UTF-8'))
for n in nodes:
    output_file.write(bytes(n.to_mse(), 'UTF-8'))
    output_file.write(bytes(u'\n', 'UTF-8'))
output_file.write(bytes(u')\n', 'UTF-8'))
del output_file


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Migration.BusinessModel;
using Microsoft.TeamFoundation.Migration.EntityModel;

namespace Microsoft.TeamFoundation.Migration.Toolkit.Services
{
    /// <summary>
    /// This abstract class provides the basic common implementation for some of the ITranslationService methods.
    /// </summary>
    public abstract class TranslationServiceBase : ITranslationService
    {
        protected readonly Session m_session;
        protected MigrationItemCache m_migrationItemCache = new MigrationItemCache();

        // The Guid key is a MigrationSource Guid
        protected Dictionary<Guid, MigrationItemId> m_lastMigratedItemsForMigrationSource = new Dictionary<Guid, MigrationItemId>();

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="userIdLookupService"></param>
        internal TranslationServiceBase(Session session, UserIdentityLookupService userIdLookupService)
        {
            m_session = session;
            UserIdLookupService = userIdLookupService;
        }

        internal UserIdentityLookupService UserIdLookupService
        {
            get;
            set;
        }

        #region ITranslationService Members

        public abstract void Translate(IMigrationAction action, Guid migrationSourceIdOfChangeGroup);

        public abstract bool IsSyncGeneratedAction(IMigrationAction action, Guid migrationSourceIdOfChangeGroup);

        public virtual bool IsSyncGeneratedItemVersion(string itemId, string itemVersion, Guid migrationSourceIdOfChangeGroup)
        {
            if (m_migrationItemCache.IsItemVersionMigratedByUs(migrationSourceIdOfChangeGroup, itemId, itemVersion))
            {
                return true;
            }

            using (RuntimeEntityModel context = RuntimeEntityModel.CreateInstance())
            {
                var migrationItemResult =
                    from mi in context.RTMigrationItemSet
                    where mi.ItemId.Equals(itemId)
                    select mi;

                if (migrationItemResult.Count() > 0)
                {
                    var migrationItemVersionQuery =
                        from rev in migrationItemResult
                        where rev.ItemVersion.Equals(itemVersion)
                           && rev.MigrationSource.UniqueId.Equals(migrationSourceIdOfChangeGroup)
                        select rev.Id;

                    if (migrationItemVersionQuery.Count() > 0)
                    {
                        long sourceItemId = migrationItemVersionQuery.First();
                        Guid sessionId = new Guid(m_session.SessionUniqueId);

                        var itemConvPairResult =
                            from p in context.RTItemRevisionPairSet
                            where (p.LeftMigrationItem.Id == sourceItemId || p.RightMigrationItem.Id == sourceItemId)
                               && p.ConversionHistory.SessionRun.Config.SessionUniqueId.Equals(sessionId)
                            select p;

                        return itemConvPairResult.Count() > 0;
                    }
                }

                return false;
            }
        }

        public abstract string TryGetTargetItemId(string sourceItemId, Guid sourceId);

        public virtual void CacheItemVersion(string sourceItemId, string sourceVersionId, Guid sourceId)
        {
            MigrationItemId migrationItemId = new MigrationItemId();
            migrationItemId.ItemId = sourceItemId;
            migrationItemId.ItemVersion = sourceVersionId;
            if (m_lastMigratedItemsForMigrationSource.ContainsKey(sourceId))
            {
                m_lastMigratedItemsForMigrationSource[sourceId] = migrationItemId;
            }
            else
            {
                m_lastMigratedItemsForMigrationSource.Add(sourceId, migrationItemId);
            }
        }

        public virtual MigrationItemId GetLastMigratedItemId(Guid sourceId)
        {
            MigrationItemId migrationItemId;
            if (!m_lastMigratedItemsForMigrationSource.TryGetValue(sourceId, out migrationItemId))
            {
                migrationItemId.ItemId = null;
            }
            return migrationItemId;
        }

        public abstract string GetLastProcessedItemVersion(string sourceItemId, Guid sourceId);

        public abstract void UpdateLastProcessedItemVersion(Dictionary<string, string> itemVersionPair, long lastChangeGroupId, Guid sourceId);

        #endregion
    }
}


text:
Homework 4
==========

Nate Mara

CSE 278

#. Components of Von Newman archetecture:

    1. ALU
    2. Control Unit
    3. Memory
    4. I/O

#. The EIP register is the instruction pointer register. It points to the
   location of the next instruction to be run by the processor.

#. The CS register points to the location of the code segment in memory. The DS
   register points to the data segment in memory. The SS register points to the
   location of the stack segment in memory. The ES register can be used to point
   to "extra" segments of memory, like video memory.

#. Addressing modes:

    #. Base addressing
    #. Displacement addressing
    #. Displacement addressing
    #. Displacement addressing

#. This instruction would be located at :code:`2100H`.
#. This instruction would be located at :code:`11482H`.
#. Two move instructions:

    #. This moves the value :code:`1234ABCD` into register EAX
    #. This moves the value :code:`1234` into the location pointed to by
       register AX.


text:
"""Loss scaling optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.eager import context
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_control_flow_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training import optimizer

class LossScaleOptimizer(optimizer.Optimizer):
  # TODO(jamesqin): move mixed precision training explanation to __init__
  # docstring.
  """An optimizer that applies loss scaling in backprop.

  This class is useful for "mixed precision training" on GPUs (or other
  potential accelerators), an approach to improve compute throughput without
  compromising model quality.

  The canonical way to perform mixed precision training is the following:
  * Model variables are kept in high precision (e.g. float32).
  * Computations are done in lower precision (e.g. float16), which enjoys
    performance speedup by virtue of hardware support. Variables are casted to
    lower precision before they're used.
  * Final gradients are casted back to high precision dtype, then used to update
    variables.

  The side-effect of performing computation in lower precision, is that it comes
  with smaller numerical range. During backproping, small gradients might
  underflow in the reduced numerical range, causing a model to converge at
  suboptimal level.

  To prevent underflow, this optimizer multiplies the loss by a factor before
  backprop starts. Consequently, the gradients are linearly scaled up by the
  same factor, thus not falling into the underflow zone. After that, to perserve
  the correctness of backprop, the gradients are down-scaled by the same factor,
  casted to the (higher) variable precision, then applied on the variables.

  See [Nvidia's manual on mixed precision training](
  https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html)
  for more details.

  To use loss scale optimizer, one only needs choose a loss scale strategy and
  wrap a regular optimizer. See examples below.

  ```
  loss = loss_fn()
  opt = tf.AdamOptimizer(learning_rate=...)

  # Choose a loss scale manager which decides how to pick the right loss scale
  # throughout the training process.
  loss_scale_manager = tf.contrib.mixed_precision.FixedLossScaleManager(5000)

  # Wraps the original optimizer in a LossScaleOptimizer.
  loss_scale_optimizer =
      tf.contrib.mixed_precision.LossScaleOptimizer(opt, loss_scale_manager)

  # Call minimize() on the loss scale optimizer.
  train_op = loss_scale_optimizer.minimize(loss)
  ```

  If gradients clipping is applied, one can call
  `optimizer.compute_gradients()` and `optimizer.apply_gradients()`
  separately.

  Notice the following way of using LossScaleOptimizer is not intended. Always
  use `loss_scale_optimizer.compute_gradients()` to compute gradients instead of
  `tf.gradients()` if doing mixed precision training.

  ```
  # The following is a wrong way to use LossScaleOptimizer along with
  # tf.gradients().

  # Always use loss_scale_optimizer.compute_gradients() to compute grads, or
  # loss scale is not correctly applied.
  grads = tf.gradients(loss, ...)

  # Do some custom grad clipping.
  grads = clip_grads(grads, ...)

  loss_scale_optimizer.apply(grads_and_vars)
  ```
  """

  def __init__(self, opt, loss_scale_manager):
    """Construct a loss scaling optimizer.

    Args:
      opt: The actual optimizer that will be used to compute and apply the
        gradients. Must be an implementation of the `tf.train.Optimizer`
        interface.
      loss_scale_manager: A LossScaleManager object.
    """
    self._opt = opt
    self._loss_scale_manager = loss_scale_manager

  def compute_gradients(self,
                        loss,
                        var_list=None,
                        gate_gradients=optimizer.Optimizer.GATE_OP,
                        aggregation_method=None,
                        colocate_gradients_with_ops=False,
                        grad_loss=None):
    """Compute gradients. See base class `tf.train.Optimizer`."""
    loss_scale = self._loss_scale_manager.get_loss_scale()
    if context.executing_eagerly():

      def scaled_loss():
        loss_val = loss()
        return loss_val * math_ops.cast(loss_scale, loss_val.dtype.base_dtype)
    else:
      if callable(loss):
        loss_val = loss()
      else:
        loss_val = loss
      scaled_loss = loss_val * math_ops.cast(loss_scale,
                                             loss_val.dtype.base_dtype)
    grads_and_vars = self._opt.compute_gradients(
        scaled_loss,
        var_list=var_list,
        gate_gradients=gate_gradients,
        aggregation_method=aggregation_method,
        colocate_gradients_with_ops=colocate_gradients_with_ops,
        grad_loss=grad_loss)
    return self._down_scale(grads_and_vars, loss_scale)

  def apply_gradients(self, grads_and_vars, global_step=None, name=None):
    """Apply gradients. See base class `tf.train.Optimizer`."""
    grads = [g for (g, _) in grads_and_vars]

    is_finite_grad = []
    for g in grads:
      is_finite_grad.append(math_ops.reduce_all(gen_math_ops.is_finite(g)))
    is_overall_finite = math_ops.reduce_all(is_finite_grad)

    # Only update gradients when all grads are finite.
    def true_apply_gradients_fn():
      return self._opt.apply_gradients(grads_and_vars, global_step, name)

    update_vars = control_flow_ops.cond(
        is_overall_finite, true_apply_gradients_fn, gen_control_flow_ops.no_op)
    # Potentially adjust gradient scale in case of finite gradients.
    return control_flow_ops.group(
        update_vars,
        self._loss_scale_manager.update_loss_scale(is_overall_finite))

  def _down_scale(self, grads_vars, loss_scale):
    # Down scale grads by the loss_scale.
    gv = []
    inv_loss_scale = gen_math_ops.reciprocal(loss_scale)
    for g, v in grads_vars:
      if g is not None:
        gv.append((g * math_ops.cast(inv_loss_scale, g.dtype.base_dtype), v))
      else:
        gv.append((g, v))
    return gv


text:
<?php
class IsActiveException extends Exception {
	public function errorMessage() {
		$errorMsg = 'Account is not active! Please wait until somone approved it.';
		return $errorMsg;
	}
}
?>


text:
package com.salesmanager.shop.store.api.exception;

import java.util.Objects;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice({"com.salesmanager.shop.store.api"})
public class RestErrorHandler {

    private static final Logger log = LoggerFactory.getLogger(RestErrorHandler.class);

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody ErrorEntity handleServiceException(Exception exception) {
        log.error(exception.getMessage(), exception);
        Objects.requireNonNull(exception.getCause());
        Throwable rootCause = exception.getCause();
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }
        ErrorEntity errorEntity = createErrorEntity("500", exception.getMessage(),
        		rootCause.getMessage());
        return errorEntity;
    }

    /**
     * Generic exception serviceException handler
     */
    @RequestMapping(produces = "application/json")
    @ExceptionHandler(ServiceRuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody ErrorEntity handleServiceException(ServiceRuntimeException exception) {
        log.error(exception.getErrorMessage(), exception);
        Throwable rootCause = exception.getCause();
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }
        ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode()!=null?exception.getErrorCode():"500", exception.getErrorMessage(),
        		rootCause.getMessage());
        return errorEntity;
    }

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(ConversionRuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody ErrorEntity handleServiceException(ConversionRuntimeException exception) {
        log.error(exception.getErrorMessage(), exception);
        ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode(), exception.getErrorMessage(),
            exception.getLocalizedMessage());
        return errorEntity;
    }

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody ErrorEntity handleServiceException(ResourceNotFoundException exception) {
        log.error(exception.getErrorMessage(), exception);

        ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode(), exception.getErrorMessage(),
                exception.getLocalizedMessage());
        return errorEntity;
    }

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public @ResponseBody ErrorEntity handleServiceException(UnauthorizedException exception) {
        log.error(exception.getErrorMessage(), exception);

        ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode(), exception.getErrorMessage(),
                exception.getLocalizedMessage());
        return errorEntity;
    }

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(RestApiException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody ErrorEntity handleRestApiException(RestApiException exception) {
        log.error(exception.getErrorMessage(), exception);

        ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode(), exception.getErrorMessage(),
                exception.getLocalizedMessage());
        return errorEntity;
    }

    private ErrorEntity createErrorEntity(String errorCode, String message, String detailMessage) {
        ErrorEntity errorEntity = new ErrorEntity();
        Optional.ofNullable(errorCode)
                .ifPresent(errorEntity::setErrorCode);

        String resultMessage = (message != null && detailMessage !=null)  ? new StringBuilder().append(message).append(", ").append(detailMessage).toString() : detailMessage;
        if(StringUtils.isBlank(resultMessage)) {
        	resultMessage = message;
        }
        Optional.ofNullable(resultMessage)
                .ifPresent(errorEntity::setMessage);
        return errorEntity;
    }
}


text:
require 'spec_helper'

describe Facilethings::Mail do
	before(:each) do
    @client = Facilethings::REST::Client.new(:key => FT_KEY, :secret => FT_SECRET, :token =>  MY_ACCESS_TOKEN, :endpoint => FT_ENDPOINT)
	end

	describe "#attr_reader and #attr_accessor" do
		it "should build get methods for all attributes" do
			mail = Facilethings::Mail.new(@client, { :id => 2, :created_at => DateTime.now,
				:mail => "pachisaez@hotmail.com", :marked => false, :language => "es", :was_client => true,
				:first_name => "Pachi" })

			expect(mail.id).to eq(2)
			expect(mail.created_at).to be_a DateTime
			expect(mail.mail).to eq("pachisaez@hotmail.com")
			expect(mail.first_name).to eq("Pachi")
			expect(mail.language).to eq("es")
			expect(mail.marked).to eq(false)
			expect(mail.was_client).to eq(true)
		end
		it "should build set methods for accessor attributes" do
			mail = Facilethings::Mail.new(@client)
			mail.mail = "pachisaez@hotmail.com"
			mail.first_name = "Pachi"
			mail.language = "es"
			mail.marked = true

			expect(mail.mail).to eq("pachisaez@hotmail.com")
			expect(mail.first_name).to eq("Pachi")
			expect(mail.language).to eq("es")
			expect(mail.marked).to eq(true)
		end
		it "should not build set methods for reader attributes" do
			mail = Facilethings::Mail.new(@client)

			expect{mail.id = 4}.to raise_error(NoMethodError)
			expect{mail.created_at = DateTime.now}.to raise_error(NoMethodError)
			expect{mail.was_client = true}.to raise_error(NoMethodError)
		end
	end

end


text:
# Nusharp

A (very) simple nuget c# nuget server, using [Nancy](https://github.com/NancyFx/Nancy) and running under [Mono](https://github.com/mono/mono).

#Installation

```bash
sudo adduser --disabled-login --gecos 'Nusharp' nusharp
cd /home/nusharp
sudo -u nusharp -H git clone https://github.com/willemda/Nusharp.git
sudo mkdir /opt/nusharp #nusharp will be installed here
sudo mkdir /var/nusharp/packages #packages store
sudo chown nusharp /opt/nusharp
sudo chown nusharp /var/nusharp/packages
sudo -u nusharp xbuild /property:OutputPath='/opt/nusharp'
sudo -u nusharp vim /opt/nusharp/Nusharp.SelfHost.exe.config #edit config, see below
```

Change the config to match your setup

```csharp
<add key="packageRepositoryPath" value="/var/nusharp/packages"/> /*package store*/
<add key="port" value="80"/> /*local port to bind*/
<add key="uri" value="http://mynugetserver.mydomain.com"/> /*external uri*/
<add key="username" value="Nusharp"/> /*basic auth, leave empty to disable basic auth*/
<add key="password" value="D64767AA-CCC2-43C9-BA99-F39247963628"/> /*basic auth passw*/
```

```bash
sudo apt-get install supervisor
sudo vim /etc/supervisor/conf.d/nusharp
```

Make sure to edit the config file to match your setup:

```bash
[program:nusharp]
command=/opt/mono/bin/mono Nusharp.SelfHost.exe -d
user=nusharp
stderr_logfile = /var/log/supervisor/nusharp-err.log
stdout_logfile = /var/log/supervisor/nusharp-stdout.log
directory=/opt/nusharp
```

#Other Nuget Server Projects

[https://github.com/kendarorg/PhpNuget](https://github.com/kendarorg/PhpNuget)


text:
MAGSIXG1 ;WOIFO/EdM/GEK/SEB/SG/NST - LIST OF IMAGES RPCS ; JUN 11, 2018@11:43 AM
 ;;3.0;IMAGING;**8,48,59,93,117,221**;Mar 19, 2002;Build 2238;Jul 15, 2011
 ;; Per VHA Directive 2004-038, this routine should not be modified.
 ;; +---------------------------------------------------------------+
 ;; | Property of the US Government.                                |
 ;; | No permission to copy or redistribute this software is given. |
 ;; | Use of unreleased versions of this software requires the user |
 ;; | to execute a written test agreement with the VistA Imaging    |
 ;; | Development Office of the Department of Veterans Affairs,     |
 ;; | telephone (301) 734-0100.                                     |
 ;; | The Food and Drug Administration classifies this software as  |
 ;; | a medical device.  As such, it may not be changed in any way. |
 ;; | Modifications to this software may result in an adulterated   |
 ;; | medical device under 21CFR820, the use of which is considered |
 ;; | to be a violation of US Federal Statutes.                     |
 ;; +---------------------------------------------------------------+
 ;;
 Q
 ;
 ;+++++ FORMATS RPC ERRORS
ERRORS(RESULTS,RC) ;
 S:$G(RC)'<0 RC=$$FIRSTERR^MAGUERR1()
 D RPCERRS^MAGUERR1(.RESULTS,RC)
 Q
 ;
 ;***** RETURNS THE LIST OF IMAGE DESCRIPTORS
 ; RPC: MAG4 IMAGE LIST
 ;
 ; .MAGOUT       Reference to a local variable where the results
 ;               are returned to.
 ;
 ; FLAGS         Flags that control the execution (can be combined):
 ;
 ;                 C  Capture date range. If this flag is provided,
 ;                    then the remote procedure uses values of the
 ;                    FROMDATE and TODATE parameters to select images
 ;                    that were captured in this date range.
 ;
 ;                    Otherwise, values of those parameters are
 ;                    treated as the date range when procedures were
 ;                    performed.
 ;
 ;                 D  Include only deleted images (file #2005.1)
 ;                 E  Include only existing images (file #2005)
 ;
 ;                 S  Return the sparse subset of images captured by
 ;                    the user defined by the MISCPRMS("SAVEDBY").
 ;                    The latter becomes required in this case.
 ;
 ;                 G  Include Group Images in the list of images returned.
 ;                    If any image in a group has an image that matches the
 ;                    status provided in the search criteria then
 ;                    the group will be returned.
 ;
 ;                    If the G flag is not set then only the status of the
 ;                    Group entry will be checked and the group will be
 ;                    returned if it passes.
 ;
 ;                    See description of the MAG4 IMAGE LIST remote
 ;                    procedure for details.
 ;
 ;               If neither 'E' nor 'D' flag is provided, then an
 ;               error code is returned.
 ;
 ; [FROMDATE]    Date range for image selection. Dates can be in
 ; [TODATE]      internal or external FileMan format. If a date
 ;               parameter is not defined or empty, then the date
 ;               range remains open on the corresponding side.
 ;
 ;               Time parts of parameter values are ignored and both
 ;               ends of the date range are included in the search.
 ;               For example, in order to search images for May 21,
 ;               2008, the internal value of both parameters should
 ;               be 3080521.
 ;
 ;               If the FROMDATE is after the TODATE, then values of
 ;               the parameters are swapped.
 ;
 ; [MAXNUM]      If this parameter is defined and greater than 0,
 ;               then it determines the maximum number of images
 ;               returned by the call.
 ;
 ;               If the S flag is included in the value of the FLAGS
 ;               parameter, then the MAXNUM parameter must be defined
 ;               and greater than 0. Its value determines percentage
 ;               of preselected images to be returned in the result
 ;               array.
 ;
 ;               See description of the MAG4 IMAGE LIST remote
 ;               procedure for details.
 ;
 ; [.MISCPRMS]   Reference to a local variable that stores misc.
 ;               parameters that define the image selection criteria.
 ;               See the description of the MAG4 IMAGE LIST remote
 ;               procedure for details.
 ;
 ; Return Values
 ; =============
 ;
 ; If MAGOUT(0) is defined and its 1st '^'-piece is 0, then an error
 ; occurred during execution of the procedure. In this case, the array
 ; is formatted as described in the comments to the RPCERRS^MAGUERR1.
 ;
 ; See description of the MAG4 IMAGE LIST remote procedure for more
 ; details.
 ;
 ; Notes
 ; =====
 ;
 ; Temporary global nodes ^TMP("MAGSIX1",$J) and ^TMP("MAGSIXG3",$J)
 ; are used by this procedure.
 ;
 ; If the number of images conforming to the filter reaches 76, all
 ; results are stored in the ^TMP("MAGSIXG1",$J) global node, closed
 ; reference is assigned to the MAGOUT parameter, and the type of the
 ; RPC return parameter is changed to 'GLOBAL ARRAY'.
 ;
GETIMGS(MAGOUT,FLAGS,FROMDATE,TODATE,MAXNUM,MISCPRMS) ;RPC [MAG4 IMAGE LIST]
 N MAGDATA       ; Array for passing the data to the callback
 ;               ; function of the image query (including the
 ;               ; image selection criteria).
 ;
 N ERROR,MISC,QF,RC,TMP
 S (MAGDATA("RESCNT"),RC)=0,MAGDATA="MAGOUT"  K MAGOUT
 D CLEAR^MAGUERR(1),NETPLCS^MAGGTU6
 K ^TMP("MAGSIXG3",$J)
 ;
 S MAXNUM=$G(MAXNUM)
 ;=== Validate parameters
 S ERROR=$$VALPARAM(.MAGDATA,FLAGS,.FROMDATE,.TODATE,MAXNUM,.MISCPRMS)
 ;
 ;--- Check for errors
 I ERROR D ERROR^MAGUERR(-30),ERRORS(.MAGOUT)  Q
 ;
 S MAXNUM=+$G(MAXNUM)
 ;
 ;=== Query the image file(s)
 S MAGDATA("FLAGS")=FLAGS,MAGDATA("MAXNUM")=MAXNUM
 S TMP=$S(TODATE<9999999:$$FMADD^XLFDT(TODATE,1),1:TODATE)
 S QF=$$TRFLAGS^MAGUTL05(FLAGS,"CDEG")
 S RC=$$QUERY^MAGGI13("$$QRYCBK^MAGSIXG3",QF,.MAGDATA,FROMDATE,TMP,+$G(MAGDATA("IDFN")))
 I RC<0  D ERRORS(.MAGOUT,RC)  Q
 ;
 ;=== Post-processing for the sparse subset query
 I FLAGS["S"  D  I RC<0  D ERRORS(.MAGOUT,RC)  Q
 . S RC=$$SUBSET^MAGSIXG4()
 . Q
 ;
 ;=== Cleanup
 K ^TMP("MAGSIXG3",$J)
 S TMP=$$FLTDESC^MAGSIXG2(.MAGDATA,FROMDATE(0),TODATE(0),FLAGS)
 I 'MAGDATA("RESCNT")  D ERRORS(.MAGOUT,$$ERROR^MAGUERR(-19,,TMP))  Q
 S @MAGDATA@(0)="1^"_TMP_$S($G(MAGDATA("MAXNUM")):U_(RC>0),1:"")
 S @MAGDATA@(1)=$$BLDHDR^MAGSIXG2()
 Q
 ;
 ;***** GET IMAGES FOR THE PATIENT
 ; RPC: MAG4 PAT GET IMAGES
 ;
 ; .MAGOUT       Reference to a local variable where the results
 ;               are returned to.
 ;
 ; DFN           Patient IEN (DFN)
 ;
 ; [PKG]         Package index(es)
 ; [CLASS]       Class index(es)
 ; [TYPE]        Type index(es)
 ; [EVENT]       Procedure/Event index(es)
 ; [SPEC]        Speciality/SubSpecialty index(es)
 ;
 ; [FROMDATE]    Date range for image selection. See description
 ; [TODATE]      of the GETIMGS^MAGSIXG1 entry point for details.
 ;
 ; [ORIGIN]      Origin index(es)
 ;
 ; [DATA]        Reserved for future use.
 ;
 ; [FLAGS]       Flags that control the execution (can be combined):
 ;
 ;                 D  Include only deleted images (file #2005.1)
 ;                 E  Include only existing images (file #2005)
 ;
 ;               By default ($G(FLAGS)=""), the "E" value is assumed.
 ;
 ; Return Values
 ; =============
 ;
 ; See description of the MAG4 PAT GET IMAGES remote procedure.
 ;
PGI(MAGOUT,DFN,PKG,CLASS,TYPE,EVENT,SPEC,FROMDATE,TODATE,ORIGIN,DATA,FLAGS) ;RPC [MAG4 PAT GET IMAGES]
 N I,MISCPRMS
 K MAGOUT  S I=0
 ;--- Check the patient IEN (DFN)
 I $G(DFN)'>0  D ERRORS(.MAGOUT,$$IPVE^MAGUERR("DFN"))  Q
 S I=I+1,MISCPRMS(I)="IDFN^^"_(+DFN)
 ;--- Check the flags
 S:$G(FLAGS)="" FLAGS="E"
 I $TR(FLAGS,"DE")'=""  D ERRORS(.MAGOUT,$$IPVE^MAGUERR("FLAGS"))  Q
 ;--- Pass the filter parameters through
 S:$G(PKG)'="" I=I+1,MISCPRMS(I)="IXPKG^^"_$TR(PKG,",","^")
 S:$G(CLASS)'="" I=I+1,MISCPRMS(I)="IXCLASS^^"_$TR(CLASS,",","^")
 S:$G(TYPE)'="" I=I+1,MISCPRMS(I)="IXTYPE^^"_$TR(TYPE,",","^")
 S:$G(EVENT)'="" I=I+1,MISCPRMS(I)="IXPROC^^"_$TR(EVENT,",","^")
 S:$G(SPEC)'="" I=I+1,MISCPRMS(I)="IXSPEC^^"_$TR(SPEC,",","^")
 S:$G(ORIGIN)'="" I=I+1,MISCPRMS(I)="IXORIGIN^^"_$TR(ORIGIN,",","^")
 ;--- Call the new remote procedure implementation
 D GETIMGS(.MAGOUT,FLAGS,.FROMDATE,.TODATE,,.MISCPRMS)
 Q
 ;
VALPARAM(MAGDATA,FLAGS,FROMDATE,TODATE,MAXNUM,MISCPRMS)  ; Validate input parameters
 N ERROR,MISC,MISCDEFS,RC,TMP
 ;--- Control flags
 S ERROR=0
 S FLAGS=$G(FLAGS)
 I $TR(FLAGS,"CDESG")'=""  D  S ERROR=1
 . D IPVE^MAGUERR("FLAGS")     ; Unknown/Unsupported flag(s)
 . Q
 I $TR(FLAGS,"DE")=FLAGS  D  S ERROR=1
 . D ERROR^MAGUERR(-6,,"D,E")  ; Missing required flag
 . Q
 ;--- Date range
 S:$$DTRANGE^MAGUTL03(.FROMDATE,.TODATE)<0 ERROR=1
 ;--- Miscellaneous parameters
 S RC=$$LDMPDEFS^MAGUTL01(.MISCDEFS,"MISCDEFS^MAGSIXG2")
 I RC<0  S ERROR=1  Q
 S RC=$$RPCMISC^MAGUTL02(.MISCPRMS,.MISC,.MISCDEFS,"UV")
 I RC<0  S ERROR=1  Q
 S:$$VALMISC^MAGSIXG2(.MISC,.MAGDATA)<0 ERROR=1
 ;--- Number/percentage of results
 I $G(MAXNUM)<0  D
 . D IPVE^MAGUERR("MAXNUM")  S ERROR=1
 . Q
 E  I FLAGS["S"  D
 . ;--- Check the percentage
 . S TMP=+$G(MAXNUM)
 . I 'TMP!(TMP>100)  D IPVE^MAGUERR("MAXNUM")  S ERROR=1  Q
 . S MAGDATA("SUBSET%")=TMP,MAXNUM=0
 . ;--- User filter is required for this query
 . S TMP=$NA(MAGDATA("SAVEDBY"))
 . I $G(@TMP)'>0  D ERROR^MAGUERR(-8,,TMP)  S ERROR=1  Q
 . Q
 ;
 Q ERROR


text:
App.Controller.SearchCollection = {

  attachTo: function(region){

    var $region = $(region),

      request = JSON.parse($region.attr('data-'+Engine.Config.Search.type)),
      viewName = $region.attr('data-view'),
      title = $region.attr('data-title')

      renderRegion = function(apps, textStatus, jqXHR){
        $region.append(App.View.make(viewName, {"apps":apps,"title":title}));
        $region.find('[data-app-details]').each(function(){
          App.Controller.Details.attachTo(this);
        })
        $region.find('.scrollable ul:not(.one-line)').each(function(){
          var $this = $(this), width = 0;
          $this.find('> li > *').each(function(){
            width += $(this).outerWidth(true);
          })
          $this.css('width', width);
        });
      },

      throwError = function(jqXHR, textStatus, errorThrown){
        console.error(errorThrown)
      }

    request._source = ['identity','attributes'];

    Engine.Search.elasticsearch({
      request: request,
      success: renderRegion,
      error: throwError
    })

  }

}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class SolrSearchConfig(AppConfig):
    name = 'solr_search'


text:
<?php

final class PhabricatorMailManagementSendTestWorkflow
  extends PhabricatorMailManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('send-test')
      ->setSynopsis(
        pht(
          'Simulate sending mail. This may be useful to test your mail '.
          'configuration, or while developing new mail adapters.'))
      ->setExamples('**send-test** --to alincoln --subject hi < body.txt')
      ->setArguments(
        array(
          array(
            'name'    => 'from',
            'param'   => 'user',
            'help'    => pht('Send mail from the specified user.'),
          ),
          array(
            'name'    => 'to',
            'param'   => 'user',
            'help'    => pht('Send mail "To:" the specified users.'),
            'repeat'  => true,
          ),
          array(
            'name'    => 'cc',
            'param'   => 'user',
            'help'    => pht('Send mail which "Cc:"s the specified users.'),
            'repeat'  => true,
          ),
          array(
            'name'    => 'subject',
            'param'   => 'text',
            'help'    => pht('Use the provided subject.'),
          ),
          array(
            'name'    => 'tag',
            'param'   => 'text',
            'help'    => pht('Add the given mail tags.'),
            'repeat'  => true,
          ),
          array(
            'name'    => 'attach',
            'param'   => 'file',
            'help'    => pht('Attach a file.'),
            'repeat'  => true,
          ),
          array(
            'name' => 'mailer',
            'param' => 'key',
            'help' => pht('Send with a specific configured mailer.'),
          ),
          array(
            'name'    => 'html',
            'help'    => pht('Send as HTML mail.'),
          ),
          array(
            'name'    => 'bulk',
            'help'    => pht('Send with bulk headers.'),
          ),
        ));
  }

  public function execute(PhutilArgumentParser $args) {
    $console = PhutilConsole::getConsole();
    $viewer = $this->getViewer();

    $from = $args->getArg('from');
    if ($from) {
      $user = id(new PhabricatorPeopleQuery())
        ->setViewer($viewer)
        ->withUsernames(array($from))
        ->executeOne();
      if (!$user) {
        throw new PhutilArgumentUsageException(
          pht("No such user '%s' exists.", $from));
      }
      $from = $user;
    }

    $tos = $args->getArg('to');
    $ccs = $args->getArg('cc');

    if (!$tos && !$ccs) {
      throw new PhutilArgumentUsageException(
        pht(
          'Specify one or more users to send mail to with `%s` and `%s`.',
          '--to',
          '--cc'));
    }

    $names = array_merge($tos, $ccs);
    $users = id(new PhabricatorPeopleQuery())
      ->setViewer($viewer)
      ->withUsernames($names)
      ->execute();
    $users = mpull($users, null, 'getUsername');

    $raw_tos = array();
    foreach ($tos as $key => $username) {
      // If the recipient has an "@" in any noninitial position, treat this as
      // a raw email address.
      if (preg_match('/.@/', $username)) {
        $raw_tos[] = $username;
        unset($tos[$key]);
        continue;
      }

      if (empty($users[$username])) {
        throw new PhutilArgumentUsageException(
          pht("No such user '%s' exists.", $username));
      }
      $tos[$key] = $users[$username]->getPHID();
    }

    foreach ($ccs as $key => $username) {
      if (empty($users[$username])) {
        throw new PhutilArgumentUsageException(
          pht("No such user '%s' exists.", $username));
      }
      $ccs[$key] = $users[$username]->getPHID();
    }

    $subject = $args->getArg('subject');
    if ($subject === null) {
      $subject = pht('No Subject');
    }

    $tags = $args->getArg('tag');
    $attach = $args->getArg('attach');
    $is_bulk = $args->getArg('bulk');

    $console->writeErr("%s\n", pht('Reading message body from stdin...'));
    $body = file_get_contents('php://stdin');

    $mail = id(new PhabricatorMetaMTAMail())
      ->addCCs($ccs)
      ->setSubject($subject)
      ->setBody($body)
      ->setIsBulk($is_bulk)
      ->setMailTags($tags);

    if ($tos) {
      $mail->addTos($tos);
    }

    if ($raw_tos) {
      $mail->addRawTos($raw_tos);
    }

    if ($args->getArg('html')) {
      $mail->setBody(
        pht(
          '(This is a placeholder plaintext email body for a test message '.
          'sent with %s.)',
          '--html'));

      $mail->setHTMLBody($body);
    } else {
      $mail->setBody($body);
    }

    if ($from) {
      $mail->setFrom($from->getPHID());
    }

    $mailer_key = $args->getArg('mailer');
    if ($mailer_key !== null) {
      $mailers = PhabricatorMetaMTAMail::newMailers();
      $mailers = mpull($mailers, null, 'getKey');
      if (!isset($mailers[$mailer_key])) {
        throw new PhutilArgumentUsageException(
          pht(
            'Mailer key ("%s") is not configured. Available keys are: %s.',
            $mailer_key,
            implode(', ', array_keys($mailers))));
      }

      $mail->setTryMailers(array($mailer_key));
    }

    foreach ($attach as $attachment) {
      $data = Filesystem::readFile($attachment);
      $name = basename($attachment);
      $mime = Filesystem::getMimeType($attachment);
      $file = new PhabricatorMetaMTAAttachment($data, $name, $mime);
      $mail->addAttachment($file);
    }

    PhabricatorWorker::setRunAllTasksInProcess(true);
    $mail->save();

    $console->writeErr(
      "%s\n\n    phabricator/ $ ./bin/mail show-outbound --id %d\n\n",
      pht('Mail sent! You can view details by running this command:'),
      $mail->getID());
  }

}


text:
/// <reference no-default-lib="true"/>

interface Symbol {
    /** Returns a string representation of an object. */
    toString(): string;

    /** Returns the primitive value of the specified object. */
    valueOf(): Object;
}

interface SymbolConstructor {
    /**
      * A reference to the prototype.
      */
    readonly prototype: Symbol;

    /**
      * Returns a new unique Symbol value.
      * @param  description Description of the new Symbol object.
      */
    (description?: string|number): symbol;

    /**
      * Returns a Symbol object from the global symbol registry matching the given key if found.
      * Otherwise, returns a new symbol with this key.
      * @param key key to search for.
      */
    for(key: string): symbol;

    /**
      * Returns a key from the global symbol registry matching the given Symbol if found.
      * Otherwise, returns a undefined.
      * @param sym Symbol to find the key for.
      */
    keyFor(sym: symbol): string | undefined;
}

declare var Symbol: SymbolConstructor;


text:
ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE(ACE_QOS_DECORATOR)

// Constructor.
ACE_QoS_Decorator_Base::ACE_QoS_Decorator_Base (void)
{}

// Constructor.
ACE_QoS_Decorator_Base::ACE_QoS_Decorator_Base (ACE_Event_Handler
                                                *event_handler)
  : event_handler_ (event_handler)
{
}

// Destructor.
ACE_QoS_Decorator_Base::~ACE_QoS_Decorator_Base (void)
{
}

// Forward the call to ACE_Event_Handler component.
ACE_HANDLE
ACE_QoS_Decorator_Base::get_handle (void) const
{
 return this->event_handler_->get_handle ();
}

// Forward the call to ACE_Event_Handler component.
int
ACE_QoS_Decorator_Base::handle_input (ACE_HANDLE fd)
{
  return this->event_handler_->handle_input (fd);
}

// Forward the call to ACE_Event_Handler component.
int
ACE_QoS_Decorator_Base::handle_qos (ACE_HANDLE fd)
{
  return this->event_handler_->handle_qos (fd);
}

// Constructor.
ACE_QoS_Decorator::ACE_QoS_Decorator (void)
{}

// Constructor.
ACE_QoS_Decorator::ACE_QoS_Decorator (ACE_Event_Handler *event_handler,
                                      ACE_QoS_Session *qos_session,
                                      ACE_Reactor *reactor)
  : qos_session_ (qos_session),
    reactor_ (reactor)
{
  ACE_NEW (this->decorator_base_,
           ACE_QoS_Decorator_Base (event_handler));

  ACE_NEW (this->qos_event_handler_,
           ACE_QoS_Event_Handler (this->decorator_base_));
}

// Destructor.
ACE_QoS_Decorator::~ACE_QoS_Decorator (void)
{
  delete this->decorator_base_;
  delete this->qos_event_handler_;
}

// Implements the undecorated functionality. This is sufficient for
// GQoS. RAPI needs additional QoS decoration. This is done by the
// ACE_QoS_Event_Handler class.
ACE_HANDLE
ACE_QoS_Decorator::get_handle (void) const
{
  return this->decorator_base_->get_handle ();
}

// Implements the undecorated functionality. This is sufficient for
// GQoS. RAPI needs additional QoS decoration. This is done by the
// ACE_QoS_Event_Handler class.
int
ACE_QoS_Decorator::handle_input (ACE_HANDLE fd)
{
  return this->decorator_base_->handle_input (fd);
}

// Implements the undecorated functionality. This is sufficient for
// GQoS. RAPI needs additional QoS decoration. This is done by the
// ACE_QoS_Event_Handler class.
int
ACE_QoS_Decorator::handle_qos (ACE_HANDLE fd)
{
  return this->decorator_base_->handle_qos (fd);
}

// This method registers the RAPI QoS event handler with the reactor
// if the application is using RAPI. Note that it is a no-op for GQoS
// because an extra socket for handling QoS events is not required.
int
ACE_QoS_Decorator::init (void)
{
#if defined (ACE_HAS_RAPI)

  // Pass the QoS session to QoS Event Handler.
  this->qos_event_handler_->qos_session (this->qos_session_);

  // Register the QoS Event Handler with the Reactor.
  return this->reactor_->register_handler (this->qos_event_handler_,
                                           ACE_Event_Handler::READ_MASK);
#endif
  return 0;

}

// Constructor.
ACE_QoS_Event_Handler::ACE_QoS_Event_Handler (void)
{
}

// Constructor.
ACE_QoS_Event_Handler::ACE_QoS_Event_Handler (ACE_QoS_Decorator_Base
                                              *decorator_base)
  : decorator_base_ (decorator_base)
{
}

// Destructor.
ACE_QoS_Event_Handler::~ACE_QoS_Event_Handler (void)
{
}

// Set the QoS session.
void
ACE_QoS_Event_Handler::qos_session (ACE_QoS_Session *qos_session)
{
  this->qos_session_ = qos_session;
}

// Returns the RAPI file descriptor for listening to RAPI evnets.
ACE_HANDLE
ACE_QoS_Event_Handler::get_handle (void) const
{
  return this->qos_session_->rsvp_events_handle ();
}

// Note, here the handle_input () calls the handle_qos () of the
// Decorator Base which then calls handle_qos () of the
// ACE_Event_Handler component within it. This helps to translate the
// normal read events into qos events in case of RAPI so the
// application using the API is oblivious to the fact that in RAPI,
// QoS events are received on a different socket. This helps to
// maintain a uniform design for the application irrespective of
// whether it is using RAPI or GQoS.
int
ACE_QoS_Event_Handler::handle_input (ACE_HANDLE fd)
{
  return this->decorator_base_->handle_qos (fd);
}

ACE_END_VERSIONED_NAMESPACE_DECL


text:
/**
 * this file will be loaded before server started
 * you can define global functions used in controllers, models, templates
 */

/**
 * use global.xxx to define global functions
 *
 * global.fn1 = function(){
 *
 * }
 */
"use strict";
//# sourceMappingURL=global.js.map


text:
<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\helpers\Url;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">

    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?=!empty($this->context->seoPage) ? $this->context->seoPage['meta'] : '';?>
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
    <link href="/fuelux/css/fuelux.min.css" rel="stylesheet">

<?php $this->beginBody() ?>

    <?php
    /*NavBar::begin([
        'brandLabel' => 'Efir.cityt',
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => [
            ['label' => 'Home', 'url' => ['/site/index']],
            ['label' => 'About', 'url' => ['/site/about']],
            ['label' => 'Contact', 'url' => ['/site/contact']],
            Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/site/login']]
            ) : (
                '
'
                . Html::beginForm(['/site/logout'], 'post', ['class' => 'navbar-form'])
                . Html::submitButton(
                    'Logout (' . Yii::$app->user->identity->username . ')',
                    ['class' => 'btn btn-link']
                )
                . Html::endForm()
                . '
'
            )
        ],
    ]);
    NavBar::end();*/
    ?>

        <?= Breadcrumbs::widget([
            'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
            'homeLink' => ['label' => 'Главная',
                'url' => Yii::$app->getHomeUrl()],
        ]) ?>

                    <?=$this->context->settings['site_name'];?>

                    <? if(!empty($this->context->seoPage)){ echo $this->context->seoPage['title'];}else{ ?>
                        Общение в <?=$this->context->city;?>, <?=$this->context->region;?>, <?=$this->context->country;?>
                    <? } ?>

                    <?
                        $title_text = !empty($this->context->seoPage) ? $this->context->seoPage['title_text'] : $this->context->settings['default_title_text'];
                        $title_text = str_replace('{city}',$this->context->city,$title_text);
                        $title_text = str_replace('{category}',$this->context->categoryInfo['category_name'],$title_text);
                    echo $title_text;
                    ?>

                            <button class="btn btn-primary btn-block buttonBack" id="buttonBack">
                                 Выбрать другой город
                            </button>

<?=!empty($this->context->seoPage['html_1_header']) ? $this->context->seoPage['html_1_header'] : $this->context->settings['html_1_header'];?>

<?=!empty($this->context->seoPage['html_1_text']) ? $this->context->seoPage['html_1_text'] : $this->context->settings['html_1_text'];?>

<?=!empty($this->context->seoPage['html_2_header']) ? $this->context->seoPage['html_2_header'] : $this->context->settings['html_2_header'];?>

<?=!empty($this->context->seoPage['html_2_text']) ? $this->context->seoPage['html_2_text'] : $this->context->settings['html_2_text'];?>

                        <?= $content ?>

                    <button class="btn btn-block btn-default bottomButtonWrite" id="bottomButtonWrite">
                        НАПИСАТЬ СООБЩЕНИЕ
                    </button>

Инструкция

Стоимость

Правила сервиса

Вопросы и ответы

Мы в Соц.сетях

                        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 socialBlock socialBlockVk" data-url="<?=$this->context->settings['vk'];?>">

                            В

Вконтакте

                        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 socialBlock socialBlockFb" data-url="<?=$this->context->settings['facebook'];?>">

                            f

Facebook

                        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 socialBlock socialBlockOk" data-url="<?=$this->context->settings['ok'];?>">

                            Ok

Ок

                    <?=!empty($this->context->settings['layout_footer']) ? $this->context->settings['layout_footer'] : 'Efir.city';?>

© alexseyka1 <?= date('Y') ?>

<?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
package org.squbs.sample.app;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;

import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class SampleDispatcherTest {

    static ActorSystem system;
    static FiniteDuration timeout = Duration.create(1, TimeUnit.SECONDS);

    @BeforeClass
    public static void beforeAll() {
        system = ActorSystem.create("SampleDispatcherTest");
    }

    @AfterClass
    public static void afterAll() {
        system.shutdown();
    }

    @Test
    public void testForwardRequest() {
        new JavaTestKit(system) {{
            ActorRef target = getSystem().actorOf(Props.create(SampleDispatcher.class), "SampleDispatcher");
            target.tell(new PingRequest("foo"), getRef());
            PingResponse response = expectMsgClass(timeout, PingResponse.class);
            assertEquals("Hello foo welcome to squbs!", response.message);
            String senderPath = getLastSender().path().toString();
            System.out.println(senderPath);
            assertTrue(senderPath.matches("akka://SampleDispatcherTest/user/SampleDispatcher/\\$\\w"));
        }};
    }
}


text:
namespace scalable {
template<typename Q>
struct is_pair{};

template<typename Key, typename Val>
struct is_pair<std::pair<Key, Val>> {
    typedef std::map<Key, Val> map_type;
    typedef std::unordered_map<Key, Val> unordered_map_type;
};

} //namespace scalable


text:
var List = require('../utils/list');

function getFirstMatchNode(matchNode) {
    if (matchNode.type === 'ASTNode') {
        return matchNode.node;
    }

    if (matchNode.match.length !== 0) {
        return getFirstMatchNode(matchNode.match[0]);
    }

    return null;
}

function getLastMatchNode(matchNode) {
    if (matchNode.type === 'ASTNode') {
        return matchNode.node;
    }

    if (matchNode.match.length !== 0) {
        return getLastMatchNode(matchNode.match[matchNode.match.length - 1]);
    }

    return null;
}

function matchFragments(lexer, ast, match, type, name) {
    function findFragments(matchNode) {
        if (matchNode.type === 'ASTNode') {
            return;
        }

        if (matchNode.syntax.type === type &&
            matchNode.syntax.name === name) {
            var start = getFirstMatchNode(matchNode);
            var end = getLastMatchNode(matchNode);

            lexer.syntax.walk(ast, function(node, item, list) {
                if (node === start) {
                    var nodes = new List();
                    var loc = null;

                    do {
                        nodes.appendData(item.data);

                        if (item.data === end) {
                            break;
                        }

                        item = item.next;
                    } while (item !== null);

                    if (start.loc !== null && end.loc !== null) {
                        loc = {
                            source: start.loc.source,
                            start: start.loc.start,
                            end: end.loc.end
                        };
                    }

                    fragments.push({
                        parent: list,
                        loc: loc,
                        nodes: nodes
                    });
                }
            });
        }

        matchNode.match.forEach(findFragments);
    }

    var fragments = [];

    if (match.matched !== null) {
        findFragments(match.matched);
    }

    return fragments;
}

module.exports = {
    matchFragments: matchFragments
};


text:
package edu.rice.compass;

public class WaveletConfigData {
	/* Matlab Data */
	public double[][] mCoords;
	public double[] mScale;
	public Object[] mPredNB;
	public Object[] mPredCoeff;
	public Object[] mUpdNB;
	public Object[] mUpdCoeff;

	public WaveletConfigData(double[][] coords, double[] scale, Object[] predNB,
						 Object[] predCoeff, Object[] updNB, Object[] updCoeff) {
		mCoords = coords;
		mScale = scale;
		mPredNB = predNB;
		mPredCoeff = predCoeff;
		mUpdNB = updNB;
		mUpdCoeff = updCoeff;
	}

}


text:
import React from 'react';
import Layout from './containers/Layout';
import Landing from './components/Landing';
import Tutorial1 from './components/tutorial/Tutorial1';
import Tutorial2 from './components/tutorial/Tutorial2';
import Tutorial3 from './components/tutorial/Tutorial3';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

class App extends React.Component {
	render() {

		return (
			<div>
				<Router history={hashHistory}>
					<Route path="/" component={Layout}>
						<IndexRoute component={Landing} />
                        <Route path="tutorial1" component={Tutorial1}/>
                        <Route path="tutorial2" component={Tutorial2}/>
                        <Route path="tutorial3" component={Tutorial3}/>
					</Route>
				</Router>
			</div>
		);
	}
}

export default App;


text:
==================
###How to create test runner for a module using Makefile

Makefiles are a simple way to organize code compilation, here we use makefile to automate testing.
To create your own test runner say xxxx-test in makefile:

  1. Open the Makefile (It is in flowsim/src/backend directory).
  2. Locate this line:

      `#--ADD PATH OF THE MODULE SPECIFIC TEST DIRECTORY HERE--`

  3. Add the path of the module specific test directory below the above located line. For example to add xxxx module test directory path (note we are excluding node_modules folder here, since it might contain its own test directory):

    `XXXX_TESTS=$(shell find -path "*/xxxx/test/rest*.js" -not -path "*/node_modules/*")`

  4. Finally we write the test runner as follows:

        xxxx-test:
          $(flyway) clean && $(flyway) migrate
          $(server) -t &
          @sleep 4
          -$(MOCHA) -t 90000 -R $(REPORTER) $(XXXX_TESTS)
          @killall node

    + Note that lines following **xxxx-test:** must be indented by tab and not by spaces.
    + **xxxx-test:** is the name of the test-runner.
    + **$(flyway) clean && $(flyway) migrate** is used to clean and migrate the database using flyway.
    + **$(server) -t &** will start server in test mode.
    + **@sleep 4** is used to wait(sleep for 4 seconds) for server to start.
    + **-$(MOCHA) -t 90000 -R $(REPORTER) $(PACKET_TESTS)**:
      + **- before $(MOCHA)** is used to ignore the errors which may occur during the tests, hence it makes sure that all test cases are executed.
      + **$(XXXX_TESTS)**: Give the name of the test directory path variable here (created in step 3).
    + **@killall node**: kills the server.

<span>5. </span>  Add the test runner name to **.PHONY** separated by comma:

      .PHONY: unit-test, system-test, xxxx-test

  + Why .PHONY?
    + Makefile targets are "file targets" - they are used to build files from other files. Make assumes its target is a file, and this makes writing Makefiles relatively easy. However, sometimes you want your Makefile to run commands that do not represent physical files in the file system. These special targets are called phony and you can explicitly tell Make they're not associated with files.

###How to run unit test runner

Unit test runner runs all the test files except the rest tests on server.

  1. Locate the Makefile
  2. Run the unit test runner as follows in that Makefile directory

      `make unit-test`

###How to run system test runner

System test runner runs all the rest tests on the server files except the unit tests.

  1. Locate the Makefile
  2. Run the system test runner as follows in that Makefile directory

      `make system-test`

###MOCHA TEST FRAMEWORK

  It is a feature-rich JS test framework running on node.js and the browser, making asynchronous testing simple and fun.

+ **describe()**
    * commonly known as test suites, which contains test cases
    * It is used for grouping test cases and we can have groups within groups
+ **it()**
    * This is used to write a test case
+ **before(), beforeEach(), after(), afterEach()**
    * All 'hooks' may be sync or async as well, behaving much like a regular test-case.
    * They are hooks to run before/after first/each it() or describe(), which means, `before()` is run before first it()/describe()
+ **before()**
    * Run once before the first test-case/test-suite
+ **beforeEach()**
    * Run once before each test-case/test-suite
+ **after()**
    * Run once before first test-case/test-suite
+ **afterEach()**
    * Run once after each test-case/test-suite

###HOW TO RUN TESTS

* To run mocha tests, just add all the mocha javascript test files in a folder called "test"
* By default mocha will use the pattern './test/*.js' if no parameter is given to it.
* From the root directory of the project, run "make unit-test" to execute that Makefile, which runs mocha tests on all the files present in the test folder except the rest test files.

###Example Code

####Testing synchronous code
When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test

    var assert = require('assert')

    describe('Array', function(){
      describe('#indexOf()', function(){
        it('should return -1 when the value is not present', function(){
          assert.equal([1,2,3].indexOf(5),-1);
          assert.equal([1,2,3].indexOf(0),-1);
        })
      })
    })

####To run this test:

    mocha -R spec test.js

####Testing Asynchronous code
Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it() Mocha will know that it should wait for completion.

    var assert = require("assert");
    var fs = require('fs');

    describe('fs', function(){
      describe('#readFile()', function(){
        it('should read without error', function(done){
          fs.readFile("test/test.js", function (err, data) {
            if (err) throw err;
            done();
          });
        });
      });
    });

####To run this test:

    mocha -R spec test.js


text:
RedIO
=====

MCU mod for Minecraft


text:
from msrest.serialization import Model

class ResizeError(Model):
    """An error that occurred when resizing a pool.

    :param code: An identifier for the pool resize error. Codes are invariant
     and are intended to be consumed programmatically.
    :type code: str
    :param message: A message describing the pool resize error, intended to be
     suitable for display in a user interface.
    :type message: str
    :param values: A list of additional error details related to the pool
     resize error.
    :type values: list of :class:`NameValuePair
     <azure.batch.models.NameValuePair>`
    """

    _attribute_map = {
        'code': {'key': 'code', 'type': 'str'},
        'message': {'key': 'message', 'type': 'str'},
        'values': {'key': 'values', 'type': '[NameValuePair]'},
    }

    def __init__(self, code=None, message=None, values=None):
        self.code = code
        self.message = message
        self.values = values


text:
<?php

/* FOSUserBundle:Security:login.html.twig */
class __TwigTemplate_ce690b3a1295eefe1803d63c558e66385f3365a18f96a80bc6683cc6c722776e extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("AcmeDefaultBundle::layout.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'js_css' => array($this, 'block_js_css'),
            'main' => array($this, 'block_main'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "AcmeDefaultBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_title($context, array $blocks = array())
    {
        echo "欢迎您登录 ";
    }

    // line 5
    public function block_js_css($context, array $blocks = array())
    {
        // line 6
        echo "
";
    }

    // line 10
    public function block_main($context, array $blocks = array())
    {
        // line 11
        echo "

登录

                    <form method=\"get\" action=\"./?qa=search\" class=\"form-inline search-form pull-right\">
                        <input type=\"hidden\" name=\"qa\" value=\"search\">\t

                            <input type=\"text\" name=\"q\" value=\"\" class=\"form-control navbar-search\" placeholder=\"Search for questions\">

                        <button type=\"submit\" class=\"icon-magnifier btn btn-primary\" title=\"Search\"></button>
                    </form>

facebook

twitter

PlusOne

                        <form  id=\"form\" class=\"form-horizontal\" method=\"post\" action=\"";
        // line 43
        echo $this->env->getExtension('routing')->getPath("fos_user_security_check");
        echo "\">

                                        <input name=\"_username\" id=\"emailhandle\" type=\"text\" value=\"\" class=\"qa-form-tall-text\" placeholder=\"Email or Username\">

                                        <input name=\"_password\" id=\"password\" type=\"password\" value=\"\" class=\"qa-form-tall-text\" placeholder=\"Password\">

                                                ";
        // line 55
        if ((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error"))) {
            // line 56
            echo "                                                    ";
            echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error"))), "html", null, true);
            echo "
                                                ";
        }
        // line 58
        echo "

                                        这是我的个人计算机

                                        <input name=\"_remember_me\" type=\"checkbox\" value=\"on\" class=\"qa-form-tall-checkbox\">

                                    <input value=\"登录\" title=\"\" type=\"submit\" name=\"_submit\" class=\"btn btn-default btn-login\">

                            <input type=\"hidden\" name=\"_csrf_token\" value=\"";
        // line 75
        echo twig_escape_filter($this->env, (isset($context["csrf_token"]) ? $context["csrf_token"] : $this->getContext($context, "csrf_token")), "html", null, true);
        echo "\" />
                        </form>

            ...

";
    }

    public function getTemplateName()
    {
        return "FOSUserBundle:Security:login.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  125 => 75,  106 => 58,  100 => 56,  98 => 55,  83 => 43,  49 => 11,  46 => 10,  39 => 6,  36 => 5,  30 => 3,);
    }
}


text:
class wxWindow;
class wxDialog;
class wxButton;
class wxFlexGridSizer;
class wxCommandEvent;

class preferenceWindow : public wxDialog {
	public:
		preferenceWindow(wxWindow*);
	private:
		wxFlexGridSizer * layout;
		void onOk(wxCommandEvent&);
		void onOpen(wxCommandEvent&);
		wxButton * launchFileButton;
};

#endif


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<title>Webtal Telecom</title>
	<meta name="viewport"
	      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="dist/css/villa.min.css"/>
	<link rel="stylesheet" href="dist/css/mowe.min.css"/>
	<link rel="stylesheet" href="css/wtal.css"/>

					<svg id="bg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
						<g>
							<path d="M332,203.5c151.6,163.9,151.6,429.1,0,592.9"></path>
							<path d="M403.5,111.8c199.7,214.6,199.7,561.9,0,776.5"></path>
							<path d="M468,20c266.7,265.3,266.7,694.7,0,960"></path>
						</g>
					</svg>

			<button class="toggle teal-700 font-white">

				<svg version="1.1" id="bars" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
					<g>
						<line class="st0" x1="99.1" y1="182.2" x2="1000" y2="182.2"/>
						<line class="st0" x1="99.1" y1="504.6" x2="1000" y2="504.6"/>
						<line class="st0" x1="99.1" y1="817.8" x2="1000" y2="817.8"/>
					</g>
				</svg>

			</button>

					Sobre

					Planos

					Contato

Bem vindo à
Webtal Telecom!

					Tenha a melhor internet pelo melhor custo benefício da região

			Conheça nossos planos

Selecione a sua cidade:

Bem vindo à Webtal Telecom!

Nosso compromisso é o de oferecer sempre os melhores serviços aos nossos clientes. Para tanto, investimos constantemente em novas tecnologias e nas soluções inovadoras, garantindo a evolução constante da qualidade do produto final disponibilizado a cada cliente.

Primamos pela excelência e o respeito no atendimento personalizado, na rapidez e na eficiência da assistência técnica oferecida gratuitamente e, principalmente, na qualidade e na estabilidade do sinal de internet com as melhores taxas de Download e Upload com o menor custo. Quem conhece, confia. Conheça você também.

Nossa história

WEBTal Telecom é o primeiro provedor de internet a oferecer serviço de acesso local nas cidades de Palmital e Campos Novos Paulista. É uma empresa criada com a filosofia de investir em tecnologia e que contribuiu decisivamente para a democratização da tecnologia da informação e à inclusão digital em toda a região.

A ampliação e a modernização permanente das redes de distribuição de sinal de internet e a confiança dos clientes tornou o provedor WEBTal Telecom sinônimo de inovação desde o início de sua operação comercial, em junho de 2001.

Com o trabalho consolidado de bons serviços prestados, é uma empresa que oferece o melhor de cada tecnologia disponível aos usuários, desde a rede wireless (sem fio), até as modernas redes de fibra óptica expandidas nos municípios de Palmital, Ibirarema e Platina e nos distritos de Nova Alexandria e Nossa Senhora Aparecida (PR), além de grande número de propriedades rurais e empresas dos municípios de Andirá (PR), Cândido Mota e Ribeirão do Sul.

Nos últimos anos, WEBTal Telecom investiu permanentemente na inovação e nas tecnologias de ponta para suprir as expectativas e as necessidades dos clientes residenciais, comerciais, industriais e rurais. Nos primeiros períodos de funcionamento, o acesso à internet era feito por meio de linha telefônica e recepção de sinal em modems analógicos.

Com a implantação do serviço via rádio (wireless), amplamente utilizado em todo o mundo, os usuários tiveram acesso ao sinal de melhor qualidade e com maior velocidade na transferência de dados, caracterizado pela Banda Larga.

Chegamos então à era da velocidade da luz, graças à implantação das redes de fibra óptica que chegam a cada endereço para oferecer o melhor serviço e garantir a velocidade ideal e necessária a cada cliente.

O pioneirismo e o empreendedorismo são as mais importantes contribuições empresariais à sociedade e ao desenvolvimento dos municípios, graças às profundas mudanças que o acesso facilitado à rede mundial de computadores causa na sociedade e na economia modernas.

Nos últimos anos a WEBTal buscou a inovação e as tecnologias de ponta para garantir o pleno atendimento às necessidades dos clientes residenciais, comerciais, industriais e rurais. Nos primeiros períodos de funcionamento o acesso à internet era feito por meio do uso de linha telefônica, que era onerado pelo custo dos pulsos cobrados pela operadora de telefonia. Com a implantação do serviço via rádio (wireless), amplamente utilizado em todo o mundo, os usuários se utilizam da comunicação sem fio com o provedor e também contam com maior qualidade no sinal para garantir velocidade na transferência de dados pelo acesso em banda larga.

Missão

Nosso objetivo principal é desenvolver, implantar e prover a melhor tecnologia em telecomunicação com elevado nível de excelência. Serviços e soluções inteligentes em conectividade atendem nossos clientes de forma integrada e garantem as telecomunicações com qualidade e alta disponibilidade para atividades empresariais, domésticas e de lazer.

Nossa missão é prestar o melhor serviço, com o melhor atendimento e com a melhor tecnologia para integrar e aproximar as pessoas.

Escolha o seu plano

Para melhor atender nossos clientes, criamos planos de acesso adaptados a cada exigência e necessidade. Escolha o seu plano e preencha o formulário. Nossa equipe vai trabalhar para oferecer o melhor serviço pelo menor custo.

			Exibindo planos disponíveis para
			<select name="city" id="city">
				<option value="palmital" selected>Palmital</option>
				<option value="ibirarema">Ibirarema</option>
				<option value="platina">Platina</option>
				<option value="demais-localidades">Demais Localidades</option>

			</select>

Residencial

Rural

Empresarial

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

Residencial

Rural

Empresarial

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

Residencial

Rural

Empresarial

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

Residencial

Rural

Empresarial

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

									1 Mega
									Upload: 600kbps

									2 Mega
									Upload: 600kbps

									3 Mega
									Upload: 600kbps

									4 Mega
									Upload: 800kbps

									Mais planos
									Sob consulta

Entre em contato

			18 3351 9500
			Fixo

			18 9 9677 9500
			Vivo

			18 9 9705 9500
			Vivo

			site@oai.com.br
			Email

Horários de atendimento

			Seg/Sex
			08:00 até 18:00

			Sábado
			08:00 até 13:00

		(18) 3351-9500 / Webtal Telecom, Palmital, SP, CEP 19970-000
		©Webtal Telecom 2015

		Desenvolvimento