based on https://github.com/apache/avro/pull/82/
968415
def _read_decimal(data, size, writer_schema):
    
    scale = writer_schema.get('scale', 0)
    precision = writer_schema['precision']

    datum_byte = str2ints(data)

    unscaled_datum = 0
    msb = fstint(data)
    leftmost_bit = (msb >> 7) & 1
    if leftmost_bit == 1:
        modified_first_byte = datum_byte[0] ^ (1 << 7)
        datum_byte = [modified_first_byte] + datum_byte[1:]
        for offset in xrange(size):
            unscaled_datum <<= 8
            unscaled_datum += datum_byte[offset]
        unscaled_datum += pow(-2, (size * 8) - 1)
    else:
        for offset in xrange(size):
            unscaled_datum <<= 8
            unscaled_datum += (datum_byte[offset])

    with localcontext() as ctx:
        ctx.prec = precision
        scaled_datum = Decimal(unscaled_datum).scaleb(-scale)
    return scaled_datum
690923
def make_avsc_object(json_data, names=None):
    # type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema
    
    if names is None:
        names = Names()
    assert isinstance(names, Names)

    # JSON object (non-union)
    if hasattr(json_data, 'get') and callable(json_data.get):  # type: ignore
        assert isinstance(json_data, Dict)
        atype = cast(Text, json_data.get('type'))
        other_props = get_other_props(json_data, SCHEMA_RESERVED_PROPS)
        if atype in PRIMITIVE_TYPES:
            return PrimitiveSchema(atype, other_props)
        if atype in NAMED_TYPES:
            name = cast(Text, json_data.get('name'))
            namespace = cast(Text, json_data.get('namespace',
                                                 names.default_namespace))
            if atype == 'enum':
                symbols = cast(List[Text], json_data.get('symbols'))
                doc = json_data.get('doc')
                return EnumSchema(name, namespace, symbols, names, doc, other_props)
            if atype in ['record', 'error']:
                fields = cast(List, json_data.get('fields'))
                doc = json_data.get('doc')
                return RecordSchema(name, namespace, fields, names, atype, doc, other_props)
            raise SchemaParseException('Unknown Named Type: %s' % atype)
        if atype in VALID_TYPES:
            if atype == 'array':
                items = cast(List, json_data.get('items'))
                return ArraySchema(items, names, other_props)
        if atype is None:
            raise SchemaParseException('No "type" property: %s' % json_data)
        raise SchemaParseException('Undefined type: %s' % atype)
    # JSON array (union)
    if isinstance(json_data, list):
        return UnionSchema(json_data, names)
    # JSON string (primitive)
    if json_data in PRIMITIVE_TYPES:
        return PrimitiveSchema(cast(Text, json_data))
    # not for us!
    fail_msg = "Could not make an Avro Schema object from %s." % json_data
    raise SchemaParseException(fail_msg)
1259042
def srpflood(x, promisc=None, filter=None, iface=None, iface_hint=None, nofilter=None, *args, **kargs):  # noqa: E501
    """"""
    if iface is None and iface_hint is not None:
        iface = conf.route.route(iface_hint)[0]
    s = conf.L2socket(promisc=promisc, filter=filter, iface=iface, nofilter=nofilter)  # noqa: E501
    r = sndrcvflood(s, x, *args, **kargs)
    s.close()
    return r
62227
function _from_args (opts, cfg_so_far, cb) {
  var args = parseArgs (opts.input || (process.argv.slice(2))); 
  var ka = [];
  var va = [];

  _.forEach (args, function (v, k) {
    if (k == '_') return;

    // change __ into . in k
    k = k.replace (/__/g, '.');

    if (opts.regexp && !(k.match (opts.regexp))) return;
    if (opts.prefix && !(_.startsWith (k, opts.prefix))) return;

    if (opts.prefix) k = k.substr (opts.prefix.length);

    ka.push (k);
    va.push (v);
  });

  var obj = _.zipObjectDeep(ka, va);
  _expand (obj, cfg_so_far, cb);
}
777146
def complete_vrf(arg):
    

    search_string = ''
    if arg is not None:
        search_string = '^%s' % arg

    res = VRF.search({
        'operator': 'regex_match',
        'val1': 'rt',
        'val2':  search_string
        }, { 'max_result': 100000 } )

    ret = []

    for v in res['result']:
        ret.append(v.rt)
    if re.match(search_string, 'none'):
        ret.append('none')

    return ret
