text:
"""Tests for shared functionality for dtFabric-based data format plugins."""

import io
import unittest

from dtfabric import errors as dtfabric_errors
from dtfabric.runtime import data_maps as dtfabric_data_maps
from dtfabric.runtime import fabric as dtfabric_fabric

from plaso.lib import errors
from plaso.parsers.winreg_plugins import dtfabric_plugin

from tests.parsers.winreg_plugins import test_lib

class ErrorBytesIO(io.BytesIO):
  """Bytes IO that errors."""

  # The following methods are part of the file-like object interface.
  # pylint: disable=invalid-name

  def read(self, size=None):  # pylint: disable=unused-argument
    """Reads bytes.

    Args:
      size (Optional[int]): number of bytes to read, where None represents
          all remaining bytes.

    Raises:
      IOError: for testing.
      OSError: for testing.
    """
    raise IOError('Unable to read for testing purposes.')

class ErrorDataTypeMap(dtfabric_data_maps.DataTypeMap):
  """Data type map that errors."""

  def FoldByteStream(self, mapped_value, **unused_kwargs):
    """Folds the data type into a byte stream.

    Args:
      mapped_value (object): mapped value.

    Raises:
      FoldingError: for testing.
    """
    raise dtfabric_errors.FoldingError(
        'Unable to fold to byte stream for testing purposes.')

  def MapByteStream(self, byte_stream, **unused_kwargs):
    """Maps the data type on a byte stream.

    Args:
      byte_stream(bytes): byte stream.

    Raises:
      dtfabric.MappingError: for testing.
    """
    raise dtfabric_errors.MappingError(
        'Unable to map byte stream for testing purposes.')

