Patch botocore client so it generates subsegments
    when calling AWS services.
6348
def patch():
    
    if hasattr(botocore.client, '_xray_enabled'):
        return
    setattr(botocore.client, '_xray_enabled', True)

    wrapt.wrap_function_wrapper(
        'botocore.client',
        'BaseClient._make_api_call',
        _xray_traced_botocore,
    )

    wrapt.wrap_function_wrapper(
        'botocore.endpoint',
        'Endpoint.prepare_request',
        inject_header,
    )
540436
def patch(*args, **kwargs):
    
    from caliendo.patch import patch as p
    return p(*args, **kwargs)
574898
def patch_tree(actions, tree):
    """"""
    patcher = patch.Patcher()
    return patcher.patch(actions, tree)
5311
def apply_fixes(args, tmpdir):
  """"""
  invocation = [args.clang_apply_replacements_binary]
  if args.format:
    invocation.append('-format')
  if args.style:
    invocation.append('-style=' + args.style)
  invocation.append(tmpdir)
  subprocess.call(invocation)
1143243
def monkey_patch(cls):
        """"""
        on_read_the_docs = os.environ.get('READTHEDOCS', False)
        if on_read_the_docs:
            sys.modules['zbarlight._zbarlight'] = cls
323192
def _patch(self, opt={}):
        
        opt_netloc = opt.pop(Request.opt_url_netloc, None)
        opt_scheme = opt.pop(Request.opt_url_scheme, None)
        if opt_netloc or opt_scheme:
            scheme, netloc, path, params, query, fragment = six.moves.urllib.parse.urlparse(self.__url)
            self.__url = six.moves.urllib.parse.urlunparse((
                opt_scheme or scheme,
                opt_netloc or netloc,
                path,
                params,
                query,
                fragment
            ))

            logger.info('patching url: [{0}]'.format(self.__url))
810269
function Client (opts) {
  // update client instance and config
  // with overrides from opts.
  _.extend(this, {
    Saver: require('./saver').Saver
  }, opts)

  config.extend(opts)

  // allow sqs to be overridden
  // in tests.
  if (opts && opts.sqs) {
    this.sqs = opts.sqs
    delete opts.sqs
  } else {
    this.sqs = new aws.SQS({
      accessKeyId: config.get('awsKey'),
      secretAccessKey: config.get('awsSecret'),
      region: config.get('awsRegion')
    })
  }

  config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue'))
}
594634
function patch(Ware) {
  var AttachWare = unherit(Ware)
  var useFn = Ware.prototype.use

  AttachWare.prototype.use = use

  return wrap

  function wrap(fn) {
    return new AttachWare(fn)
  }

  /* Attach configurable middleware. */
  function use(attach) {
    var self = this
    var params = slice.call(arguments, 1)
    var index
    var length
    var fn

    /* Multiple attachers. */
    if ('length' in attach && typeof attach !== 'function') {
      index = -1
      length = attach.length

      /* So, `attach[0]` is a function, meaning its
       * either a list of `attachers` or its a `list`. */
      if (typeof attach[0] === 'function') {
        if (
          attach[1] !== null &&
          attach[1] !== undefined &&
          typeof attach[1] !== 'function'
        ) {
          self.use.apply(self, attach)
        } else {
          while (++index < length) {
            self.use.apply(self, [attach[index]].concat(params))
          }
        }
      } else {
        while (++index < length) {
          self.use(attach[index])
        }
      }

      return self
    }

    /* Single attacher. */
    fn = attach.apply(null, [self.context || self].concat(params))

    /* Store the attacher to not break `new Ware(otherWare)`
     * functionality. */
    if (!self.attachers) {
      self.attachers = []
    }

    self.attachers.push(attach)

    /* Pass `fn` to the original `Ware#use()`. */
    if (fn) {
      useFn.call(self, fn)
    }

    return self
  }
}
1070035
public function oldDispatch()
    {
        // For each update type
        foreach (BasicBot::$update_types as $offset => $class) {
            // Check if the bot has an inherited method
            if (method_exists($this, 'process' . $class)) {
                // Wrap it in a closure to make it works with the 3.0 version
                $this->answerUpdate[$offset] = function ($bot, $entity) use ($class) {
                    $bot->{"process$class"}($entity);
                };
            }
        }
    }