556828
function obj(argv, callback) {
  var uri = argv[2];

  if (argv[3]) {
    util.put(argv[2], '<> <> """' + argv[3] + '""" .', function(err, callback){
      if (err) {
        console.error(err);
      } else {
        console.log('put value : ' + argv[3]);
      }
    });
  } else {
    var wss = 'wss://' + uri.split('/')[2] + '/';

    var s = new ws(wss, {
      origin: 'http://websocket.org'
    });

    s.on('open', function open() {
      s.send('sub ' + uri);
    });

    s.on('close', function close() {
      console.log('disconnected');
    });

    s.on('message', function message(data, flags) {
      var a = data.split(' ');
      if (a.length && a[0] === 'pub') {
        util.getAll(a[1], function(err, res) {
          if (err) {
            callback(err);
          } else {
            callback(null, res[res.length-1].object.value);
          }
        });
      }
    });
  }
}
217340
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
        nofilter=0, type=ETH_P_ALL, *args, **kargs):
    """"""
    if iface is None and iface_hint is not None:
        iface = conf.route.route(iface_hint)[0]
    s = conf.L2socket(promisc=promisc, iface=iface,
                      filter=filter, nofilter=nofilter, type=type)
    result = sndrcv(s, x, *args, **kargs)
    s.close()
    return result
1143134
def absolute(parser, token):
    '''
    
    '''
    node = url(parser, token)
    return AbsoluteUrlNode(
        view_name=node.view_name,
        args=node.args,
        kwargs=node.kwargs,
        asvar=node.asvar
    )
96271
function notfoundUnit (server) {
  var regexes = [];
  var callbacks = [];

  function notfound (paths, literalCall) {
    regexes.push(RegExp(paths));
    callbacks.push(literalCall);
  }

  server.notfound = notfound;

  return function notfoundLayer (req, res) {
    res.statusCode = 404;
    var matched = null;
    var cbindex = -1;
    for (var i = 0; i < regexes.length; i++) {
      matched = req.path.match (regexes[i]);
      if (matched !== null) { cbindex = i; break; }
    }
    if (cbindex >= 0) {
      catchpath(req, res, matched, callbacks[cbindex], server.templateReader);
    } else {
      res.end('Not Found\n');
    }
  };
}
807948
@Override
  public AvroEvaluatorsInfo toAvro(
      final List<String> ids, final Map<String, EvaluatorDescriptor> evaluators) {

    final List<AvroEvaluatorInfo> evaluatorsInfo = new ArrayList<>();

    for (final String id : ids) {

      final EvaluatorDescriptor evaluatorDescriptor = evaluators.get(id);
      String nodeId = null;
      String nodeName = null;
      InetSocketAddress address = null;
      int memory = 0;
      String type = null;
      String runtimeName = null;

      if (evaluatorDescriptor != null) {
        nodeId = evaluatorDescriptor.getNodeDescriptor().getId();
        nodeName = evaluatorDescriptor.getNodeDescriptor().getName();
        address = evaluatorDescriptor.getNodeDescriptor().getInetSocketAddress();
        memory = evaluatorDescriptor.getMemory();
        type = evaluatorDescriptor.getProcess().getType().toString();
        runtimeName = evaluatorDescriptor.getRuntimeName();
      }

      evaluatorsInfo.add(AvroEvaluatorInfo.newBuilder()
          .setEvaluatorId(id)
          .setNodeId(nodeId != null ? nodeId : "")
          .setNodeName(nodeName != null ? nodeName : "")
          .setInternetAddress(address != null ? address.toString() : "")
          .setMemory(memory)
          .setType(type != null ? type : "")
          .setRuntimeName(runtimeName != null ? runtimeName : "")
          .build());
    }

    return AvroEvaluatorsInfo.newBuilder()
        .setEvaluatorsInfo(evaluatorsInfo)
        .build();
  }
1374787
def make_valid_avro(items,          # type: Avro
                    alltypes,       # type: Dict[Text, Dict[Text, Any]]
                    found,          # type: Set[Text]
                    union=False     # type: bool
                    ):
    # type: (...) -> Union[Avro, Dict, Text]
    """"""
    # Possibly could be integrated into our fork of avro/schema.py?
    if isinstance(items, MutableMapping):
        items = copy.copy(items)
        if items.get("name") and items.get("inVocab", True):
            items["name"] = avro_name(items["name"])

        if "type" in items and items["type"] in (
                "https://w3id.org/cwl/salad#record",
                "https://w3id.org/cwl/salad#enum", "record", "enum"):
            if (hasattr(items, "get") and items.get("abstract")) or ("abstract"
                                                                     in items):
                return items
            if items["name"] in found:
                return cast(Text, items["name"])
            found.add(items["name"])
        for field in ("type", "items", "values", "fields"):
            if field in items:
                items[field] = make_valid_avro(
                    items[field], alltypes, found, union=True)
        if "symbols" in items:
            items["symbols"] = [avro_name(sym) for sym in items["symbols"]]
        return items
    if isinstance(items, MutableSequence):
        ret = []
        for i in items:
            ret.append(make_valid_avro(i, alltypes, found, union=union))  # type: ignore
        return ret
    if union and isinstance(items, string_types):
        if items in alltypes and avro_name(items) not in found:
            return cast(Dict, make_valid_avro(alltypes[items], alltypes, found,
                                              union=union))
        items = avro_name(items)
    return items