class DtFabricBaseWindowsRegistryPluginTest(test_lib.RegistryPluginTestCase):
  """Shared functionality for dtFabric-based data format plugins tests."""

  # pylint: disable=protected-access

  _DATA_TYPE_FABRIC_DEFINITION = b"""\
name: uint32
type: integer
attributes:
  format: unsigned
  size: 4
  units: bytes
---
name: point3d
type: structure
attributes:
  byte_order: little-endian
members:
- name: x
  data_type: uint32
- name: y
  data_type: uint32
- name: z
  data_type: uint32
---
name: shape3d
type: structure
attributes:
  byte_order: little-endian
members:
- name: number_of_points
  data_type: uint32
- name: points
  type: sequence
  element_data_type: point3d
  number_of_elements: shape3d.number_of_points
"""

  _DATA_TYPE_FABRIC = dtfabric_fabric.DataTypeFabric(
      yaml_definition=_DATA_TYPE_FABRIC_DEFINITION)

  _POINT3D = _DATA_TYPE_FABRIC.CreateDataTypeMap('point3d')

  _POINT3D_SIZE = _POINT3D.GetByteSize()

  _SHAPE3D = _DATA_TYPE_FABRIC.CreateDataTypeMap('shape3d')

  # TODO: add tests for _GetDataTypeMap

  # TODO: add tests for _ReadDefinitionFile

  def testReadStructureFromByteStream(self):
    """Tests the _ReadStructureFromByteStream function."""
    parser = dtfabric_plugin.DtFabricBaseWindowsRegistryPlugin()

    parser._ReadStructureFromByteStream(
        b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00', 0,
        self._POINT3D)

    # Test with missing byte stream.
    with self.assertRaises(ValueError):
      parser._ReadStructureFromByteStream(None, 0, self._POINT3D)

    # Test with missing data map type.
    with self.assertRaises(ValueError):
      parser._ReadStructureFromByteStream(
          b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00', 0, None)

    # Test with data type map that raises an dtfabric.MappingError.
    data_type_map = ErrorDataTypeMap(None)

    with self.assertRaises(errors.ParseError):
      parser._ReadStructureFromByteStream(
          b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00', 0,
          data_type_map)

if __name__ == '__main__':
  unittest.main()


text:
from plumbum.commands.base import (
    ERROUT,
    BaseCommand,
    ConcreteCommand,
    shquote,
    shquote_list,
)
from plumbum.commands.modifiers import (
    BG,
    FG,
    NOHUP,
    RETCODE,
    TEE,
    TF,
    ExecutionModifier,
    Future,
)
from plumbum.commands.processes import (
    CommandNotFound,
    ProcessExecutionError,
    ProcessLineTimedOut,
    ProcessTimedOut,
    run_proc,
)

__all__ = (
    "BaseCommand",
    "ConcreteCommand",
    "shquote",
    "shquote_list",
    "ERROUT",
    "BG",
    "FG",
    "NOHUP",
    "RETCODE",
    "TEE",
    "TF",
    "ExecutionModifier",
    "Future",
    "CommandNotFound",
    "ProcessExecutionError",
    "ProcessLineTimedOut",
    "ProcessTimedOut",
    "run_proc",
)

def __dir__():
    return __all__

redpajama_set_name: RedPajamaGithub


text:
module MergeRequests
  class CreateService < MergeRequests::BaseService
    def execute
      # @project is used to determine whether the user can set the merge request's
      # assignee, milestone and labels. Whether they can depends on their
      # permissions on the target project.
      source_project = @project
      @project = Project.find(params[:target_project_id]) if params[:target_project_id]

      params[:target_project_id] ||= source_project.id

      merge_request = MergeRequest.new
      merge_request.source_project = source_project
      merge_request.merge_params['force_remove_source_branch'] = params.delete(:force_remove_source_branch)

      create(merge_request)
    end

    def after_create(issuable)
      event_service.open_mr(issuable, current_user)
      notification_service.new_merge_request(issuable, current_user)
      todo_service.new_merge_request(issuable, current_user)
      issuable.cache_merge_request_closes_issues!(current_user)
    end
  end
end


text:
function theResult = domenu(self, theEvent, varargin)

% pst/domenu -- Handler for "pst" menus.
%  domenu(self, 'theEvent') handles 'theEvent' on
%   behalf of self, a "pst" object.

% svn $Id: domenu.m 361 2009-07-02 15:43:20Z arango $
%=======================================================================
% Copyright (C) 1999 Dr. Charles R. Denham, ZYDECO.
%  All Rights Reserved.
%   Disclosure without explicit written consent from the
%    copyright owner does not constitute publication.
%=======================================================================

% Version of 05-Nov-1999 11:49:51.
% Updated    05-Nov-1999 15:00:06.

if nargout > 0, theResult = []; end
if nargin < 1, help(mfilename), return, end

try
	theHandler = handler(self, theEvent);
	result = builtin('feval', theHandler, self, theEvent);
catch
	errormsg(self)
end

if nargout > 0
	theResult = self;
end


text:
package org.kurento.jsonrpc;

/**
 * Exception thrown when trying to use a JsonRpcClient explicitly closed by user.
 *
 * @author Micael Gallego (micael.gallego@gmail.com)
 *
 */
public class JsonRpcClientClosedException extends RuntimeException {

  private static final long serialVersionUID = -6830100526527848866L;

  public JsonRpcClientClosedException() {
  }

  public JsonRpcClientClosedException(String message) {
    super(message);
  }

  public JsonRpcClientClosedException(Throwable cause) {
    super(cause);
  }

  public JsonRpcClientClosedException(String message, Throwable cause) {
    super(message, cause);
  }

  public JsonRpcClientClosedException(String message, Throwable cause, boolean enableSuppression,
      boolean writableStackTrace) {
    super(message, cause, enableSuppression, writableStackTrace);
  }

}


text:
from networkx import DiGraph, dijkstra_path
import os.path, sys
from pydispatch import dispatcher
try:
    import xml.etree.cElementTree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree
import inspect, marshal, types

from object import Object
from region import Region
from pathway import Pathway
from neuron import Neuron
from neurite import Neurite
from arborization import Arborization
from synapse import Synapse
from gap_junction import GapJunction
from stimulus import Stimulus
from muscle import Muscle
from innervation import Innervation
from attribute import Attribute

try:
    import pydot    # pylint: disable=F0401,W0611
except ImportError:
    pydot = None

class Network:

    def __init__(self):
        """
        Networks are containers for all :class:`objects <Network.Object.Object>` that exist in a neural circuit.
        """

        self.graph = DiGraph()
        self.objects = []
        self.idDict = {}   # TODO: weak ref dict?
        self.displays = []
        self._nextUniqueId = -1
        self._savePath = None
        self._attributes = []
        self._displaysAreSynchronized = True
        self._weightingFunction = None

        self._bulkLoading = False
        self._bulkAddObjects = []

        self._modified = False

    @classmethod
    def _fromXMLElement(cls, xmlElement):
        network = cls()

        network.setBulkLoading(True)

        # Load the classes in such an order that any referenced objects are guaranteed to have already been created.
        for moduleName, className in [('region', 'Region'), ('pathway', 'Pathway'), ('neuron', 'Neuron'), ('muscle', 'Muscle'), ('arborization', 'Arborization'), ('innervation', 'Innervation'), ('gap_junction', 'GapJunction'), ('synapse', 'Synapse'), ('stimulus', 'Stimulus')]:
            elementModule = getattr(sys.modules['network'], moduleName)
            elementClass = getattr(elementModule, className)
            for element in xmlElement.findall(className):
                networkObject = elementClass._fromXMLElement(network, element)
                if networkObject is not None:
                    network.addObject(networkObject)

        weightingFunctionElement = xmlElement.find('WeightingFunction')
        if weightingFunctionElement is not None:
            funcType = weightingFunctionElement.get('type')
            funcName = weightingFunctionElement.get('name')
            if funcType == 'source':
                exec(weightingFunctionElement.text)
                network._weightingFunction = eval(funcName)
            elif funcType == 'marshal':
                code = marshal.loads(eval(weightingFunctionElement.text))
                network._weightingFunction = types.FunctionType(code, globals(), funcName or 'weightingFunction')
            else:
                raise ValueError, gettext('Unknown weighting function type: %s') % (funcType)

        for element in xmlElement.findall('Attribute'):
            attribute = Attribute._fromXMLElement(network, element)
            if attribute is not None:
                network._attributes.append(attribute)

        network.setBulkLoading(False)

        return network

    def _toXMLElement(self, parentElement):
        networkElement = ElementTree.SubElement(parentElement, 'Network')

        for networkObject in self.objects:
            # Nested regions are handled by their parents and neurites are handled by their neurons.
            if not (isinstance(networkObject, Region) and networkObject.parentRegion is not None) and not isinstance(networkObject, Neurite):
                objectElement = networkObject._toXMLElement(networkElement)
                if objectElement is None:
                    pass    # TODO: are there any cases where this is NOT an error?

        if self._weightingFunction:
            weightingFunctionElement = ElementTree.SubElement(networkElement, 'WeightingFunction')
            weightingFunctionElement.set('name', self._weightingFunction.func_name)
            # First try to get the function source and if that fails then marshal the byte code.
            try:
                source = inspect.getsource(self._weightingFunction)
                weightingFunctionElement.text = source
                weightingFunctionElement.set('type', 'source')
            except IOError:
                weightingFunctionElement.text = repr(marshal.dumps(self._weightingFunction.func_code))
                weightingFunctionElement.set('type', 'marshal')

        for attribute in self._attributes:
            attribute._toXMLElement(networkElement)

        return networkElement

    def _toScriptFile(self, scriptFile, scriptRefs):
        if len(self._attributes) > 0:
            scriptFile.write(gettext('# Create the network') + '\n\n')
            for attribute in self._attributes:
                attribute._toScriptFile(scriptFile, scriptRefs)

        if self._weightingFunction:
            # First try to get the function source and if that fails then marshal the byte code.
            scriptFile.write(gettext('# Add the weighting function') + '\n\n')
            funcName = self._weightingFunction.func_name
            try:
                source = inspect.getsource(self._weightingFunction)
                scriptFile.write(source + '\n\nnetwork.setWeightingFunction(' + funcName + ')\n\n')
            except IOError:
                scriptFile.write('import marshal, types\n')
                scriptFile.write('code = marshal.loads(' + repr(marshal.dumps(self._weightingFunction.func_code)) + ')\n')
                scriptFile.write('network.setWeightingFunction(types.FunctionType(code, globals(), \'' + funcName + '\'))\n\n')

        # Add each network object to the script in an order that guarantees dependent objects will already have been added.
        # Neurites will be added by their neurons, sub-regions by their root region.
        for objectClass in (Region, Pathway, Muscle, Neuron, Arborization, GapJunction, Innervation, Synapse, Stimulus):
            objects = self.objectsOfClass(objectClass)
            if len(objects) > 0:
                scriptFile.write('\n# ' + gettext('Create each %s') % (objectClass.displayName().lower()) + '\n\n')
                for networkObject in objects:
                    if networkObject._includeInScript(atTopLevel = True):
                        networkObject._toScriptFile(scriptFile, scriptRefs)

    def setBulkLoading(self, bulkLoading):
        """
        Indicate whether or not a large quantity of objects are being added to the network.

        >>> network.setBulkLoading(True)
        >>> # ... add lots of objects ...
        >>> network.setBulkLoading(False)

        If bulk loading is enabled then various actions are delayed to make loading faster.
        """

        if bulkLoading != self._bulkLoading:
            self._bulkLoading = bulkLoading
            if self._bulkLoading == False:
                self._updateGraph()
                if any(self._bulkAddObjects):
                    dispatcher.send('addition', self, affectedObjects = self._bulkAddObjects)
                    self._bulkAddObjects = []
            dispatcher.send(('set', 'bulkLoading'), self)

    def setSavePath(self, path):
        if path != self._savePath:
            self._savePath = path
            dispatcher.send(('set', 'savePath'), self)

    def savePath(self):
        return self._savePath

    def name(self):
        if self._savePath is None:
            return gettext('Untitled Network')
        else:
            return os.path.splitext(os.path.basename(self._savePath))[0]

    def _generateUniqueId(self):
        self._nextUniqueId += 1
        return self._nextUniqueId

    def findObject(self, objectClass, name = None, default = False):
        """
        Return the first object of the given class with the given name.

        >>> neuron = network.findObject(Neuron, 'AVAL')

        Returns an :class:`Object <Network.Object.Object>` or None if there are no matching objects.

        If default is True then each object's :meth:`defaultName() <Network.Object.Object.defaultName>` will be queried instead of its name.
        """

        if name is not None:
            for networkObject in self.objects:
                if isinstance(networkObject, objectClass) and ((not default and networkObject.name == name) or (default and networkObject.defaultName() == name)):
                    return networkObject
        return None

    def findObjects(self, objectClass, name = None, default = False):
        """
        Return all objects of the given class with the given name.

        >>> neuron = network.findObject(Neuron, 'AVAL')

        Returns a list of :class:`Object <Network.Object.Object>` or None if there are no matching objects.

        If default is True then each object's :meth:`defaultName() <Network.Object.Object.defaultName>` will be queried instead of its name.
        """

        objects = []
        if name is not None:
            for networkObject in self.objects:
                if isinstance(networkObject, objectClass) and ((not default and networkObject.name == name) or (default and networkObject.defaultName() == name)):
                    objects.append(networkObject)
        return objects if objects else None

    def findObjectsRegex(self, objectClass, nameRegex = None, default = False):
        """
        Return all objects of the given class whos name matches the regular expression

        >>> neuron = network.findObject(Neuron, 'AVAL')

        Returns a list of :class:`Object <Network.Object.Object>` or None if there are no matching objects.

        """
        from re import search
        matchingObjects = []

        if nameRegex is not None:
            for networkObject in self.objects:
                if isinstance(networkObject, objectClass) and ((not default and search(nameRegex, networkObject.name)) or (default and search(nameRegex, networkObject.defaultName()))):
                    matchingObjects.append(networkObject)
        return matchingObjects if matchingObjects else None

    def createRegion(self, addSubTerms = False, *args, **keywordArgs):
        """
        Create a new region optionally associated with an ontology term.

        >>> region = network.createRegion(name = 'Glomerulus 2')

        To associate the region with an ontology term pass in a term from an ontology in the library:

        >>> flyBrainOnt = library.ontology('flybrain')
        >>> ellipsoidBody = network.createRegion(ontologyTerm = flyBrainOnt.findTerm(name = 'Ellipsoid body'))

        If addSubTerms is true then sub-regions will be created for all sub-terms in the ontology.

        Returns the :class:`region <Network.Region.Region>` that is created.
        """

        region = Region(self, *args, **keywordArgs)
        self.addObject(region)

        if region.ontologyTerm is not None and addSubTerms:
            for term in region.ontologyTerm.parts:
                self.createRegion(ontologyTerm = term, parentRegion = region, addSubTerms = True)

        return region

    def findRegion(self, name = None):
        """
        Find the first region with the given name.

        >>> region = network.findRegion('Ellipsoid body')

        Returns a :class:`region <Network.Region.Region>` or None if there are no regions with the name.
        """

        return self.findObject(Region, name)

    def regions(self):
        """
        Return a list of all :class:`regions <Network.Region.Region>` in the network.

        >>> for region in network.regions():
        ...     display.setVisibleColor(region, (1.0, 0.0, 0.0))

        An empty list will be returned if there are no regions in the network.
        """

        return self.objectsOfClass(Region)

    def pathways(self):
        """
        Return a list of all :class:`pathways <Network.Pathway.Pathway>` in the network.

        >>> for pathway in network.pathways():
        ...     display.setVisibleColor(pathway, (1.0, 0.0, 0.0))

        An empty list will be returned if there are no pathways in the network.
        """

        return self.objectsOfClass(Pathway)

    def createNeuron(self, *args, **keywordArgs):
        """
        Create a new neuron.

        >>> neuron = network.createNeuron(name = 'AVAL')

        Returns the :class:`neuron <Network.Neuron.Neuron>` that is created.
        """

        neuron = Neuron(self, *args, **keywordArgs)
        self.addObject(neuron)
        return neuron

    def findNeuron(self, name = None):
        """
        Find the first neuron with the given name.

        >>> neuron = network.findNeuron('AVAL')

        Returns a :class:`neuron <Network.Neuron.Neuron>` or None if there are no neurons with the name.
        """

        return self.findObject(Neuron, name)

    def neurons(self):
        """
        Return a list of all :class:`neurons <Network.Neuron.Neuron>` in the network.

        >>> for neuron in network.neurons():
        ...     neuron.setHasFunction(Neuron.Function.SENSORY, False)

        An empty list will be returned if there are no neurons in the network.
        """

        return self.objectsOfClass(Neuron)

    def neurites(self):
        """
        Return a list of all :class:`neurites <Network.Neurite.Neurite>` in the network.

        >>> for neurite in network.neurites():
        ...     neurite.setPathway(None)

        An empty list will be returned if there are no neurites in the network.
        """

        return self.objectsOfClass(Neurite)

    def arborizations(self):
        """
        Return a list of all :class:`arborizations <Network.Arborization.Arborization>` in the network.

        >>> for arborization in network.arborizations():
        ...     display.setVisibleShape(arborization, shapes['Cone'])

        An empty list will be returned if there are no arborizations in the network.
        """

        return self.objectsOfClass(Arborization)

    def gapJunctions(self):
        """
        Return a list of all :class:`gap junctions <Network.GapJunction.GapJunction>` in the network.

        >>> for gapJunction in network.gapJunctions():
        ...     display.setVisibleColor(gapJunction, (0, 0, 0))

        An empty list will be returned if there are no gap junctions in the network.
        """

        return self.objectsOfClass(GapJunction)

    def innervations(self):
        """
        Return a list of all :class:`innervations <Network.Innervation.Innervation>` in the network.

        >>> for innervation in network.innervations():
        ...     display.setVisibleWeight(innervation, 2.0)

        An empty list will be returned if there are no innervations in the network.
        """

        return self.objectsOfClass(Innervation)

    def synapses(self):
        """
        Return a list of all :class:`chemical synapses <Network.Synapse.Synapse>` in the network.

        >>> for synapse in network.synapses():
        ...     synapse.activation = None

        An empty list will be returned if there are no chemical synapses in the network.
        """

        return self.objectsOfClass(Synapse)

    def createStimulus(self, *args, **keywordArgs):
        """
        Create a new stimulus.  DEPRECATED: Call :meth:`stimulate() <Network.Object.Object.stimulate>` on the desired target object instead.

        >>> stimulus = network.createStimulus(target = neuron1, modality = library.modality('light'))

        Returns the :class:`stimulus <Network.Stimulus.Stimulus>` that is created.
        """

        target = keywordArgs['target']
        del keywordArgs['target']

        return target.stimulate(*args, **keywordArgs)

    def findStimulus(self, name = None):
        """
        Find the first stimulus with the given name.

        >>> stimulus = network.findStimulus('Light')

        Returns a :class:`stimulus <Network.Stimulus.Stimulus>` or None if there are no stimuli with the name.
        """

        return self.findObject(Stimulus, name)

    def stimuli(self):
        """
        Return a list of all :class:`stimuli <Network.Stimulus.Stimulus>` in the network.

        >>> for stimulus in network.stimuli():
        ...     if stimulus.modality == library.modality('light'):
        ...         display.setVisibleColor(stimulus, (1, 1, 1))

        An empty list will be returned if there are no stimuli in the network.
        """

        return self.objectsOfClass(Stimulus)

    def createMuscle(self, *args, **keywordArgs):
        """
        Create a new muscle.

        >>> muscle = network.createMuscle(name = 'M1')

        Returns the :class:`muscle <Network.Muscle.Muscle>` that is created.
        """

        muscle = Muscle(self, *args, **keywordArgs)
        self.addObject(muscle)
        return muscle

    def findMuscle(self, name = None):
        """
        Find the first muscle with the given name.

        >>> muscle = network.findMuscle('M1')

        Returns a :class:`muscle <Network.Muscle.Muscle>` or None if there are no muscles with the name.
        """

        return self.findObject(Muscle, name)

    def muscles(self):
        """
        Return a list of all :class:`muscles <Network.Muscle.Muscle>` in the network.

        >>> for muscle in network.muscles():
        ...     display.setVisibleOpacity(muscle, 0.5)

        An empty list will be returned if there are no muscles in the network.
        """

        return self.objectsOfClass(Muscle)

    def _updateGraph(self, objectToUpdate = None):
        if objectToUpdate is None:
            # Rebuild the entire graph.
            objectsToUpdate = self.objects
            self.graph.clear()
        else:
            # Just rebuild the connections to the one object.
            objectsToUpdate = [objectToUpdate]
            # Remove the object if it was there before.  This will also delete any edges from the node.
            objectId = objectToUpdate.networkId
            if objectId in self.graph:
                self.graph.remove_node(objectId)

        # Maintain a temporary cache of weights so that rebuilding the whole graph doesn't take so long.
        objectWeights = {}
        def weightOfObject(weightedObject):
            if weightedObject.networkId in objectWeights:
                objectWeight = objectWeights[weightedObject.networkId]
            else:
                objectWeight = self.weightOfObject(weightedObject)
                objectWeights[weightedObject.networkId] = objectWeight
            return objectWeight

        for objectToUpdate in objectsToUpdate:
            objectId = objectToUpdate.networkId

            # (Re-)Add the object to the graph.
            self.graph.add_node(objectId)

            # Get the weight of this object.
            objectWeight = weightOfObject(objectToUpdate)

            # Add the connections to other objects already in the graph.
            # (Each connection to an object not in the graph will be added when that object is added.)
            # The weight of each edge is the average of the weights of the two objects it connects.
            inputIds = set([objectInput.networkId for objectInput in objectToUpdate.inputs(recurse = False)])
            outputIds = set([objectOutput.networkId for objectOutput in objectToUpdate.outputs(recurse = False)])
            unknownIds = set([objectInput.networkId for objectInput in objectToUpdate.connections(recurse = False)]).difference(inputIds).difference(outputIds)
            for inputId in inputIds.union(unknownIds):
                if inputId in self.graph:
                    otherWeight = weightOfObject(objectToUpdate)
                    self.graph.add_edge(inputId, objectId, weight = (objectWeight + otherWeight) / 2.0)
            for outputId in outputIds.union(unknownIds):
                if outputId in self.graph:
                    otherWeight = weightOfObject(objectToUpdate)
                    self.graph.add_edge(objectId, outputId, weight = (objectWeight + otherWeight) / 2.0)

    def _objectChanged(self, sender):
        if not self._bulkLoading:
            self._updateGraph(sender)
            if not self._modified:
                self._modified = True
                dispatcher.send(('set', 'modified'), self)

    def simplifiedGraph(self):
        """
        Return a simplified version of the NetworkX representation of the network.

        This version of the network will have far fewer nodes but will not accurately model edges with more than two end points (hyperedges).  This speeds processing when using NetworkX's algorithms.
        """

        def addEdge(graph, object1, object2, weight):
            node1 = object1.networkId
            node2 = object2.networkId
            if node1 in graph and node2 in graph[node1]:
                if weight < graph[node1][node2]['weight']:
                    # Use a smaller weight for an existing edge.
                    graph[node1][node2]['weight'] = weight
            else:
                # Create a new edge.
                graph.add_edge(node1, node2, weight = weight)

        simplifiedGraph = DiGraph()

        # In self.graph edges are actually nodes to support hyperedges.  Convert these to standard edges in the simplified graph.
        # TODO: make this object type independent
        for arborization in self.arborizations():
            if arborization.sendsOutput:
                addEdge(simplifiedGraph, arborization.neurite.neuron(), arborization.region, self.weightOfObject(arborization))
            if arborization.receivesInput:
                addEdge(simplifiedGraph, arborization.region, arborization.neurite.neuron(), self.weightOfObject(arborization))
        for synapse in self.synapses():
            for postPartner in synapse.postSynapticPartners:
                if isinstance(postPartner, Neurite):
                    postPartner = postPartner.neuron()
                addEdge(simplifiedGraph, synapse.preSynapticNeurite.neuron(), postPartner, self.weightOfObject(synapse))
        for gapJunction in self.gapJunctions():
            neurites = gapJunction.neurites()
            addEdge(simplifiedGraph, neurites[0].neuron(), neurites[1].neuron(), self.weightOfObject(gapJunction))
            addEdge(simplifiedGraph, neurites[1].neuron(), neurites[0].neuron(), self.weightOfObject(gapJunction))
        for innervation in self.innervations():
            addEdge(simplifiedGraph, innervation.neurite.neuron(), innervation.muscle, self.weightOfObject(innervation))
        for pathway in self.pathways():
            region1, region2 = pathway.regions()
            weight = self.weightOfObject(pathway)
            if pathway.region1Projects:
                addEdge(simplifiedGraph, region1, region2, weight)
            if pathway.region2Projects:
                addEdge(simplifiedGraph, region2, region1, weight)
        for stimulus in self.stimuli():
            addEdge(simplifiedGraph, stimulus, stimulus.target.rootObject(), self.weightOfObject(stimulus))

        return simplifiedGraph

    def setModified(self, modified):
        """
        Set whether or not this network is dirty and needs to be saved.
        """

        if self._modified != modified:
            self._modified = modified
            dispatcher.send(('set', 'modified'), self)

    def isModified(self):
        """
        Return whether the network has been modified and needs to be saved.
        """

        return self._modified

    def addObject(self, objectToAdd):
        if objectToAdd.networkId in self.idDict:
            raise ValueError, gettext('All objects in a network must have unique identifiers.')

        self.objects.append(objectToAdd)
        self.idDict[objectToAdd.networkId] = objectToAdd

        if objectToAdd.networkId > self._nextUniqueId:
            self._nextUniqueId = objectToAdd.networkId

        # Update the NetworkX graph representation of the object and its connections.
        if not self._bulkLoading:
            self._updateGraph(objectToAdd)

        # Watch for any changes to the object so we can update our dirty state and the graph.
        dispatcher.connect(self._objectChanged, dispatcher.Any, objectToAdd)

        # Let anyone who cares know that the network was changed.
        if self._bulkLoading:
            self._bulkAddObjects += [objectToAdd]
        else:
            dispatcher.send('addition', self, affectedObjects = [objectToAdd])

    def objectWithId(self, objectId):
        if (isinstance(objectId, str) or isinstance(objectId, unicode)) and objectId.isdigit():
            objectId = int(objectId)

        return self.idDict[objectId] if objectId in self.idDict else None

    def objectsOfClass(self, objectClass):
        objects = []
        for networkObject in self.objects:
            if isinstance(networkObject, objectClass):
                objects.append(networkObject)
        return objects

    def setWeightingFunction(self, weightingFunction = None):
        """
        Set a function to be used to calculate the weight of objects in the network.

        The function should accept a single argument (an :class:`object <network.object.Object>` in the network) and return a floating point value indicating the weight of the object.  An object with a higher weight is considered more expensive to traverse.
        """

        if weightingFunction is not None and not callable(weightingFunction):
            raise ValueError, gettext('The function passed to setWeightingFunction must be callable.')

        if weightingFunction != self._weightingFunction:
            self._weightingFunction = weightingFunction
            self._updateGraph()
            dispatcher.send(('set', 'weightingFunction'), self)

    def weightingFunction(self):
        """
        Return the function being used to calculate the weights of objects in the network.

        If no function has been set then None will be returned.
        """

        return self._weightingFunction

    def weightOfObject(self, weightedObject):
        """
        Return the weight of the indicated object or 1.0 if no weighting function has been set.
        """

        return 1.0 if not self._weightingFunction else self._weightingFunction(weightedObject)

    def shortestPath(self, startObject, endObject):
        """
        Return one of the shortest paths through the :class:`network <Network.Network.Network>` from the first object to the second.

        Returns a list of objects in the path from the first object to the second.  If the second object cannot be reached from the first then an empty list will be returned.
        """

        if not isinstance(startObject, Object) or startObject.network != self or not isinstance(endObject, Object) or endObject.network != self:
            raise ValueError, 'The objects passed to shortestPath() must be from the same network.'

        path = []
        try:
            nodeList = dijkstra_path(self.graph, startObject.networkId, endObject.networkId)
        except:
            nodeList = []
        for nodeID in nodeList:
            pathObject = self.objectWithId(nodeID)
            if pathObject is not startObject:
                path.append(pathObject)

        return path

    def removeObject(self, networkObject):
        """
        Remove the indicated object and any dependent objects from the network and any displays.

        >>> network.removeObject(network.findNeuron('AVAL'))
        """

        if networkObject in self.objects:
            # Determine all of the objects that will need to be removed
            objectsToRemove = set([networkObject])
            objectsToInspect = [networkObject]
            while any(objectsToInspect):
                objectToInspect = objectsToInspect.pop(0)
                dependentObjects = set(objectToInspect.dependentObjects())
                objectsToInspect += list(dependentObjects.difference(objectsToRemove))
                objectsToRemove = objectsToRemove.union(dependentObjects)

            # Remove all of the objects.
            for objectToRemove in objectsToRemove:
                objectToRemove.disconnectFromNetwork()
                self.objects.remove(objectToRemove)
                del self.idDict[objectToRemove.networkId]

                # Keep the NetworkX graph in sync.
                if objectToRemove.networkId in self.graph:
                    self.graph.remove_node(objectToRemove.networkId)

            # Let anyone who cares know that the network was changed.
            dispatcher.send('deletion', self, affectedObjects = objectsToRemove)

    def removeAllObjects(self):
        """
        Remove all objects from the network and any displays.
        """

        removedObjects = list(self.objects)
        for networkObject in self.objects:
            networkObject.network = None
        self.objects = []
        self.idDict = {}
        self.graph.clear()

        # Let anyone who cares know that the network was changed.
        dispatcher.send('deletion', self, affectedObjects = removedObjects)

    def addDisplay(self, display):
        self.displays.append(display)
        dispatcher.connect(self._synchronizeDisplays, ('set', 'selection'), display)

    def removeDisplay(self, display):
        self.displays.remove(display)
        dispatcher.disconnect(self._synchronizeDisplays, ('set', 'selection'), display)

    def setSynchronizeDisplays(self, synchronize):
        if synchronize != self._displaysAreSynchronized:
            self._displaysAreSynchronized = synchronize

            if synchronize and any(self.displays):
                self._synchronizeDisplays(None, self.displays[0])

    def _synchronizeDisplays(self, sender):
        if self._displaysAreSynchronized:
            selection = sender.selectedObjects()
            for display in self.displays:
                if display != sender:
                    display.selectObjects(selection)

    def addAttribute(self, name = None, type = None, value = None): # pylint: disable=W0622
        """
        Add a user-defined attribute to this network.

        >>> network.addAttribute('Preliminary', Attribute.BOOLEAN_TYPE, True)

        The type parameter should be one of the :class:`Attribute.*_TYPE <Network.Attribute.Attribute>` values.

        Returns the attribute object that is created.
        """

        if name is None or type is None or value is None:
            raise ValueError, gettext('The name, type and value parameters must be specified when adding an attribute.')
        if not isinstance(name, str):
            raise TypeError, 'The name parameter passed to addAttribute() must be a string.'
        if type not in Attribute.TYPES:
            raise TypeError, 'The type parameter passed to addAttribute() must be one of the Attribute.*_TYPE values.'
        # TODO: validate value based on the type?

        attribute = Attribute(self, name, type, value)
        self._attributes.append(attribute)
        dispatcher.send(('set', 'attributes'), self)
        return attribute

    def getAttribute(self, name):
        """
        Return the first user-defined :class:`attribute <Network.Attribute.Attribute>` of this network with the given name or None if there is no matching attribute.

        >>> creationDate = network.getAttribute('Creation Date').value()
        """

        for attribute in self._attributes:
            if attribute.name() == name:
                return attribute
        return None

    def getAttributes(self, name = None):
        """
        Return a list of all user-defined :class:`attributes <Network.Attribute.Attribute>` of this network or only those with the given name.

        >>> reviewers = [reviewer.value() for reviewer in network.getAttributes('Reviewed By')]

        If there are no attributes then an empty list will be returned.
        """

        attributes = []
        for attribute in self._attributes:
            if name == None or attribute.name() == name:
                attributes += [attribute]
        return attributes

    def removeAttribute(self, attribute):
        """
        Remove the given attribute from the network.
        """

        if not isinstance(attribute, Attribute) or not attribute in self._attributes:
            raise ValueError, 'The attribute passed to removeAttribute() must be an existing attribute of the network.'

        self._attributes.remove(attribute)
        dispatcher.send(('set', 'attributes'), self)


text:
*[Compare two strings](http://rosettacode.org/wiki/String_comparison) for equality.*

To run:
```
java -cp <path-to-clojure-jar> clojure.main StringComparison.clj <string 1> <string 2>
```


text:
/*jslint vars: false, browser: true, nomen: true */
/*global MOOC:true, _, jQuery, Backbone */

// Copyright 2013 UNED
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

if (_.isUndefined(window.MOOC)) {
    window.MOOC = {};
}

(function ($, Backbone, _) {
    "use strict";

    var cleanView, successHandler, restart;

    MOOC.ajax = {
        hostA: "/course/",
        hostB: "/teacheradmin/stats/",

        getAbsoluteUrl: function (path) {
            return MOOC.ajax.hostA + MOOC.course.get("slug") + MOOC.ajax.hostB + path;
        },

        showLoading: function () {
            $(".loading").removeClass("hide");
        },

        hideLoading: function () {
            $(".loading").addClass("hide");
        },

        showAlert: function (id) {
            var alert = $("#" + id);
            alert.removeClass("hide");
            $("body").animate({ scrollTop: alert.offset().top }, 500);
            if(!alert.hasClass('alert-dismissible')){
                setTimeout(function () {
                    alert.addClass("hide");
                }, MOOC.alertTime);
            }else{
                alert.find('.close').click(function(){
                    alert.addClass("hide");
                });
            }
        }
    };

    MOOC.lastView = null;

    cleanView = function () {
        if (!_.isNull(MOOC.lastView)) {
            MOOC.lastView.destroy();
            MOOC.lastView = null;
        }
    };

    successHandler = function (View, instance) {
        cleanView();
        MOOC.ajax.hideLoading();

        MOOC.lastView = new View({
            model: instance,
            el: MOOC.viewport
        });
        MOOC.lastView.render();
    };

    restart = function () {
        cleanView();
        MOOC.ajax.hideLoading();
        MOOC.ajax.showAlert("generic");
        setTimeout(function () {
            MOOC.router.navigate("", { trigger: true });
        }, 500);
    };

    MOOC.App = Backbone.Router.extend({
        course: function () {
            MOOC.ajax.showLoading();
            MOOC.course.get("units").fetch({
                success: function (units, response, options) {
                    successHandler(MOOC.views.Course, MOOC.course);
                },
                error: function (units, xhr, options) {
                    cleanView();
                    MOOC.ajax.hideLoading();
                    MOOC.ajax.showAlert("generic");
                }
            });
        },

        students: function () {
            MOOC.ajax.showLoading();
            MOOC.students.fetch({
                success: function (units, response, options) {
                    successHandler(MOOC.views.Students, MOOC.students);
                },
                error: function (units, xhr, options) {
                    cleanView();
                    MOOC.ajax.hideLoading();
                    MOOC.ajax.showAlert("generic");
                }
            });
        },

        teachers: function () {
            MOOC.ajax.showLoading();
            MOOC.teachers.fetch({
                success: function (units, response, options) {
                    successHandler(MOOC.views.Teachers, MOOC.teachers);
                },
                error: function (units, xhr, options) {
                    cleanView();
                    MOOC.ajax.hideLoading();
                    MOOC.ajax.showAlert("generic");
                }
            });
        },

        unit: function (unit) {
            MOOC.ajax.showLoading();
            var callback = function () {
                var unitObj = MOOC.course.getUnitByID(unit);
                if (_.isUndefined(unitObj)) {
                    restart();
                } else {
                    unitObj.get("kqs").fetch({
                        success: function (kqs, response, options) {
                            successHandler(MOOC.views.Unit, unitObj);
                        },
                        error: function (kqs, xhr, options) {
                            cleanView();
                            MOOC.ajax.hideLoading();
                            MOOC.ajax.showAlert("generic");
                        }
                    });
                }
            };

            if (MOOC.course.get("units").length > 0) {
                callback();
            } else {
                MOOC.course.get("units").fetch({
                    success: function (units, response, options) {
                        callback();
                    },
                    error: function (kqs, xhr, options) {
                        restart();
                    }
                });
            }
        },

        kq: function (unit, kq) {
            MOOC.ajax.showLoading();
            var callback = function () {
                    var kqObj = MOOC.course.getKQByID(unit, kq);
                    if (_.isUndefined(kqObj)) {
                        restart();
                    } else {
                        successHandler(MOOC.views.KnowledgeQuantum, kqObj);
                    }
                },
                kqObj = MOOC.course.getKQByID(unit, kq),
                unitObj,
                unitCB;

            if (_.isUndefined(kqObj)) {
                unitObj = MOOC.course.getUnitByID(unit);
                unitCB = function () {
                    var unitObj = MOOC.course.getUnitByID(unit);
                    unitObj.get("kqs").fetch({
                        success: function (kqs, response, options) {
                            callback();
                        },
                        error: function (kqs, xhr, options) {
                            restart();
                        }
                    });
                };

                if (_.isUndefined(unitObj)) {
                    MOOC.course.get("units").fetch({
                        success: function (units, response, options) {
                            unitCB();
                        },
                        error: function (units, xhr, options) {
                            restart();
                        }
                    });
                } else {
                    unitCB();
                }
            } else {
                callback();
            }
        }
    });

    MOOC.init = function (courseSlug, initialData) {
        var path = window.location.pathname;
        MOOC.alertTime = 4000;
        initialData.slug = courseSlug;
        MOOC.course = new MOOC.models.Course(initialData);
        MOOC.students = new MOOC.models.Students(initialData);
        MOOC.teachers = new MOOC.models.Teachers(initialData);
        MOOC.viewport = $("#viewport")[0];

        MOOC.router = new MOOC.App();
        MOOC.router.route("", "course");
        MOOC.router.route("course", "course");
        MOOC.router.route("students", "students");
        MOOC.router.route("teachers", "teachers");
        MOOC.router.route("unit:unit", "unit");
        MOOC.router.route("unit:unit/kq:kq", "kq");

        if (path.lastIndexOf('/') < path.length - 1) {
            path += '/';
        }
        Backbone.history.start({ root: path });

        if (window.location.hash.length > 1) {
            path = window.location.hash.substring(1); // Remove #
            MOOC.router.navigate(path, { trigger: true });
        } else {
            MOOC.router.navigate("", { trigger: true });
        }
    };
}(jQuery, Backbone, _));


text:
package com.palantir.atlasdb.keyvalue.dbkvs;

import com.google.common.base.Preconditions;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.spi.AtlasDbFactory;
import com.palantir.atlasdb.spi.KeyValueServiceConfig;
import com.palantir.timestamp.TimestampService;

public class DbAtlasDbFactory implements AtlasDbFactory {
    @Override
    public String getType() {
        return "db";
    }

    @Override
    public KeyValueService createRawKeyValueService(KeyValueServiceConfig config) {
        Preconditions.checkArgument(config instanceof DbKeyValueServiceConfiguration,
                "DbAtlasDbFactory expects a configuration of type DbKeyValueServiceConfiguration, found %s", config.getClass());
        throw new UnsupportedOperationException("Cannot instantiate a relational key value service.");
    }

    @Override
    public TimestampService createTimestampService(KeyValueService rawKvs) {
        throw new UnsupportedOperationException("Cannot instantiate a TimestampService from a relational key value service.");
    }
}


text:
import distance from '@turf/distance';
import intersect from '@turf/intersect';
import { getType } from '@turf/invariant';
import {
    polygon, featureCollection, isObject, isNumber,
    Units, BBox, Feature, Polygon, MultiPolygon, FeatureCollection, Properties
} from '@turf/helpers';

/**
 * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid.
 *
 * @name triangleGrid
 * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
 * @param {number} cellSide dimension of each cell
 * @param {Object} [options={}] Optional parameters
 * @param {string} [options.units='kilometers'] used in calculating cellSide, can be degrees, radians, miles, or kilometers
 * @param {Feature<Polygon>} [options.mask] if passed a Polygon or MultiPolygon, the grid Points will be created only inside it
 * @param {Object} [options.properties={}] passed to each point of the grid
 * @returns {FeatureCollection<Polygon>} grid of polygons
 * @example
 * var bbox = [-95, 30 ,-85, 40];
 * var cellSide = 50;
 * var options = {units: 'miles'};
 *
 * var triangleGrid = turf.triangleGrid(bbox, cellSide, options);
 *
 * //addToMap
 * var addToMap = [triangleGrid];
 */
function triangleGrid<P = Properties>(bbox: BBox, cellSide: number, options: {
    units?: Units,
    properties?: P,
    mask?: Feature<Polygon> | Polygon
} = {}): FeatureCollection<Polygon, P> {
    // Containers
    var results = [];

    // Input Validation is being handled by Typescript

    // if (cellSide === null || cellSide === undefined) throw new Error('cellSide is required');
    // if (!isNumber(cellSide)) throw new Error('cellSide is invalid');
    // if (!bbox) throw new Error('bbox is required');
    // if (!Array.isArray(bbox)) throw new Error('bbox must be array');
    // if (bbox.length !== 4) throw new Error('bbox must contain 4 numbers');
    // if (mask && ['Polygon', 'MultiPolygon'].indexOf(getType(mask)) === -1) throw new Error('options.mask must be a (Multi)Polygon');

    // Main
    var xFraction = cellSide / (distance([bbox[0], bbox[1]], [bbox[2], bbox[1]], options));
    var cellWidth = xFraction * (bbox[2] - bbox[0]);
    var yFraction = cellSide / (distance([bbox[0], bbox[1]], [bbox[0], bbox[3]], options));
    var cellHeight = yFraction * (bbox[3] - bbox[1]);

    var xi = 0;
    var currentX = bbox[0];
    while (currentX <= bbox[2]) {
        var yi = 0;
        var currentY = bbox[1];
        while (currentY <= bbox[3]) {
            var cellTriangle1 = null;
            var cellTriangle2 = null;

            if (xi % 2 === 0 && yi % 2 === 0) {
                cellTriangle1 = polygon([[
                    [currentX, currentY],
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY]
                ]], options.properties);
                cellTriangle2 = polygon([[
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY + cellHeight]
                ]], options.properties);
            } else if (xi % 2 === 0 && yi % 2 === 1) {
                cellTriangle1 = polygon([[
                    [currentX, currentY],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY]
                ]], options.properties);
                cellTriangle2 = polygon([[
                    [currentX, currentY],
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX, currentY]
                ]], options.properties);
            } else if (yi % 2 === 0 && xi % 2 === 1) {
                cellTriangle1 = polygon([[
                    [currentX, currentY],
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX, currentY]
                ]], options.properties);
                cellTriangle2 = polygon([[
                    [currentX, currentY],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY]
                ]], options.properties);
            } else if (yi % 2 === 1 && xi % 2 === 1) {
                cellTriangle1 = polygon([[
                    [currentX, currentY],
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY]
                ]], options.properties);
                cellTriangle2 = polygon([[
                    [currentX, currentY + cellHeight],
                    [currentX + cellWidth, currentY + cellHeight],
                    [currentX + cellWidth, currentY],
                    [currentX, currentY + cellHeight]
                ]], options.properties);
            }
            if (options.mask) {
                if (intersect(options.mask, cellTriangle1)) results.push(cellTriangle1);
                if (intersect(options.mask, cellTriangle2)) results.push(cellTriangle2);
            } else {
                results.push(cellTriangle1);
                results.push(cellTriangle2);
            }

            currentY += cellHeight;
            yi++;
        }
        xi++;
        currentX += cellWidth;
    }
    return featureCollection(results);
}