280196
def on_patch(self, req, resp, **kwargs):
        """"""
        validated = self.require_validated(req, bulk=True)

        return super().on_patch(
            req, resp,
            handler=partial(self._create_bulk, validated=validated),
            **kwargs
        )
189556
def worker_config(queue, s3_key, period, verbose):
    """"""
    logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
    logging.getLogger('botocore').setLevel(logging.WARNING)
    logging.getLogger('s3transfer').setLevel(logging.WARNING)

    queue, region = get_queue(queue)
    factory = SessionFactory(region)
    session = factory()
    client = session.client('sqs')
    messages = MessageIterator(client, queue, timeout=20)

    for m in messages:
        msg = unwrap(m)
        if 'configurationItemSummary' in msg:
            rtype = msg['configurationItemSummary']['resourceType']
        else:
            rtype = msg['configurationItem']['resourceType']
        if rtype not in RESOURCE_MAPPING.values():
            log.info("skipping %s" % rtype)
            messages.ack(m)
        log.info("message received %s", m)
384955
def main():
    """"""
    parser = ArgumentParser()
    subs = parser.add_subparsers(dest='cmd')
    setup_parser = subs.add_parser('setup')
    setup_parser.add_argument('-r', '--region', default=PRIMARY_REGION,
                              help='AWS region to install all services')
    setup_parser.add_argument('-d', '--debug', action='store_true',
                              help='Run in debug mode')
    setup_parser.add_argument('--rollback', action='store_true',
                              help='Rollback configuration on failure')
    setup_parser.add_argument('--skip-node-setup', action='store_true',
                              help='Rollback configuration on failure')
    setup_parser = subs.add_parser('teardown')
    setup_parser.add_argument('-r', '--region', default=PRIMARY_REGION,
                              help='AWS region to delete all services')
    setup_parser.add_argument('-d', '--debug', action='store_true',
                              help='Run in debug mode')
    args = parser.parse_args()

    if args.region:
        if args.region not in SUPPORTED_REGIONS:
            raise Exception("INVALID_REGION: Region must be one of: %s"
                            % (', '.join(SUPPORTED_REGIONS)))
        global PRIMARY_REGION
        PRIMARY_REGION = args.region

    if args.debug:
        logger.setLevel(logging.DEBUG)

    if args.cmd == 'setup':
        try:
            generate_handler()
            time.sleep(7)
            generate_s3_bucket()
            generate_dynamodb_tables()
            generate_lambda_functions()
            generate_api_gateway()
            generate_admin_resource()
            api_node = generate_api_resources()
        except Exception as e:
            logger.error(str(e))
            if args.rollback:
                logger.info("[!] Rolling back deployed services")
                remove_s3_bucket()
                remove_dynamodb_tables()
                remove_lambda_functions()
                remove_api_gateway()
                remove_handler()

        if not args.skip_node_setup:
            email = input("[*] Blockade admin email: ")
            if email.find('@') < 0:
                logger.error("[!] %s does not appear to be an email" % email)
                email = input("[*] Blockade admin email: ")
            name = input("[*] Blockade admin name: ")

            url = api_node + "admin/add-user"
            params = {'user_email': email, 'user_name': name,
                      'user_role': 'admin'}
            headers = {'Content-Type': 'application/json'}
            response = requests.post(url, data=json.dumps(params),
                                     headers=headers)
            loaded = json.loads(response.content)
            logger.info("[#] Successfully added Blockade admin")
            logger.debug(loaded)
            print("---------------------------------------------------------------------------")
            print("Blockade Server: %s" % api_node)
            print("Blockade Admin: %s" % loaded['email'])
            print("Blockade API Key: %s" % loaded['api_key'])
            print("---------------------------------------------------------------------------")
            print("Quick Config: blockade-cfg setup %s %s --api-node=%s"
                  % (loaded['email'], loaded['api_key'], api_node))
            print("Next steps: Add indicators to your node with our analyst toolbench: %s" % (ANALYST_TOOLBENCH))
            print("For more documentation on other cloud node actions, see %s." % (CLOUD_NODE_DOCS))

    if args.cmd == 'teardown':
        remove_s3_bucket()
        remove_dynamodb_tables()
        remove_lambda_functions()
        remove_api_gateway()
        remove_handler()