1289839
def _update_avr_2016(self):
        
        # Collect tags for AppCommand.xml call
        tags = ["GetAllZonePowerStatus", "GetAllZoneSource",
                "GetAllZoneVolume", "GetAllZoneMuteStatus",
                "GetSurroundModeStatus"]
        # Execute call
        root = self.exec_appcommand_post(tags)
        # Check result
        if root is None:
            _LOGGER.error("Update failed.")
            return False

        # Extract relevant information
        zone = self._get_own_zone()

        try:
            self._power = root[0].find(zone).text
        except (AttributeError, IndexError):
            _LOGGER.error("No PowerStatus found for zone %s", self.zone)

        try:
            self._mute = root[3].find(zone).text
        except (AttributeError, IndexError):
            _LOGGER.error("No MuteStatus found for zone %s", self.zone)

        try:
            self._volume = root.find(
                "./cmd/{zone}/volume".format(zone=zone)).text
        except AttributeError:
            _LOGGER.error("No VolumeStatus found for zone %s", self.zone)

        try:
            inputfunc = root.find(
                "./cmd/{zone}/source".format(zone=zone)).text
        except AttributeError:
            _LOGGER.error("No Source found for zone %s", self.zone)
        else:
            try:
                self._input_func = self._input_func_list_rev[inputfunc]
            except KeyError:
                _LOGGER.info("No mapping for source %s found", inputfunc)
                self._input_func = inputfunc
                # Get/update sources list if current source is not known yet
                if self._update_input_func_list():
                    _LOGGER.info("List of input functions refreshed.")
                    # If input function is still not known, create new entry.
                    if (inputfunc not in self._input_func_list and
                            inputfunc is not None):
                        self._input_func_list_rev[inputfunc] = inputfunc
                        self._input_func_list[inputfunc] = inputfunc
                else:
                    _LOGGER.error((
                        "Input function list for Denon receiver at host %s "
                        "could not be updated."), self._host)
        try:
            self._sound_mode_raw = root[4][0].text.rstrip()
        except (AttributeError, IndexError):
            _LOGGER.error("No SoundMode found for the main zone %s", self.zone)

        # Now playing information is not implemented for 2016+ models, because
        # a HEOS API query needed. So only sync the power state for now.
        if self._power == POWER_ON:
            self._state = STATE_ON
        else:
            self._state = STATE_OFF

        return True
56978
function vver(pt, inc) {
		return (pt ? vv(3) : '') + vv(5, self.versionMajor) + vv(6) + vv(7, self.versionMinor) + vv(8)
				+ vv(9, self.versionPatch, inc && !self.versionPrereleaseChar) + vv(10)
				+ vv(11, self.versionPrerelease, inc && self.versionPrereleaseChar) + vv(12, self.versionMetadata);
	}
934143
function absoluteURI(uri, base) {
    if (uri.substr(0, 2) == './')
      uri = uri.substr(2);

    // absolute urls are left in tact
    if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
      return uri;
    
    var baseParts = base.split('/');
    var uriParts = uri.split('/');
    
    baseParts.pop();
    
    while (curPart = uriParts.shift())
      if (curPart == '..')
        baseParts.pop();
      else
        baseParts.push(curPart);
    
    return baseParts.join('/');
  }
906398
function pluck(srcArr, pathStr) {
      var tmpArr = [];
      if (typeVal(pathStr, 'str')) {
        forEach(srcArr, function (val) { tmpArr.push(get(val, pathStr)); });
      }
      return tmpArr;
    }
1134797
def make_avro_schema(i,         # type: List[Any]
                     loader     # type: Loader
                     ):  # type: (...) -> Names
    
    names = Names()
    avro = make_avro(i, loader)
    make_avsc_object(convert_to_dict(avro), names)
    return names
662661
def is_avro(path_or_buffer):
    
    if is_str(path_or_buffer):
        fp = open(path_or_buffer, 'rb')
        close = True
    else:
        fp = path_or_buffer
        close = False

    try:
        header = fp.read(len(MAGIC))
        return header == MAGIC
    finally:
        if close:
            fp.close()