export default triangleGrid;


text:
package io.reflectoring.coderadar.dependencymap;

import io.reflectoring.coderadar.dependencymap.analyzers.JavaAnalyzer;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class JavaAnalyzerTest {

  private final String fileContent =
      "package org.wickedsource.dependencytree.example;\n"
          + "\n"
          + "//These imports shouldn't matter to the DependencyTree\n"
          + "import java.util.Objects;\n"
          + // valid
          "import java.io.BufferedReader;\n"
          + // valid
          "import org.junit.jupiter.api.*;\n"
          + // valid
          "import org.junit.jupiter.api.*;\n"
          + // valid but ignored
          "import org.wickedsource.dependencytree.sbdfjksbdf; import org.wickedsource.dependencytree.fhzgkobd;\n"
          + // valid x2
          "import org.wickedsource/dependencytree.sbdfjksbdf;\n"
          + // invalid
          "import org.wickedsource.3dependencytree.sbdfjksbdf;\n"
          + // invalid
          "//import org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest1;\n"
          + // invalid
          "/*import org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest2;\n"
          + // invalid
          "*import org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest3;\n"
          + // invalid
          "\"import org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest4;\"\n"
          + // invalid
          "import org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest5;\n"
          + // valid
          "import org.wickedsource.dependencytree.example.wildcardpackage.*;\n"
          + // valid
          "\n"
          + "\n"
          + "//Test code for dependencyTree\n"
          + "public class CoreTest<Typ1, Typ2> extends ClassA implements InterfaceB, interfaceC {\n"
          + // valid x6
          "    @Annotation1 RandomClass3 randomClass3;\n"
          + // valid x2
          "    private RandomClass2 randomClass2; RandomClass randomClass;\n"
          + // valid x2
          "\n"
          + "    org.wickedsource.dependencytree.example.somepackage.FullyClassifiedDependencyTest fullyClassifiedDependencyTest;\n"
          + // valid
          "\n"
          + "    public CoreTest() {\n"
          + // valid
          "        ClassB b = new ClassC();\n"
          + // valid x2
          "        ClassD b = ClassE.create();\n"
          + // valid x2
          "        ClassF b = ClassF1.create(ClassG.create(), classH.create());\n"
          + // valid x4
          "        ClassI b = new ClassJ(ClassK.create(), classL.create());\n"
          + // valid x4
          "        ClassM b = (ClassN) ClassO.create();\n"
          + // valid x3
          "        ClassP b = ((ClassQ.isEmpty() && classR.isEmpty()) || classS.isEmpty || ((classT.size > classU.size) && classV.size < classW.size)) ? ClassX.get : classY.get;\n"
          + // valid x10
          "        ClassZ.doSomething();\n"
          + // valid
          "        try {} catch (ExceptionA | ExceptionB b) {}\n"
          + // valid x2
          "    }\n"
          + "    @Annotation2 @Annotation3\n"
          + // valid x2
          "    public void test() throws ExceptionC {\n"
          + // valid
          "        throw new ExceptionD;\n"
          + // valid
          "    }\n"
          + "\n"
          + "}";

  private JavaAnalyzer analyzer;

  @BeforeEach
  public void setUp() {
    this.analyzer = new JavaAnalyzer();
  }

  /**
   * imports: 7 classDefinition: 5 attributes: 5 constructor: 29 test()-method: 4
   *
   * <p>missing: RandomClass3, Annotation2, Annotation3
   */
  @Test
  void testGetValidImports() {
    List<String> imports = analyzer.getValidImports(fileContent);
    Assertions.assertEquals(50, imports.size());
    Assertions.assertEquals("java.util.Objects", imports.get(0));
    Assertions.assertEquals("java.io.BufferedReader", imports.get(1));
    Assertions.assertEquals("org.junit.jupiter.api.*", imports.get(2));
    Assertions.assertEquals("org.wickedsource.dependencytree.sbdfjksbdf", imports.get(3));
    Assertions.assertEquals("org.wickedsource.dependencytree.fhzgkobd", imports.get(4));
    Assertions.assertEquals(
        "org.wickedsource.dependencytree.example.somepackage.CoreDependencyTest5", imports.get(5));
    Assertions.assertEquals(
        "org.wickedsource.dependencytree.example.wildcardpackage.*", imports.get(6));
    Assertions.assertEquals("Typ1", imports.get(7));
    Assertions.assertEquals("Typ2", imports.get(8));
    Assertions.assertEquals("ClassA", imports.get(9));
    Assertions.assertEquals("InterfaceB", imports.get(10));
    Assertions.assertEquals("interfaceC", imports.get(11));
    Assertions.assertEquals("Annotation1", imports.get(12));
    Assertions.assertEquals("RandomClass3", imports.get(13));
    Assertions.assertEquals("RandomClass2", imports.get(14));
    Assertions.assertEquals("RandomClass", imports.get(15));
    Assertions.assertEquals(
        "org.wickedsource.dependencytree.example.somepackage.FullyClassifiedDependencyTest",
        imports.get(16));
    Assertions.assertEquals("CoreTest", imports.get(17));
    Assertions.assertEquals("ClassB", imports.get(18));
    Assertions.assertEquals("ClassC", imports.get(19));
    Assertions.assertEquals("ClassD", imports.get(20));
    Assertions.assertEquals("ClassE.create", imports.get(21));
    Assertions.assertEquals("ClassF", imports.get(22));
    Assertions.assertEquals("ClassF1.create", imports.get(23));
    Assertions.assertEquals("ClassG.create", imports.get(24));
    Assertions.assertEquals("classH.create", imports.get(25));
    Assertions.assertEquals("ClassI", imports.get(26));
    Assertions.assertEquals("ClassJ", imports.get(27));
    Assertions.assertEquals("ClassK.create", imports.get(28));
    Assertions.assertEquals("classL.create", imports.get(29));
    Assertions.assertEquals("ClassM", imports.get(30));
    Assertions.assertEquals("ClassN", imports.get(31));
    Assertions.assertEquals("ClassO.create", imports.get(32));
    Assertions.assertEquals("ClassP", imports.get(33));
    Assertions.assertEquals("ClassQ.isEmpty", imports.get(34));
    Assertions.assertEquals("classR.isEmpty", imports.get(35));
    Assertions.assertEquals("classS.isEmpty", imports.get(36));
    Assertions.assertEquals("classT.size", imports.get(37));
    Assertions.assertEquals("classU.size", imports.get(38));
    Assertions.assertEquals("classV.size", imports.get(39));
    Assertions.assertEquals("classW.size", imports.get(40));
    Assertions.assertEquals("ClassX.get", imports.get(41));
    Assertions.assertEquals("classY.get", imports.get(42));
    Assertions.assertEquals("ClassZ.doSomething", imports.get(43));
    Assertions.assertEquals("ExceptionA", imports.get(44));
    Assertions.assertEquals("ExceptionB", imports.get(45));
    Assertions.assertEquals("Annotation2", imports.get(46));
    Assertions.assertEquals("Annotation3", imports.get(47));
    Assertions.assertEquals("ExceptionC", imports.get(48));
    Assertions.assertEquals("ExceptionD", imports.get(49));
  }

  @Test
  void testGetFirstSeparator() {
    String test = "= ((ClassQ.isEmpty() && classR.isEmpty())";
    // should return first '(' after ClassQ.isEmpty, because there is no potential import between
    // begin and all separators before that '('
    Assertions.assertEquals(19, test.indexOf(analyzer.getFirstSeparator(test)));
  }

  @Test
  void testDependencyStrings() {
    String line =
        "import org.wickedsource.dependencytree.sbdfjksbdf; import org.wickedsource.dependencytree.fhzgkobd;";
    // should return first '(' after ClassQ.isEmpty, because there is no potential import between
    // begin and all separators before that '('
    List<String> imports = analyzer.getDependenciesFromImportLine(line);
    Assertions.assertEquals(2, imports.size());
    Assertions.assertEquals("org.wickedsource.dependencytree.sbdfjksbdf", imports.get(0));
    Assertions.assertEquals("org.wickedsource.dependencytree.fhzgkobd", imports.get(1));
  }

  @Test
  void testImportDependencyStrings() {
    String line =
        "ClassP b = ((ClassQ.isEmpty() && classR.isEmpty()) || classS.isEmpty || ((classT.size > classU.size) && classV.size < classW.size)) ? ClassX.get : classY.get;";
    // should return first '(' after ClassQ.isEmpty, because there is no potential import between
    // begin and all separators before that '('
    List<String> imports = analyzer.getDependenciesFromLine(line);
    Assertions.assertEquals(10, imports.size());
    Assertions.assertEquals("ClassP", imports.get(0));
    Assertions.assertEquals("ClassQ.isEmpty", imports.get(1));
    Assertions.assertEquals("classR.isEmpty", imports.get(2));
    Assertions.assertEquals("classS.isEmpty", imports.get(3));
    Assertions.assertEquals("classT.size", imports.get(4));
    Assertions.assertEquals("classU.size", imports.get(5));
    Assertions.assertEquals("classV.size", imports.get(6));
    Assertions.assertEquals("classW.size", imports.get(7));
    Assertions.assertEquals("ClassX.get", imports.get(8));
    Assertions.assertEquals("classY.get", imports.get(9));
  }
}