856519
def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
	
	patches = SplitPatch(data)
	rv = []
	for patch in patches:
		set_status("uploading patch for " + patch[0])
		if len(patch[1]) > MAX_UPLOAD_SIZE:
			print ("Not uploading the patch for " + patch[0] +
				" because the file is too large.")
			continue
		form_fields = [("filename", patch[0])]
		if not options.download_base:
			form_fields.append(("content_upload", "1"))
		files = [("data", "data.diff", patch[1])]
		ctype, body = EncodeMultipartFormData(form_fields, files)
		url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
		print "Uploading patch for " + patch[0]
		response_body = rpc_server.Send(url, body, content_type=ctype)
		lines = response_body.splitlines()
		if not lines or lines[0] != "OK":
			StatusUpdate("  --> %s" % response_body)
			sys.exit(1)
		rv.append([lines[1], patch[0]])
	return rv
156402
def patch_stream(self, instream, hunks):
    

    # todo: At the moment substituted lineends may not be the same
    #       at the start and at the end of patching. Also issue a
    #       warning/throw about mixed lineends (is it really needed?)

    hunks = iter(hunks)

    srclineno = 1

    lineends = {b'\n':0, b'\r\n':0, b'\r':0}
    def get_line():
      """
      local utility function - return line from source stream
      collecting line end statistics on the way
      """
      line = instream.readline()
        # 'U' mode works only with text files
      if line.endswith(b"\r\n"):
        lineends[b"\r\n"] += 1
      elif line.endswith(b"\n"):
        lineends[b"\n"] += 1
      elif line.endswith(b"\r"):
        lineends[b"\r"] += 1
      return line

    for hno, h in enumerate(hunks):
      debug("hunk %d" % (hno+1))
      # skip to line just before hunk starts
      while srclineno < h.startsrc:
        yield get_line()
        srclineno += 1

      for hline in h.text:
        # todo: check \ No newline at the end of file
        if hline.startswith(b"-") or hline.startswith(b"\\"):
          get_line()
          srclineno += 1
          continue
        else:
          if not hline.startswith(b"+"):
            get_line()
            srclineno += 1
          line2write = hline[1:]
          # detect if line ends are consistent in source file
          if sum([bool(lineends[x]) for x in lineends]) == 1:
            newline = [x for x in lineends if lineends[x] != 0][0]
            yield line2write.rstrip(b"\r\n")+newline
          else: # newlines are mixed
            yield line2write

    for line in instream:
      yield line
596431
def patch(self, url, headers=None, body=None, kwargs=None):
        
        return self._request(
            method='patch',
            url=url,
            headers=headers,
            body=body,
            kwargs=kwargs
        )
167848
def compress_monkey_patch():
    
    from compressor.templatetags import compress as compress_tags
    from compressor import base as compress_base

    compress_base.Compressor.filter_input = filter_input
    compress_base.Compressor.output = output
    compress_base.Compressor.hunks = hunks
    compress_base.Compressor.precompile = precompile

    compress_tags.CompressorMixin.render_compressed = render_compressed

    from django_pyscss import compressor as pyscss_compressor

    pyscss_compressor.DjangoScssFilter.input = input
336801
def _process_config(self):
        """"""
        self._user_agent_adding_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)

        if self.config.region_names:
            self.add_regional_clients_from_list(self.config.region_names)
            self.default_region = self.config.region_names[0]
        else:
            self.default_region = self.config.botocore_session.get_config_variable("region")
            if self.default_region is not None:
                self.add_regional_client(self.default_region)

        if self.config.key_ids:
            self.add_master_keys_from_list(self.config.key_ids)