text:
require 'rspec'
require 'cantango-config'
require 'active_record'

require 'cutter'
require 'yaml'
require 'logger'
require 'database_cleaner'

require 'factory_girl'
FactoryGirl.find_definitions

# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

DatabaseCleaner.strategy = :truncation

RSpec.configure do |config|
end

def connect_db
  path = File.dirname(__FILE__) + '/db/database.yml'
  dbfile = File.open(path)
  dbconfig = YAML::load(dbfile)
  ActiveRecord::Base.establish_connection(dbconfig)
  ActiveRecord::Base.logger = Logger.new(STDERR)
  DatabaseCleaner.clean
end

def migrate
  folder = File.join(File.dirname(__FILE__), 'migrations')
  puts "Migrate: #{folder}"
  ActiveRecord::Migrator.migrate folder
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.OSM.OSMClassExtension;

namespace ESRI.ArcGIS.OSM.GeoProcessing
{
    public class NetworkTurns
    {
        private string _turnClassName;
        private IDataset _osmDataset;
        private INetworkDataset _networkDataset;

        private string _dsPath;

        public IFeatureClass OsmPointFeatureClass { get; set; }
        public List<IFeatureClass> OsmEdgeFeatureClasses { get; set; }
        public int OsmExtVersion { get; set; }
        public RunTaskManager TaskManager { get; set; }

        public NetworkTurns(string turnClassName, IDataset osmDataset, INetworkDataset nds)
        {
            _turnClassName = turnClassName;
            _osmDataset = osmDataset;
            _networkDataset = nds;

            IGPUtilities gpUtil = new GPUtilitiesClass();
            IDataElement de = gpUtil.MakeDataElementFromNameObject(osmDataset.FullName);
            _dsPath = de.CatalogPath;
        }

        /// Adds turn restriction feature class to network dataset
        public INetworkSource ExtractTurnRestrictions()
        {
            CreateNetworkTurnFeatureClass();
            TaskManager.ExecuteTask("GPTools_OSMGPCreateNetworkDataset_populatingTurns", PopulateTurnsFromRelations);

            // Create a TurnFeatureSource object and point it to the new turns feature class.
            INetworkSource turnNetworkSource = new TurnFeatureSourceClass();
            turnNetworkSource.Name = _turnClassName;
            turnNetworkSource.ElementType = esriNetworkElementType.esriNETTurn;

            return turnNetworkSource;
        }

        private void CreateNetworkTurnFeatureClass()
        {
            IVariantArray paramArray = new VarArrayClass();
            paramArray.Add(_dsPath);
            paramArray.Add(_turnClassName);
            paramArray.Add(2);

            TaskManager.ExecuteTool("CreateTurnFeatureClass_na", paramArray);

            paramArray.RemoveAll();
            paramArray.Add(_dsPath + "\\" + _turnClassName);
            paramArray.Add("RestrictionType");
            paramArray.Add("TEXT");
            paramArray.Add("");
            paramArray.Add("");
            paramArray.Add(30);
            paramArray.Add("");
            paramArray.Add("NULLABLE");

            TaskManager.ExecuteTool("AddField_management", paramArray);
        }

        private void PopulateTurnsFromRelations()
        {
            IFeatureWorkspace fws = (IFeatureWorkspace)_osmDataset.Workspace;

            TurnFeatureClassWrapper fcTurn = new TurnFeatureClassWrapper();
            fcTurn.OpenTurnFeatureClass(fws, _turnClassName);

            // Add NDS Turn features to the turn feature class
            foreach (OSMTurnInfo osmTurn in EnumerateOsmTurnRestrictions(fws))
            {
                TaskManager.CheckCancel();

                if (osmTurn.TurnType.StartsWith("NO", StringComparison.CurrentCultureIgnoreCase))
                    CreateTurnFeature_NO(fcTurn, osmTurn);
                else if (osmTurn.TurnType.StartsWith("ONLY", StringComparison.CurrentCultureIgnoreCase))
                    CreateTurnFeature_ONLY(fcTurn, osmTurn);
            }
        }

        private IEnumerable<OSMTurnInfo> EnumerateOsmTurnRestrictions(IFeatureWorkspace fws)
        {
            OSMUtility osmUtility = new OSMUtility();
            ITable tableRelation = fws.OpenTable(_osmDataset.Name + "_osm_relation");
            try
            {
                TaskManager.StartProgress(tableRelation.RowCount(null));

                using (ComReleaser cr = new ComReleaser())
                {
                    ICursor cursor = tableRelation.Search(null, false);
                    cr.ManageLifetime(cursor);

                    int idxTags = cursor.FindField("osmTags");
                    int idxMembers = cursor.FindField("osmMembers");

                    IRow row = null;
                    while ((row = cursor.NextRow()) != null)
                    {
                        tag[] tags = osmUtility.retrieveOSMTags(row, idxTags, _osmDataset.Workspace);
                        var tagsRestriction = tags.Where(t => t.k.Equals("restriction", StringComparison.CurrentCultureIgnoreCase));

                        foreach (tag tagRestrict in tagsRestriction)
                        {
                            OSMTurnInfo turn = new OSMTurnInfo();

                            turn.TurnType = tagRestrict.v;

                            foreach (member m in osmUtility.retrieveMembers(row, idxMembers))
                            {
                                if (m.role.Equals("from", StringComparison.CurrentCultureIgnoreCase))
                                    turn.From = m;
                                else if (m.role.Equals("to", StringComparison.CurrentCultureIgnoreCase))
                                    turn.To = m;
                                else if (m.role.Equals("via", StringComparison.CurrentCultureIgnoreCase))
                                    turn.Via = m;
                            }

                            if (turn.HasValidMembers())
                            {
                                turn.FromFeature = FindEdgeFeature(turn.From.@ref);
                                turn.ToFeature = FindEdgeFeature(turn.To.@ref);
                                turn.ViaFeature = FindJunctionFeature(turn.Via.@ref);

                                if (turn.HasValidFeatures())
                                    yield return turn;
                            }
                        }

                        TaskManager.StepProgress();
                    }
                }
            }
            finally
            {
                TaskManager.EndProgress();
            }
        }

        private IFeature FindEdgeFeature(string osmid)
        {
            List<IFeatureClass> fcEdges = OsmEdgeFeatureClasses;

            foreach (IFeatureClass fcEdge in fcEdges)
            {
                IQueryFilter filter = new QueryFilterClass();
                filter.SubFields = string.Join(",", new string[] { fcEdge.OIDFieldName, fcEdge.ShapeFieldName, "OSMID" });
                filter.WhereClause = fcEdge.WhereClauseByExtensionVersion(osmid, "OSMID", OsmExtVersion);

                using (ComReleaser cr = new ComReleaser())
                {
                    IFeatureCursor cursor = fcEdge.Search(filter, false);
                    cr.ManageLifetime(cursor);

                    IFeature feature = cursor.NextFeature();
                    if (feature != null)
                        return feature;
                }
            }

            return null;
        }

        private IFeature FindJunctionFeature(string osmid)
        {
            IFeatureClass fcPoint = OsmPointFeatureClass;

            IQueryFilter filter = new QueryFilterClass();
            filter.SubFields = string.Join(",", new string[] { fcPoint.OIDFieldName, fcPoint.ShapeFieldName, "OSMID" });
            filter.WhereClause = fcPoint.WhereClauseByExtensionVersion(osmid, "OSMID", OsmExtVersion);

            using (ComReleaser cr = new ComReleaser())
            {
                IFeatureCursor cursor = fcPoint.Search(filter, false);
                cr.ManageLifetime(cursor);

                IFeature feature = cursor.NextFeature();
                if (feature != null)
                    return feature;
            }

            return null;
        }

        private void CreateTurnFeature_NO(TurnFeatureClassWrapper turnFCW, OSMTurnInfo osmTurn)
        {
            IFeature turn = turnFCW.TurnFeatureClass.CreateFeature();

            IPoint ptVia = osmTurn.ViaFeature.Shape as IPoint;
            IPolyline lineFrom = osmTurn.FromFeature.Shape as IPolyline;
            IPolyline lineTo = osmTurn.ToFeature.Shape as IPolyline;

            // Create Turn Shape
            bool edge1End, edge2End;
            double posFrom, posTo;
            IPoint ptStart = GetTurnEndpoint(lineFrom, ptVia, out edge1End, out posFrom);
            IPoint ptEnd = GetTurnEndpoint(lineTo, ptVia, out edge2End, out posTo);
            turn.Shape = CreateTurnGeometry(ptStart, ptVia, ptEnd, lineFrom.SpatialReference);

            // Attributes (Edge1)
            turn.set_Value(turnFCW.idxEdge1End, (edge1End) ? "Y" : "N");
            turn.set_Value(turnFCW.idxEdge1FCID, osmTurn.FromFeature.Class.ObjectClassID);
            turn.set_Value(turnFCW.idxEdge1FID, osmTurn.FromFeature.OID);
            turn.set_Value(turnFCW.idxEdge1Pos, posFrom);

            // Attributes (Edge2)
            turn.set_Value(turnFCW.idxEdge2FCID, osmTurn.ToFeature.Class.ObjectClassID);
            turn.set_Value(turnFCW.idxEdge2FID, osmTurn.ToFeature.OID);
            turn.set_Value(turnFCW.idxEdge2Pos, posTo);

            // Restriction Type
            turn.set_Value(turnFCW.idxRestrict, osmTurn.TurnType);

            turn.Store();
        }

        private void CreateTurnFeature_ONLY(TurnFeatureClassWrapper turnFCW, OSMTurnInfo osmTurn)
        {
            IPoint ptVia = osmTurn.ViaFeature.Shape as IPoint;
            IPolyline lineFrom = osmTurn.FromFeature.Shape as IPolyline;

            bool edge1End, edge2End;
            double posFrom, posTo;
            IPoint ptStart = GetTurnEndpoint(lineFrom, ptVia, out edge1End, out posFrom);

            foreach (INetworkEdge edge in EnumerateAdjacentTurnEdges(osmTurn, edge1End))
            {
                IFeature turn = turnFCW.TurnFeatureClass.CreateFeature();

                INetworkSource srcTo = _networkDataset.get_SourceByID(edge.SourceID);
                IFeatureClass fcTo = ((IFeatureClassContainer)_networkDataset).get_ClassByName(srcTo.Name);
                IFeature featureTo = fcTo.GetFeature(edge.OID);
                IPolyline lineTo = featureTo.Shape as IPolyline;

                // Create Turn Shape
                IPoint ptEnd = GetTurnEndpoint(lineTo, ptVia, out edge2End, out posTo);
                turn.Shape = CreateTurnGeometry(ptStart, ptVia, ptEnd, lineFrom.SpatialReference);

                // Attributes (Edge1)
                turn.set_Value(turnFCW.idxEdge1End, (edge1End) ? "Y" : "N");
                turn.set_Value(turnFCW.idxEdge1FCID, osmTurn.FromFeature.Class.ObjectClassID);
                turn.set_Value(turnFCW.idxEdge1FID, osmTurn.FromFeature.OID);
                turn.set_Value(turnFCW.idxEdge1Pos, posFrom);

                // Attributes (Edge2)
                turn.set_Value(turnFCW.idxEdge2FCID, featureTo.Class.ObjectClassID);
                turn.set_Value(turnFCW.idxEdge2FID, featureTo.OID);
                turn.set_Value(turnFCW.idxEdge2Pos, posTo);

                // Restriction Type
                turn.set_Value(turnFCW.idxRestrict, "NO");

                turn.Store();
            }
        }

        /// Gets the end point of a turn edge
        /// <remarks>
        /// - The Via node of a turn is assumed to be at the From or To point of the edge
        /// </remarks>
        private static IPoint GetTurnEndpoint(IPolyline line, IPoint ptVia, out bool edgeEndAtToPoint, out double position)
        {
            IPoint point = null;

            edgeEndAtToPoint = false;
            position = 0.0;

            if ((ptVia.X == line.FromPoint.X) && (ptVia.Y == line.FromPoint.Y))
            {
                point = ((IPointCollection)line).get_Point(1);
                ISegment segment = ((ISegmentCollection)line).get_Segment(0);
                position = segment.Length / line.Length;
            }
            else
            {
                edgeEndAtToPoint = true;

                IPointCollection pc = (IPointCollection)line;
                point = pc.get_Point(pc.PointCount - 2);

                ISegmentCollection sc = line as ISegmentCollection;
                ISegment segment = sc.get_Segment(sc.SegmentCount - 1);

                position = (line.Length - segment.Length) / line.Length;
            }

            return point;
        }

        private static IGeometry CreateTurnGeometry(IPoint ptStart, IPoint ptVia, IPoint ptEnd, ISpatialReference sr)
        {
            IPolyline lineTurn = new PolylineClass();
            lineTurn.SpatialReference = sr;

            IPointCollection pcTurn = lineTurn as IPointCollection;
            pcTurn.AddPoint(ptStart);
            pcTurn.AddPoint(ptVia);
            pcTurn.AddPoint(ptEnd);

            return (IGeometry)lineTurn;
        }

        private IEnumerable<INetworkEdge> EnumerateAdjacentTurnEdges(OSMTurnInfo osmTurn, bool useToJunction)
        {
            INetworkQuery query = (INetworkQuery)_networkDataset;

            // get turn FROM-edge
            INetworkSource source = _networkDataset.get_SourceByName(((IDataset)osmTurn.FromFeature.Class).Name);
            IEnumNetworkElement enumNetElements = null;

            IRelationalOperator relationalOperator = ((IPolyline)osmTurn.ToFeature.Shape).FromPoint as IRelationalOperator;

            bool useFromPointOfToFeature = relationalOperator.Contains(osmTurn.ViaFeature.Shape);

            if (useFromPointOfToFeature)
                enumNetElements = query.get_EdgesByPosition(source.ID, osmTurn.ToFeature.OID, 0, false);
            else
                enumNetElements = query.get_EdgesByPosition(source.ID, osmTurn.ToFeature.OID, 1, false);

            INetworkEdge edgeFrom = enumNetElements.Next() as INetworkEdge;

            // get the FROM-edge Junctions
            INetworkJunction fromJunction = query.CreateNetworkElement(esriNetworkElementType.esriNETJunction) as INetworkJunction;
            INetworkJunction toJunction = query.CreateNetworkElement(esriNetworkElementType.esriNETJunction) as INetworkJunction;

            edgeFrom.QueryJunctions(fromJunction, toJunction);

            // Get adjacent edges from the turn center junction
            INetworkJunction junction = ((useFromPointOfToFeature) ? fromJunction : toJunction);

            for (int n = 0; n < junction.EdgeCount; ++n)
            {
                INetworkEdge edge = query.CreateNetworkElement(esriNetworkElementType.esriNETEdge) as INetworkEdge;
                if (useFromPointOfToFeature)
                    junction.QueryEdge(n, true, edge);
                else
                    junction.QueryEdge(n, false, edge);

                //if ((edge.SourceID == osmTurn.FromFeature.OID) || (edge.SourceID == osmTurn.ToFeature.OID))
                if ((edge.OID == osmTurn.ToFeature.OID))
                    continue;

                yield return edge;
            }
        }
    }

    internal class TurnFeatureClassWrapper
    {
        public IFeatureClass TurnFeatureClass { get; set; }

        public int idxEdge1End;
        public int idxEdge1FCID;
        public int idxEdge1FID;
        public int idxEdge1Pos;
        public int idxEdge2FCID;
        public int idxEdge2FID;
        public int idxEdge2Pos;
        public int idxRestrict;

        public TurnFeatureClassWrapper()
        {
        }

        public void OpenTurnFeatureClass(IFeatureWorkspace fws, string turnClassName)
        {
            TurnFeatureClass = fws.OpenFeatureClass(turnClassName);

            idxEdge1End = TurnFeatureClass.FindField("Edge1End");
            idxEdge1FCID = TurnFeatureClass.FindField("Edge1FCID");
            idxEdge1FID = TurnFeatureClass.FindField("Edge1FID");
            idxEdge1Pos = TurnFeatureClass.FindField("Edge1Pos");
            idxEdge2FCID = TurnFeatureClass.FindField("Edge2FCID");
            idxEdge2FID = TurnFeatureClass.FindField("Edge2FID");
            idxEdge2Pos = TurnFeatureClass.FindField("Edge2Pos");
            idxRestrict = TurnFeatureClass.FindField("RestrictionType");
        }
    }

    internal class OSMTurnInfo
    {
        public member From { get; set; }
        public member To { get; set; }
        public member Via { get; set; }

        public IFeature FromFeature { get; set; }
        public IFeature ToFeature { get; set; }
        public IFeature ViaFeature { get; set; }

        public string TurnType { get; set; }

        public OSMTurnInfo()
        {
            From = To = Via = null;
            FromFeature = ToFeature = ViaFeature = null;
        }

        public bool HasValidMembers()
        {
            return (From != null && To != null && Via != null);
        }

        public bool HasValidFeatures()
        {
            return ((FromFeature != null && FromFeature.Shape != null && !FromFeature.Shape.IsEmpty)
                && (ToFeature != null && ToFeature.Shape != null && !ToFeature.Shape.IsEmpty)
                && (ViaFeature != null && ViaFeature.Shape != null && !ViaFeature.Shape.IsEmpty));
        }

        public bool IsValid()
        {
            return (HasValidMembers() && HasValidFeatures());
        }
    }
}


text:
from django.utils.translation import ugettext_lazy as _

from taiga.base.api import ModelCrudViewSet
from taiga.base.api import ModelUpdateRetrieveViewSet
from taiga.base.api.mixins import BlockedByProjectMixin
from taiga.base import exceptions as exc
from taiga.base import filters
from taiga.base import response

from taiga.projects.mixins.ordering import BulkUpdateOrderMixin
from taiga.projects.history.mixins import HistoryResourceMixin
from taiga.projects.notifications.mixins import WatchedResourceMixin
from taiga.projects.occ.mixins import OCCResourceMixin

from . import models
from . import serializers
from . import permissions
from . import services

######################################################
# Custom Attribute ViewSets
#######################################################

class UserStoryCustomAttributeViewSet(BulkUpdateOrderMixin, BlockedByProjectMixin, ModelCrudViewSet):
    model = models.UserStoryCustomAttribute
    serializer_class = serializers.UserStoryCustomAttributeSerializer
    permission_classes = (permissions.UserStoryCustomAttributePermission,)
    filter_backends = (filters.CanViewProjectFilterBackend,)
    filter_fields = ("project",)
    bulk_update_param = "bulk_userstory_custom_attributes"
    bulk_update_perm = "change_userstory_custom_attributes"
    bulk_update_order_action = services.bulk_update_userstory_custom_attribute_order

class TaskCustomAttributeViewSet(BulkUpdateOrderMixin, BlockedByProjectMixin, ModelCrudViewSet):
    model = models.TaskCustomAttribute
    serializer_class = serializers.TaskCustomAttributeSerializer
    permission_classes = (permissions.TaskCustomAttributePermission,)
    filter_backends = (filters.CanViewProjectFilterBackend,)
    filter_fields = ("project",)
    bulk_update_param = "bulk_task_custom_attributes"
    bulk_update_perm = "change_task_custom_attributes"
    bulk_update_order_action = services.bulk_update_task_custom_attribute_order

class IssueCustomAttributeViewSet(BulkUpdateOrderMixin, BlockedByProjectMixin, ModelCrudViewSet):
    model = models.IssueCustomAttribute
    serializer_class = serializers.IssueCustomAttributeSerializer
    permission_classes = (permissions.IssueCustomAttributePermission,)
    filter_backends = (filters.CanViewProjectFilterBackend,)
    filter_fields = ("project",)
    bulk_update_param = "bulk_issue_custom_attributes"
    bulk_update_perm = "change_issue_custom_attributes"
    bulk_update_order_action = services.bulk_update_issue_custom_attribute_order

######################################################
# Custom Attributes Values ViewSets
#######################################################

class BaseCustomAttributesValuesViewSet(OCCResourceMixin, HistoryResourceMixin, WatchedResourceMixin,
                                        BlockedByProjectMixin, ModelUpdateRetrieveViewSet):
    def get_object_for_snapshot(self, obj):
        return getattr(obj, self.content_object)

class UserStoryCustomAttributesValuesViewSet(BaseCustomAttributesValuesViewSet):
    model = models.UserStoryCustomAttributesValues
    serializer_class = serializers.UserStoryCustomAttributesValuesSerializer
    permission_classes = (permissions.UserStoryCustomAttributesValuesPermission,)
    lookup_field = "user_story_id"
    content_object = "user_story"

    def get_queryset(self):
        qs = self.model.objects.all()
        qs = qs.select_related("user_story", "user_story__project")
        return qs

class TaskCustomAttributesValuesViewSet(BaseCustomAttributesValuesViewSet):
    model = models.TaskCustomAttributesValues
    serializer_class = serializers.TaskCustomAttributesValuesSerializer
    permission_classes = (permissions.TaskCustomAttributesValuesPermission,)
    lookup_field = "task_id"
    content_object = "task"

    def get_queryset(self):
        qs = self.model.objects.all()
        qs = qs.select_related("task", "task__project")
        return qs

class IssueCustomAttributesValuesViewSet(BaseCustomAttributesValuesViewSet):
    model = models.IssueCustomAttributesValues
    serializer_class = serializers.IssueCustomAttributesValuesSerializer
    permission_classes = (permissions.IssueCustomAttributesValuesPermission,)
    lookup_field = "issue_id"
    content_object = "issue"

    def get_queryset(self):
        qs = self.model.objects.all()
        qs = qs.select_related("issue", "issue__project")
        return qs


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

namespace Core.Handlers.KeyBoard
{
    /// <summary>
    /// Интерфейс Класса для эмуляции клавиатуры
    /// </summary>
    public interface IKeyBoard
    {
        /// <summary>
        /// Эмулировать нажатие клавишы на клавиатуре
        /// </summary>
        /// <param name="key"></param>
        /// <param name="pressTime"></param>
        void PressKey(KeyName key, UInt32 pressTime = 0);

        /// <summary>
        /// Эмулирует нажатие нескольких клавиш
        /// </summary>
        void PressKeys(List<KeyName> list);

        /// <summary>
        /// Вызвать событие для клавиши
        /// </summary>
        /// <param name="key">Клавиша</param>
        /// <param name="action">Событие</param>
        void InvokeKeyAct(KeyName key, KeyAction action);
    }
}


text:
set -eo pipefail

# install octave 3.6.2 (less needed as frontend)
apt-get update && apt-get install -y octave less

# cleanup package manager
apt-get autoclean && apt-get clean
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# prepare dir
mkdir /source


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.thrift.api;

import io.airlift.drift.annotations.ThriftConstructor;
import io.airlift.drift.annotations.ThriftField;
import io.airlift.drift.annotations.ThriftStruct;
import io.prestosql.spi.connector.SchemaTableName;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;
import static io.prestosql.plugin.thrift.api.NameValidationUtils.checkValidName;

@ThriftStruct
public final class PrestoThriftSchemaTableName
{
    private final String schemaName;
    private final String tableName;

    @ThriftConstructor
    public PrestoThriftSchemaTableName(String schemaName, String tableName)
    {
        this.schemaName = checkValidName(schemaName);
        this.tableName = checkValidName(tableName);
    }

    public PrestoThriftSchemaTableName(SchemaTableName schemaTableName)
    {
        this(schemaTableName.getSchemaName(), schemaTableName.getTableName());
    }

    @ThriftField(1)
    public String getSchemaName()
    {
        return schemaName;
    }

    @ThriftField(2)
    public String getTableName()
    {
        return tableName;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        PrestoThriftSchemaTableName other = (PrestoThriftSchemaTableName) obj;
        return Objects.equals(this.schemaName, other.schemaName) &&
                Objects.equals(this.tableName, other.tableName);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(schemaName, tableName);
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("schemaName", schemaName)
                .add("tableName", tableName)
                .toString();
    }

    public SchemaTableName toSchemaTableName()
    {
        return new SchemaTableName(getSchemaName(), getTableName());
    }
}


text:
.thumbnailImage{

}

.hide-magnifiedImage{
  display:none !important;
}

.magnifiedImage{
  display: block;
}


text:
author: Segment Routing Team
published: true
date: '2016-09-25 22:43 -0700'
title: 'UKNOF 27: Spring Forwarding'
tags:
  - segment-routing
  - cisco
excerpt: SPRING FORWARD(ING). Evolving IP/MPLS networks with Segment Routing
header:
  teaser: images/uknof27-teaser.png
---

## Segment Routing Overview

**ROB SHAKIR, End-to-End Network Architect, BT TSO**
{: .notice--info}

{% capture "pdf1-link" %}https://indico.uknof.org.uk/event/29/material/slides/0?contribId=8{% endcapture %}


text:
using System;
using System.Collections.Generic;
using org.apache.jute;
using org.apache.zookeeper.common;
using org.apache.zookeeper.data;
using org.apache.zookeeper.proto;

namespace org.apache.zookeeper
{
    /// <summary>
    ///     Represents a single operation in a multi-operation transaction.  Each operation can be a create, update
    ///     or delete or can just be a version check.
    ///     Sub-classes of Op each represent each detailed type but should not normally be referenced except via
    ///     the provided factory methods.
    /// </summary>
    public abstract class Op {
        private readonly string path;
        private readonly int type;
        // prevent untyped construction
        private Op(ZooDefs.OpCode type, string path) {
            this.type = (int) type;
            this.path = path;
        }
        /// <summary>
        ///     Constructs a create operation.  Arguments are as for the ZooKeeper method of the same name.
        /// </summary>
        /// <param name="path">
        ///     the path for the node
        /// </param>
        /// <param name="data">
        ///     the initial data for the node
        /// </param>
        /// <param name="acl">
        ///     the acl for the node
        /// </param>
        /// <param name="flags">
        ///     specifying whether the node to be created is ephemeral
        ///     and/or sequential but using the integer encoding.
        /// </param>
        internal static Op create(string path, byte[] data, List<ACL> acl, int flags) {
            return new Create(path, data, acl, flags);
        }

        /// <summary>
        ///     Constructs a create operation.  Arguments are as for the ZooKeeper method of the same name.
        /// </summary>
        /// <param name="path">
        ///     the path for the node
        /// </param>
        /// <param name="data">
        ///     the initial data for the node
        /// </param>
        /// <param name="acl">
        ///     the acl for the node
        /// </param>
        /// <param name="createMode">
        ///     specifying whether the node to be created is ephemeral
        ///     and/or sequential
        /// </param>
        public static Op create(string path, byte[] data, List<ACL> acl, CreateMode createMode) {
            return new Create(path, data, acl, createMode);
        }

        /// <summary>
        ///     Constructs a delete operation.  Arguments are as for the ZooKeeper method of the same name.
        /// </summary>
        /// <param name="path">
        ///     the path of the node to be deleted.
        /// </param>
        /// <param name="version">
        ///     the expected node version.
        /// </param>
        public static Op delete(string path, int version = -1) {
            return new Delete(path, version);
        }

        /// <summary>
        ///     Constructs an update operation.  Arguments are as for the ZooKeeper method of the same name.
        /// </summary>
        /// <param name="path">
        ///     the path of the node
        /// </param>
        /// <param name="data">
        ///     the data to set
        /// </param>
        /// <param name="version">
        ///     the expected matching version
        /// </param>
        public static Op setData(string path, byte[] data, int version = -1) {
            return new SetData(path, data, version);
        }

        /// <summary>
        ///     Constructs an version check operation.  Arguments are as for the ZooKeeper.setData method except that
        ///     no data is provided since no update is intended.  The purpose for this is to allow read-modify-write
        ///     operations that apply to multiple znodes, but where some of the znodes are involved only in the read,
        ///     not the write.  A similar effect could be achieved by writing the same data back, but that leads to
        ///     way more version updates than are necessary and more writing in general.
        /// </summary>
        /// <param name="path">
        ///     the path of the node
        /// </param>
        /// <param name="version">
        ///     the expected matching version
        /// </param>
        public static Op check(string path, int version) {
            return new Check(path, version);
        }

        /**
         * Gets the integer type code for an Op.  This code should be as from ZooDefs.OpCode
         * @see ZooDefs.OpCode
         * @return  The type code.
         */
        public int get_Type() {
            return type;
        }

        /**
         * Gets the path for an Op.
         * @return  The path.
         */
        public string getPath() {
            return path;
        }
        ///     Encodes an op for wire transmission.
        /// <returns> An appropriate Record structure. </returns>
        internal abstract Record toRequestRecord();

        /// <summary>
        ///     Reconstructs the transaction with the chroot prefix.
        /// </summary>
        /// <returns> transaction with chroot. </returns>
        public abstract Op withChroot(string addRootPrefix);

        /// <summary>
        ///     Performs client path validations.
        /// </summary>
        /// <exception cref="ArgumentException">
        ///     if an invalid path is specified
        /// </exception>
        /// <exception cref="KeeperException.BadArgumentsException">
        ///     if an invalid create mode flag is specified
        /// </exception>
        internal virtual void validate() {
            PathUtils.validatePath(path);
        }
        private class Create : Op {
            private readonly List<ACL> acl;
            private readonly byte[] data;
            private readonly int flags;

            internal Create(string path, byte[] data, List<ACL> acl, int flags)
                : base(ZooDefs.OpCode.create, path) {
                this.data = data;
                this.acl = acl;
                this.flags = flags;
            }

            internal Create(string path, byte[] data, List<ACL> acl, CreateMode createMode)
                : base(ZooDefs.OpCode.create, path) {
                this.data = data;
                this.acl = acl;
                flags = createMode.toFlag();
            }

            internal override Record toRequestRecord() {
                return new CreateRequest(getPath(), data, acl, flags);
            }

            public override Op withChroot(string p) {
                return new Create(p, data, acl, flags);
            }

            internal override void validate() {
                CreateMode createMode = CreateMode.fromFlag(flags);
                PathUtils.validatePath(getPath(), createMode.isSequential());
            }
        }

        private class Delete : Op {
            private readonly int version;

            internal Delete(string path, int version) : base(ZooDefs.OpCode.delete, path) {
                this.version = version;
            }

            internal override Record toRequestRecord() {
                return new DeleteRequest(getPath(), version);
            }

            public override Op withChroot(string p) {
                return new Delete(p, version);
            }
        }

        private class SetData : Op {
            private readonly byte[] data;
            private readonly int version;

            internal SetData(string path, byte[] data, int version) : base(ZooDefs.OpCode.setData, path) {
                this.data = data;
                this.version = version;
            }

            internal override Record toRequestRecord() {
                return new SetDataRequest(getPath(), data, version);
            }

            public override Op withChroot(string p) {
                return new SetData(p, data, version);
            }
        }

        private class Check : Op {
            private readonly int version;

            internal Check(string path, int version) : base(ZooDefs.OpCode.check, path) {
                this.version = version;
            }

            internal override Record toRequestRecord() {
                return new CheckVersionRequest(getPath(), version);
            }

            public override Op withChroot(string p) {
                return new Check(p, version);
            }
        }
    }
}


text:
#ifndef UCADATA_H
#define UCADATA_H

#include "unicode/utypes.h"

#if !UCONFIG_NO_COLLATION

#include "ucol_elm.h"
#include <stdio.h>
#include <string.h>
#include "unicode/utypes.h"
#include "unicode/uchar.h"
#include "ucol_imp.h"
#include "uhash.h"
#include "unewdata.h"

void deleteElement(void *element);
int32_t readElement(char **from, char *to, char separator, UErrorCode *status);
uint32_t getSingleCEValue(char *primary, char *secondary, char *tertiary, UBool caseBit, UErrorCode *status);
void printOutTable(UCATableHeader *myData, UErrorCode *status);
UCAElements *readAnElement(FILE *data, tempUCATable *t, UCAConstants *consts, UErrorCode *status);

#endif /* #if !UCONFIG_NO_COLLATION */

#endif