Question:
Default permissions for this ChangeSetItem

@param string $perm
@param Member $member
@param array $context
@return bool

public function can($perm, $member = null, $context = [])
    {
        if (!$member) {
            $member = Security::getCurrentUser();
        }

        // Allow extensions to bypass default permissions, but only if
        // each change can be individually published.
        $extended = $this->extendedCan($perm, $member, $context);
        if ($extended !== null) {
            return $extended;
        }

        // Default permissions
        return (bool)Permission::checkMember($member, ChangeSet::config()->get('required_permission'));
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end

      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Downloads and loads the CoNLL 2000 Chunking dataset.
        NOTE: There is only a train and test dataset so we use
              10% of the train set as validation

def splits(cls, fields, root=".data", train="train.txt",
               test="test.txt", validation_frac=0.1, **kwargs):

        train, test = super(CoNLL2000Chunking, cls).splits(
            fields=fields, root=root, train=train,
            test=test, separator=' ', **kwargs)

        # HACK: Saving the sort key function as the split() call removes it
        sort_key = train.sort_key

        # Now split the train set
        # Force a random seed to make the split deterministic
        random.seed(0)
        train, val = train.split(1 - validation_frac, random_state=random.getstate())
        # Reset the seed
        random.seed()

        # HACK: Set the sort key
        train.sort_key = sort_key
        val.sort_key = sort_key

        return train, val, test

def verify_convention_version(self, ds):

        try:
            for convention in getattr(ds, "Conventions", '').replace(' ', '').split(','):
                if convention == 'ACDD-' + self._cc_spec_version:
                    return ratable_result((2, 2), None, []) # name=None so grouped with Globals

            # if no/wrong ACDD convention, return appropriate result
            # Result will have name "Global Attributes" to group with globals
            m = ["Conventions does not contain 'ACDD-{}'".format(self._cc_spec_version)]
            return ratable_result((1, 2), "Global Attributes", m)
        except AttributeError: # NetCDF attribute not found
            m = ["No Conventions attribute present; must contain ACDD-{}".format(self._cc_spec_version)]
            # Result will have name "Global Attributes" to group with globals
            return ratable_result((0, 2), "Global Attributes", m)

Instruction: Given a code description, retrieve the corresponding code.


Question: // Send starts outgoing file transmission. It returns io.ReaderFrom or error.

func (c Client) Send(filename string, mode string) (io.ReaderFrom, error) {
	conn, err := net.ListenUDP("udp", &net.UDPAddr{})
	if err != nil {
		return nil, err
	}
	s := &sender{
		send:    make([]byte, datagramLength),
		receive: make([]byte, datagramLength),
		conn:    &connConnection{conn: conn},
		retry:   &backoff{handler: c.backoff},
		timeout: c.timeout,
		retries: c.retries,
		addr:    c.addr,
		mode:    mode,
	}
	if c.blksize != 0 {
		s.opts = make(options)
		s.opts["blksize"] = strconv.Itoa(c.blksize)
	}
	n := packRQ(s.send, opWRQ, filename, mode, s.opts)
	addr, err := s.sendWithRetry(n)
	if err != nil {
		return nil, err
	}
	s.addr = addr
	s.opts = nil
	return s, nil
}

function (filename) {
		var resume = filename === true; // should only ever be set by resume calls
		var fd = this._fd = resume ? this._fd : fs.openSync(filename, 'r');
		var buffer = new Buffer(4096);
		var bytesRead;
		var current = '';
		var remainder = resume ? this._remainder : '';

		while (!this._paused && (bytesRead = fs.readSync(fd, buffer, 0, buffer.length))) {
			current = buffer.toString('utf-8');
			if (current.length > bytesRead) {
				current = current.slice(0, bytesRead);
			}
			remainder = this._remainder = this._parseLines(remainder + current);
		}

		// The loop will end either when EOF is reached, or pause was called.
		// In the former case, close the file; in the latter case, leave it
		// open with the expectation that we'll pick up where we left off.
		if (!this._paused) {
			fs.closeSync(fd);
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: creates database table

public function createTable($conn, $table, $schema, array $definition)
    {
        if (empty($definition['columns'])) {
            throw new Exception("The table must contain at least one column");
        }
        $conn->execute($this->getDialect($conn)->createTable($table, $schema, $definition));
    }

public function getTables($which_connection='')
    {
        if ($which_connection == '') {
            $which_connection=$this->default_db;
        }
        $conn = $this->connections[$which_connection];

        return $conn->MetaTables();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetTagging sets the Tagging field's value.

func (s *PutObjectTaggingInput) SetTagging(v *Tagging) *PutObjectTaggingInput {
	s.Tagging = v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Trim this fastqSequence in-place by removing <amount> nucleotides from
      the 5' end (left end).

      :param amount: the number of nucleotides to trim from the left-side of
                     this sequence.

def trimLeft(self, amount):

    if amount == 0:
      return
    self.sequenceData = self.sequenceData[amount:]
    self.sequenceQual = self.sequenceQual[amount:]

func updateNodeField(src interface{}, targetName string, target interface{}) interface{} {
	var isPtr bool
	srcVal := reflect.ValueOf(src)
	// verify condition
	if srcVal.Kind() == reflect.Ptr {
		isPtr = true
		srcVal = srcVal.Elem()
	}
	targetVal := reflect.ValueOf(target)
	if srcVal.Kind() != reflect.Struct {
		return src
	}
	srcFieldValue := srcVal.FieldByName(targetName)
	if !srcFieldValue.IsValid() || srcFieldValue.Kind() != targetVal.Kind() {
		return src
	}

	if srcFieldValue.CanSet() {
		if srcFieldValue.Kind() == reflect.Slice {
			items := reflect.MakeSlice(srcFieldValue.Type(), targetVal.Len(), targetVal.Len())
			for index := 0; index < items.Len(); index++ {
				tmp := targetVal.Index(index).Interface()
				items.Index(index).Set(reflect.ValueOf(tmp))
			}
			srcFieldValue.Set(items)
		} else {
			srcFieldValue.Set(targetVal)
		}
	}
	if isPtr {
		return srcVal.Addr().Interface()
	}
	return srcVal.Interface()
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Creates a list of items with children.

@param \Aimeos\MShop\Locale\Item\Site\Iface $item Locale site item

protected function createNodeArray( \Aimeos\MShop\Locale\Item\Site\Iface $item )
	{
		$result = $item->toArray( true );

		if( method_exists( $item, 'getChildren' ) )
		{
			foreach( $item->getChildren() as $child ) {
				$result['children'][] = $this->createNodeArray( $child );
			}
		}

		return (object) $result;
	}

function CorreosInfo(obj) {
    // Sent details
    this.id = obj.nenvio
    this.state = obj.estado
    this.received = moment.tz(obj.fecha, "DD/MM/YY", zone).format()
    this.lastUpdate = moment.tz(obj.fechaEstado, "DD/MM/YY HH:mm", zone).format()

    // Sender Details
    this.sender = {
        name: obj.sendername.replace('¿', ''),
        city: obj.sendercity,
        address: obj.senderaddress
    }

    // Receiver Details
    this.receiver = {
        name: obj.receivername,
        city: obj.receivercity,
        address: obj.receiveraddress
    }

    // Product Details
    this.product = {
        weight: obj.weight,
        parcels: obj.parcels,
        ref: obj.ref,
        observations: obj.observations
    }

    //States
    this.states = obj.states.reverse()

    this.trackerWebsite = correos.getLink(obj.id)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Create WordNode with POS.
@param item
@returns {{type: string, value: *}}

function createWordNode (item) {
      var wordNode = parser.createParentNode('Word')

      if (options && options.pos) {
        wordNode.data = item
      }

      var textNode = parser.createTextNode('Text', item.surface_form)

      parser.add(textNode, wordNode)

      return wordNode
    }

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Loads waiter configuration from API configuration

@api private

function loadWaiterConfig(state) {
    if (!this.service.api.waiters[state]) {
      throw new AWS.util.error(new Error(), {
        code: 'StateNotFoundError',
        message: 'State ' + state + ' not found.'
      });
    }

    this.config = AWS.util.copy(this.service.api.waiters[state]);
  }

async def workerTypeErrors(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["workerTypeErrors"], *args, **kwargs)

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Shows the properties of an object.
// If the member delta is set to true in the request, only the delta is retrieved.
//
// The following is always returned in the output:

func (obj *GenericVariable) GetProperties(ctx context.Context) (*GenericVariableProperties, error) {
	result := &struct {
		Prop *GenericVariableProperties	`json:"qProp"`
	} {}
	err := obj.rpc(ctx, "GetProperties", result)
	return result.Prop, err
}

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Function to init new response structures.

func (nc *Conn) initNewResp() {
	// _INBOX wildcard
	nc.respSub = fmt.Sprintf("%s.*", NewInbox())
	nc.respMap = make(map[string]chan *Msg)
	nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
}

func (factory *FacebookBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface {
	bee := FacebookBee{
		Bee: bees.NewBee(name, factory.ID(), description, options),
	}
	bee.ReloadOptions(options)

	return &bee
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // GetClient returns a client instance, if set. May be nil.

func GetClient(ctx context.Context) *Client {
	c, ok := ctx.Value(ctxKeyClient).(*Client)
	if !ok {
		return nil
	}
	return c
}

func NewMockSystemAPIClient(ctrl *gomock.Controller) *MockSystemAPIClient {
	mock := &MockSystemAPIClient{ctrl: ctrl}
	mock.recorder = &MockSystemAPIClientMockRecorder{mock}
	return mock
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Run "down" a migration instance.

@param  string    $path
@param  string    $file
@param  string    $path
@param  Extension $extension
@return void

protected function runDown($path, $file, Extension $extension = null)
    {
        $migration = $this->resolve($path, $file);

        $this->runClosureMigration($migration, 'down');

        // Once we have successfully run the migration "down" we will remove it from
        // the migration repository so it will be considered to have not been run
        // by the application then will be able to fire by any later operation.
        $this->repository->delete($file, $extension ? $extension->getId() : null);

        $this->note("<info>Rolled back:</info> $file");
    }

public static function fromPath(string $path, ?Throwable $previous = null): FileNotFoundException
    {
        $message = sprintf('File not found: %s', $path);

        return new static($message, $path, $previous);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retrieves all the templates that are newer that the timestamp specified
by the client.  The pathInfo from the request specifies which templates
are desired.  QueryString parameters "timeStamp" and ??? provide

public void doGet(HttpServletRequest req,HttpServletResponse res) {
        getTemplateData(req, res,req.getPathInfo());
    }

def parse_arguments():

    # define supported command line arguments
    parser = argparse.ArgumentParser(description='Common interface for the ' +
                                                 'WakaTime api.')
    parser.add_argument('--entity', dest='entity', metavar='FILE',
                        action=FileAction,
                        help='Absolute path to file for the heartbeat. Can ' +
                             'also be a url, domain or app when ' +
                             '--entity-type is not file.')
    parser.add_argument('--file', dest='file', action=FileAction,
                        help=argparse.SUPPRESS)
    parser.add_argument('--key', dest='key', action=StoreWithoutQuotes,
                        help='Your wakatime api key; uses api_key from ' +
                             '~/.wakatime.cfg by default.')
    parser.add_argument('--write', dest='is_write', action='store_true',
                        help='When set, tells api this heartbeat was ' +
                             'triggered from writing to a file.')
    parser.add_argument('--plugin', dest='plugin', action=StoreWithoutQuotes,
                        help='Optional text editor plugin name and version ' +
                             'for User-Agent header.')
    parser.add_argument('--time', dest='timestamp', metavar='time',
                        type=float, action=StoreWithoutQuotes,
                        help='Optional floating-point unix epoch timestamp. ' +
                             'Uses current time by default.')
    parser.add_argument('--lineno', dest='lineno', action=StoreWithoutQuotes,
                        help='Optional line number. This is the current ' +
                             'line being edited.')
    parser.add_argument('--cursorpos', dest='cursorpos',
                        action=StoreWithoutQuotes,
                        help='Optional cursor position in the current file.')
    parser.add_argument('--entity-type', dest='entity_type',
                        action=StoreWithoutQuotes,
                        help='Entity type for this heartbeat. Can be ' +
                             '"file", "domain" or "app". Defaults to "file".')
    parser.add_argument('--category', dest='category',
                        action=StoreWithoutQuotes,
                        help='Category of this heartbeat activity. Can be ' +
                             '"coding", "building", "indexing", ' +
                             '"debugging", "running tests", ' +
                             '"writing tests", "manual testing", ' +
                             '"code reviewing", "browsing", or "designing". ' +
                             'Defaults to "coding".')
    parser.add_argument('--proxy', dest='proxy', action=StoreWithoutQuotes,
                        help='Optional proxy configuration. Supports HTTPS '+
                             'and SOCKS proxies. For example: '+
                             'https://user:pass@host:port or '+
                             'socks5://user:pass@host:port or ' +
                             'domain\\user:pass')
    parser.add_argument('--no-ssl-verify', dest='nosslverify',
                        action='store_true',
                        help='Disables SSL certificate verification for HTTPS '+
                             'requests. By default, SSL certificates are ' +
                             'verified.')
    parser.add_argument('--ssl-certs-file', dest='ssl_certs_file',
                        action=StoreWithoutQuotes,
                        help='Override the bundled Python Requests CA certs ' +
                             'file. By default, uses certifi for ca certs.')
    parser.add_argument('--project', dest='project', action=StoreWithoutQuotes,
                        help='Optional project name.')
    parser.add_argument('--alternate-project', dest='alternate_project',
                        action=StoreWithoutQuotes,
                        help='Optional alternate project name. ' +
                             'Auto-discovered project takes priority.')
    parser.add_argument('--alternate-language', dest='alternate_language',
                        action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--language', dest='language',
                        action=StoreWithoutQuotes,
                        help='Optional language name. If valid, takes ' +
                             'priority over auto-detected language.')
    parser.add_argument('--local-file', dest='local_file', metavar='FILE',
                        action=FileAction,
                        help='Absolute path to local file for the ' +
                             'heartbeat. When --entity is a remote file, ' +
                             'this local file will be used for stats and ' +
                             'just the value of --entity sent with heartbeat.')
    parser.add_argument('--hostname', dest='hostname',
                        action=StoreWithoutQuotes,
                        help='Hostname of current machine.')
    parser.add_argument('--disable-offline', dest='offline',
                        action='store_false',
                        help='Disables offline time logging instead of ' +
                             'queuing logged time.')
    parser.add_argument('--disableoffline', dest='offline_deprecated',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hide-file-names', dest='hide_file_names',
                        action='store_true',
                        help='Obfuscate filenames. Will not send file names ' +
                             'to api.')
    parser.add_argument('--hide-filenames', dest='hide_filenames',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hidefilenames', dest='hidefilenames',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hide-project-names', dest='hide_project_names',
                        action='store_true',
                        help='Obfuscate project names. When a project ' +
                             'folder is detected instead of using the ' +
                             'folder name as the project, a ' +
                             '.wakatime-project file is created with a ' +
                             'random project name.')
    parser.add_argument('--exclude', dest='exclude', action='append',
                        help='Filename patterns to exclude from logging. ' +
                             'POSIX regex syntax. Can be used more than once.')
    parser.add_argument('--exclude-unknown-project',
                        dest='exclude_unknown_project', action='store_true',
                        help='When set, any activity where the project ' +
                             'cannot be detected will be ignored.')
    parser.add_argument('--include', dest='include', action='append',
                        help='Filename patterns to log. When used in ' +
                             'combination with --exclude, files matching ' +
                             'include will still be logged. POSIX regex ' +
                             'syntax. Can be used more than once.')
    parser.add_argument('--include-only-with-project-file',
                        dest='include_only_with_project_file',
                        action='store_true',
                        help='Disables tracking folders unless they contain ' +
                             'a .wakatime-project file. Defaults to false.')
    parser.add_argument('--ignore', dest='ignore', action='append',
                        help=argparse.SUPPRESS)
    parser.add_argument('--extra-heartbeats', dest='extra_heartbeats',
                        action='store_true',
                        help='Reads extra heartbeats from STDIN as a JSON ' +
                             'array until EOF.')
    parser.add_argument('--log-file', dest='log_file',
                        action=StoreWithoutQuotes,
                        help='Defaults to ~/.wakatime.log.')
    parser.add_argument('--logfile', dest='logfile', action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--api-url', dest='api_url', action=StoreWithoutQuotes,
                        help='Heartbeats api url. For debugging with a ' +
                             'local server.')
    parser.add_argument('--apiurl', dest='apiurl', action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--timeout', dest='timeout', type=int,
                        action=StoreWithoutQuotes,
                        help='Number of seconds to wait when sending ' +
                             'heartbeats to api. Defaults to 60 seconds.')
    parser.add_argument('--sync-offline-activity',
                        dest='sync_offline_activity',
                        action=StoreWithoutQuotes,
                        help='Amount of offline activity to sync from your ' +
                             'local ~/.wakatime.db sqlite3 file to your ' +
                             'WakaTime Dashboard before exiting. Can be ' +
                             '"none" or a positive integer number. Defaults ' +
                             'to 5, meaning for every heartbeat sent while ' +
                             'online 5 offline heartbeats are synced. Can ' +
                             'be used without --entity to only sync offline ' +
                             'activity without generating new heartbeats.')
    parser.add_argument('--config', dest='config', action=StoreWithoutQuotes,
                        help='Defaults to ~/.wakatime.cfg.')
    parser.add_argument('--verbose', dest='verbose', action='store_true',
                        help='Turns on debug messages in log file.')
    parser.add_argument('--version', action='version', version=__version__)

    # parse command line arguments
    args = parser.parse_args()

    # use current unix epoch timestamp by default
    if not args.timestamp:
        args.timestamp = time.time()

    # parse ~/.wakatime.cfg file
    configs = parseConfigFile(args.config)

    # update args from configs
    if not args.hostname:
        if configs.has_option('settings', 'hostname'):
            args.hostname = configs.get('settings', 'hostname')
    if not args.key:
        default_key = None
        if configs.has_option('settings', 'api_key'):
            default_key = configs.get('settings', 'api_key')
        elif configs.has_option('settings', 'apikey'):
            default_key = configs.get('settings', 'apikey')
        if default_key:
            args.key = default_key
        else:
            try:
                parser.error('Missing api key. Find your api key from wakatime.com/settings/api-key.')
            except SystemExit:
                raise SystemExit(AUTH_ERROR)

    is_valid = not not re.match(r'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$', args.key, re.I)
    if not is_valid:
        try:
            parser.error('Invalid api key. Find your api key from wakatime.com/settings/api-key.')
        except SystemExit:
            raise SystemExit(AUTH_ERROR)

    if not args.entity:
        if args.file:
            args.entity = args.file
        elif not args.sync_offline_activity or args.sync_offline_activity == 'none':
            parser.error('argument --entity is required')

    if not args.sync_offline_activity:
        args.sync_offline_activity = DEFAULT_SYNC_OFFLINE_ACTIVITY
    if args.sync_offline_activity == 'none':
        args.sync_offline_activity = 0
    try:
        args.sync_offline_activity = int(args.sync_offline_activity)
        if args.sync_offline_activity < 0:
            raise Exception('Error')
    except:
        parser.error('argument --sync-offline-activity must be "none" or an integer number')

    if not args.language and args.alternate_language:
        args.language = args.alternate_language

    if not args.exclude:
        args.exclude = []
    if configs.has_option('settings', 'ignore'):
        try:
            for pattern in configs.get('settings', 'ignore').split("\n"):
                if pattern.strip() != '':
                    args.exclude.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if configs.has_option('settings', 'exclude'):
        try:
            for pattern in configs.get('settings', 'exclude').split("\n"):
                if pattern.strip() != '':
                    args.exclude.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if not args.include_only_with_project_file and configs.has_option('settings', 'include_only_with_project_file'):
        args.include_only_with_project_file = configs.get('settings', 'include_only_with_project_file') == 'true'
    if not args.include:
        args.include = []
    if configs.has_option('settings', 'include'):
        try:
            for pattern in configs.get('settings', 'include').split("\n"):
                if pattern.strip() != '':
                    args.include.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if not args.exclude_unknown_project and configs.has_option('settings', 'exclude_unknown_project'):
        args.exclude_unknown_project = configs.getboolean('settings', 'exclude_unknown_project')
    boolean_or_list('hide_file_names', args, configs, alternative_names=['hide_filenames', 'hidefilenames'])
    boolean_or_list('hide_project_names', args, configs, alternative_names=['hide_projectnames', 'hideprojectnames'])
    if args.offline_deprecated:
        args.offline = False
    if args.offline and configs.has_option('settings', 'offline'):
        args.offline = configs.getboolean('settings', 'offline')
    if not args.proxy and configs.has_option('settings', 'proxy'):
        args.proxy = configs.get('settings', 'proxy')
    if args.proxy:
        pattern = r'^((https?|socks5)://)?([^:@]+(:([^:@])+)?@)?[^:]+(:\d+)?$'
        if '\\' in args.proxy:
            pattern = r'^.*\\.+$'
        is_valid = not not re.match(pattern, args.proxy, re.I)
        if not is_valid:
            parser.error('Invalid proxy. Must be in format ' +
                         'https://user:pass@host:port or ' +
                         'socks5://user:pass@host:port or ' +
                         'domain\\user:pass.')
    if configs.has_option('settings', 'no_ssl_verify'):
        args.nosslverify = configs.getboolean('settings', 'no_ssl_verify')
    if configs.has_option('settings', 'ssl_certs_file'):
        args.ssl_certs_file = configs.get('settings', 'ssl_certs_file')
    if not args.verbose and configs.has_option('settings', 'verbose'):
        args.verbose = configs.getboolean('settings', 'verbose')
    if not args.verbose and configs.has_option('settings', 'debug'):
        args.verbose = configs.getboolean('settings', 'debug')
    if not args.log_file and args.logfile:
        args.log_file = args.logfile
    if not args.log_file and configs.has_option('settings', 'log_file'):
        args.log_file = configs.get('settings', 'log_file')
    if not args.log_file and os.environ.get('WAKATIME_HOME'):
        home = os.environ.get('WAKATIME_HOME')
        args.log_file = os.path.join(os.path.expanduser(home), '.wakatime.log')
    if not args.api_url and args.apiurl:
        args.api_url = args.apiurl
    if not args.api_url and configs.has_option('settings', 'api_url'):
        args.api_url = configs.get('settings', 'api_url')
    if not args.timeout and configs.has_option('settings', 'timeout'):
        try:
            args.timeout = int(configs.get('settings', 'timeout'))
        except ValueError:
            print(traceback.format_exc())

    return args, configs

Instruction: Given a code description, retrieve the corresponding code.


Question:
Upload file with AutoIT.
Use only this: {@code button.upload("Browse", "C:\\text.txt")};}

@param text     button text
@param filePath e.g. "C:\\text.txt"
@return true | false

public boolean upload(String text, String filePath) {
        WebLocator upload = new WebLocator(this).setTag("input").setLabel(text).setLabelPosition("//following-sibling::").setLabelTag("span").setType("file");
        return upload(upload, filePath);
    }

def tempfile_path(content)
      tempfile = Tempfile.new('tty-editor')
      tempfile << content
      tempfile.flush
      unless tempfile.nil?
        tempfile.close
      end
      tempfile.path
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Hmac加密模板

@param data      数据
@param key       秘钥
@param algorithm 加密算法
@return 密文字节数组

private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) {
        if (data == null || data.length == 0 || key == null || key.length == 0) return null;
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
            Mac           mac       = Mac.getInstance(algorithm);
            mac.init(secretKey);
            return mac.doFinal(data);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetResourceShareArn sets the ResourceShareArn field's value.

func (s *ResourceShare) SetResourceShareArn(v string) *ResourceShare {
	s.ResourceShareArn = &v
	return s
}

private String[] getEncodingMapKeys(Env env, Env.StackHelp stk, AstRoot asts[]) {
    return getArgAsStrings(env, stk, asts[1]);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retrieves the service instance from a managed object.

    me_ref
        Reference to a managed object (of type vim.ManagedEntity).

    name
        Name of managed object. This field is optional.

def get_service_instance_from_managed_object(mo_ref, name='<unnamed>'):
    '''

    '''
    if not name:
        name = mo_ref.name
    log.trace('[%s] Retrieving service instance from managed object', name)
    si = vim.ServiceInstance('ServiceInstance')
    si._stub = mo_ref._stub
    return si

public static function initByOneToOne($model, $propertyName, $annotation)
    {
        $className = BeanFactory::getObjectClass($model);

        if(class_exists($annotation->model))
        {
            $modelClass = $annotation->model;
        }
        else
        {
            $modelClass = Imi::getClassNamespace($className) . '\\' . $annotation->model;
        }

        $struct = new OneToOne($className, $propertyName, $annotation);
        $leftField = $struct->getLeftField();
        $rightField = $struct->getRightField();

        if(null === $model->$leftField)
        {
            $rightModel = $modelClass::newInstance();
        }
        else
        {
            $rightModel = $modelClass::query()->where($rightField, '=', $model->$leftField)->select()->get();
            if(null === $rightModel)
            {
                $rightModel = $modelClass::newInstance();
            }
        }

        $model->$propertyName = $rightModel;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
[buildForm description]

@param FormBuilderInterface $builder [description]
@param array                $options [description]

@return [type]

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $form_options = $builder->get('value')->getOptions();
        if ($form_options['multiple']) {
            $builder->get('value')->addModelTransformer(new StringToArrayTransformer(','));
        }
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // IsReconnecting returns true if the client is reconnecting right now.

func (c *WSClient) IsReconnecting() bool {
	c.mtx.RLock()
	defer c.mtx.RUnlock()
	return c.reconnecting
}

public List<String> introspect() {
        List<String> rc = new LinkedList<String>();
        String prefix = getClass().getSimpleName() + "@" + hashCode() + ": ";
        rc.add(prefix + "closed=" + this.closed);
        rc.add(prefix + "processClose=" + this.processClose);
        rc.add(prefix + "checkCancel=" + this.checkCancel);
        rc.add(prefix + "tcpChannel=" + this.tcpChannel);
        rc.add(prefix + "socket=" + this.socket);
        if (null != this.socket) {
            rc.add(prefix + "remoteAddr=" + this.socket.getInetAddress());
            rc.add(prefix + "remotePort=" + this.socket.getPort());
            rc.add(prefix + "localAddr=" + this.socket.getLocalAddress());
            rc.add(prefix + "localPort=" + this.socket.getLocalPort());
        }
        rc.add(prefix + "channel=" + this.channel);
        return rc;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
The type of given symbol, seen as a member of t.

@param t a type
@param sym a symbol

public Type memberType(Type t, Symbol sym) {
        return (sym.flags() & STATIC) != 0
            ? sym.type
            : memberType.visit(t, sym);
        }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Refresh all configs

@access public
@param bool $force Is force refresh or not

public function refresh($force = false) {
		if (!$force && time() - $this->last_fetch < $this->config['refresh_interval']) {
			return;
		}
		$clis = [];
		foreach ($this->conf['namespace'] as $v) {
			$clis[] = $this->getClient($v);
		}
		foreach ($clis as $cli) {
			$cli->recv();
			if ($cli->statusCode === 304) {
				continue;
			}
			$res = json_decode($cli->body, true);
			$ns = $res['namespaceName'];
			$this->last_key[$ns] = $res['releaseKey'];
			$this->update($ns, $res['configurations']);
		}
		$this->last_fetch = time();
	}

protected function updateCode() : array
    {
        $output = [];
        $returnValue = 0;

        $updateMaster = 'ls'; // dummy

        if ($this->getBranch() !== 'master') {
            $updateMaster = ' git checkout master && git pull && git checkout '.$this->getBranch().' ';
        }

        $commands = [
            'git reset --hard HEAD',
            'git pull',
            $updateMaster,
            'composer install --no-dev',
            'yarn install --production',
        ];

        foreach ($commands as $command) {
            exec('cd '.$this->getBasepath().' && '.$command, $output, $returnValue);
        }

        return [
            'output'      => $output,
            'returnValue' => $returnValue,
        ];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// See http://tools.ietf.org/html/rfc2045
// This doesn't include extension-token case
// as it's handled separatly

func isDiscreteType(s string) bool {
	if strings.HasPrefix(s, "text") ||
		strings.HasPrefix(s, "image") ||
		strings.HasPrefix(s, "audio") ||
		strings.HasPrefix(s, "video") ||
		strings.HasPrefix(s, "application") {
		return true
	}
	return false
}

def process_key ch
      chr = nil
      if ch > 0 and ch < 256
        chr = ch.chr
      end
      return :UNHANDLED unless @key_map
      @key_map.each_pair do |k,p|
        #$log.debug "KKK:  processing key #{ch}  #{chr} "
        if (k == ch || k == chr)
          #$log.debug "KKK:  checking match == #{k}: #{ch}  #{chr} "
          # compare both int key and chr
          #$log.debug "KKK:  found match 1 #{ch}  #{chr} "
          p.call(self, ch)
          return 0
        elsif k.respond_to? :include?
            #$log.debug "KKK:  checking match include #{k}: #{ch}  #{chr} "
            # this bombs if its a String and we check for include of a ch.
          if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr))
            #$log.debug "KKK:  found match include #{ch}  #{chr} "
            p.call(self, ch)
            return 0
          end
        elsif k.is_a? Regexp
          if k.match(chr)
            #$log.debug "KKK:  found match regex #{ch}  #{chr} "
            p.call(self, ch)
            return 0
          end
        end
      end
      return :UNHANDLED
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: actually run the 'git log' command

def run_log
        log = @base.lib.full_log_commits(:count => @count, :object => @object,
                                    :path_limiter => @path, :since => @since,
                                    :author => @author, :grep => @grep, :skip => @skip,
                                    :until => @until, :between => @between)
        @commits = log.map { |c| Git::Object::Commit.new(@base, c['sha'], c) }
      end

def do_dirty(self, subcmd, opts):

        for comp_name, comp in components.comp_names.items():
            releases = get_released_versions(comp_name)
            if len(releases) == 0:
                print(comp_name + ' - ' + 'No tagged releases')
            else:
                latest_tag = '-'.join(releases[0])
                data = get_changed_since_tag(latest_tag, comp.path)
                if len(data) > 0:
                    print(comp_name + ' - ' + 'Changed files in component tree')

Instruction: Given a code description, retrieve the corresponding code.


Question:
repair.

@param uuid a {@link java.lang.String} object.
@return a {@link ameba.util.Result} object.

@POST
    @Path("{uuid}/repair")
    public Result repair(@PathParam("uuid") String uuid) {
        MigrationFeature.checkMigrationId(uuid);
        if (failMigrations.isEmpty()) {
            throw new NotFoundException();
        }
        for (String dbName : failMigrations.keySet()) {
            MigrationFail fail = failMigrations.get(dbName);
            fail.flyway.repair();
            fail.migration.persist();
            fail.migration.reset();
        }
        failMigrations.clear();
        return Result.success();
    }

func (yr *YubiResponse) GetResultParameter(key string) (value string) {
	value, ok := yr.resultParameters[key]
	if !ok {
		value = ""
	}
	return value
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // MiddlewareContentType adds a content type to a handler

func MiddlewareContentType(contentType string) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			// Content type
			handleContentType(contentType, rw)

			// Next handler
			h.ServeHTTP(rw, r)
		})
	}
}

public static function UnsupportedMediaType($body = NULL, \Exception $previous = NULL) {
    return self::code(415, $body, $previous);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns true if the voter down voted the +voteable+.

def down_voted?(voteable)
      check_voteable(voteable)
      voting = fetch_voting(voteable)
      return false if voting.nil?
      return true if voting.has_attribute?(:up_vote) && !voting.up_vote
      false
    end

protected function setDataRatingEditReview()
    {
        $options = array(
            'product' => $this->data_product,
            'review' => $this->getData('review'),
            'unvote' => $this->config('rating_unvote', 1)
        );

        $this->setData('rating', $this->render('common/rating/edit', $options));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Checkboxes are hidden when inside of a RadioGroup as a selection of
        the Radio button is an implicit selection of the Checkbox. As such, we have
        to manually "check" any checkbox as needed.

def handleImplicitCheck(self):

        for button, widget in zip(self.radioButtons, self.widgets):
            if isinstance(widget, CheckBox):
                if button.GetValue(): # checked
                    widget.setValue(True)
                else:
                    widget.setValue(False)

def _private_notes(self, key, value):

    def _is_for_cds(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'CDS' in normalized_c_values

    def _is_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'HAL' in normalized_c_values

    def _is_not_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'NOT HAL' in normalized_c_values

    _private_notes = self.get('_private_notes', [])
    _export_to = self.get('_export_to', {})

    for value in force_list(value):
        if _is_for_cds(value):
            _export_to['CDS'] = True

        if _is_for_hal(value):
            _export_to['HAL'] = True
        elif _is_not_for_hal(value):
            _export_to['HAL'] = False

        source = force_single_element(value.get('9'))
        for _private_note in force_list(value.get('a')):
            _private_notes.append({
                'source': source,
                'value': _private_note,
            })

    self['_export_to'] = _export_to
    return _private_notes

Instruction: Given a code description, retrieve the corresponding code.


Question:
Convert input system config, flow cell directory and sample yaml to kwargs.

    Handles back compatibility with previous commandlines while allowing flexible
    specification of input parameters.

def _add_inputs_to_kwargs(args, kwargs, parser):

    inputs = [x for x in [args.global_config, args.fc_dir] + args.run_config
              if x is not None]
    global_config = "bcbio_system.yaml"  # default configuration if not specified
    if kwargs.get("workflow", "") == "template":
        if args.only_metadata:
            inputs.append("--only-metadata")
        if args.force_single:
            inputs.append("--force-single")
        if args.separators:
            inputs.extend(["--separators", args.separators])
        kwargs["inputs"] = inputs
        return kwargs
    elif len(inputs) == 1:
        if os.path.isfile(inputs[0]):
            fc_dir = None
            run_info_yaml = inputs[0]
        else:
            fc_dir = inputs[0]
            run_info_yaml = None
    elif len(inputs) == 2:
        if os.path.isfile(inputs[0]):
            global_config = inputs[0]
            if os.path.isfile(inputs[1]):
                fc_dir = None
                run_info_yaml = inputs[1]
            else:
                fc_dir = inputs[1]
                run_info_yaml = None
        else:
            fc_dir, run_info_yaml = inputs
    elif len(inputs) == 3:
        global_config, fc_dir, run_info_yaml = inputs
    elif args.version:
        print(version.__version__)
        sys.exit()
    else:
        print("Incorrect input arguments", inputs)
        parser.print_help()
        sys.exit()
    if fc_dir:
        fc_dir = os.path.abspath(fc_dir)
    if run_info_yaml:
        run_info_yaml = os.path.abspath(run_info_yaml)
    if kwargs.get("workflow"):
        kwargs["inputs"] = inputs
    kwargs["config_file"] = global_config
    kwargs["fc_dir"] = fc_dir
    kwargs["run_info_yaml"] = run_info_yaml
    return kwargs

def build(self):

        self._cmd_parser.add_argument(
            'install',
            type=str,
            default=None,
            nargs="+",
            help=(""),
        )

        self._cmd_parser.add_argument(
            '-l',
            '--location',
            default=None,
            help=("Specify the installation location. ")
        )

        return super(Cmd, self).build()

Instruction: Given a code description, retrieve the corresponding code.


Question:
Outpoint, hex_string, hex_string, int -> (TxIn, InputWitness)
    Create a signed witness TxIn and InputWitness from a p2wpkh prevout

def p2wpkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE):
    '''

    '''
    return tb.make_witness_input_and_witness(
        outpoint=outpoint,
        sequence=sequence,
        stack=[bytes.fromhex(sig), bytes.fromhex(pubkey)])

func getBlockTxTablesDefinition() types.EventTables {
	return types.EventTables{
		types.SQLBlockTableName: &types.SQLTable{
			Name: types.SQLBlockTableName,
			Columns: []*types.SQLTableColumn{
				{
					Name:    types.SQLColumnLabelHeight,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelBlockHeader,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
			},
		},

		types.SQLTxTableName: &types.SQLTable{
			Name: types.SQLTxTableName,
			Columns: []*types.SQLTableColumn{
				// transaction table
				{
					Name:    types.SQLColumnLabelHeight,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelTxHash,
					Type:    types.SQLColumnTypeVarchar,
					Length:  txs.HashLengthHex,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelIndex,
					Type:    types.SQLColumnTypeNumeric,
					Length:  0,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelTxType,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelEnvelope,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelEvents,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelResult,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelReceipt,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelException,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
			},
		},
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Read implements io.Reader interface. It applies mask given during
// initialization to every read byte.

func (c *CipherReader) Read(p []byte) (n int, err error) {
	n, err = c.r.Read(p)
	ws.Cipher(p[:n], c.mask, c.pos)
	c.pos += n
	return
}

boolean matchComment(
            final boolean blockMatching,
            final int markupLevel, final int markupBlockIndex) {

        checkMarkupLevel(markupLevel);

        if (this.markupSelectorItem.anyLevel() || markupLevel == 0 || (this.prev != null && this.prev.matchedMarkupLevels[markupLevel - 1])) {
            // This text has not matched yet, but might match, so we should check

            this.matchesThisLevel = this.markupSelectorItem.matchesComment(markupBlockIndex, this.markupBlockMatchingCounter);

            if (matchesPreviousOrCurrentLevel(markupLevel)) {
                // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

                if (this.next != null) {
                    return this.next.matchComment(blockMatching, markupLevel, markupBlockIndex);
                }
                return (blockMatching? true : this.matchesThisLevel);

            } else if (this.matchesThisLevel) {
                // This filter was not matched before. So the fact that it matches now means we need to consume it,
                // therefore not delegating.

                return (this.next == null);

            }

        } else if (matchesPreviousOrCurrentLevel(markupLevel)) {
            // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

            if (this.next != null) {
                return this.next.matchComment(blockMatching, markupLevel, markupBlockIndex);
            }
            return blockMatching;

        }

        return false;

    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Convert_v1_NodeVolumeConfig_To_config_NodeVolumeConfig is an autogenerated conversion function.

func Convert_v1_NodeVolumeConfig_To_config_NodeVolumeConfig(in *v1.NodeVolumeConfig, out *config.NodeVolumeConfig, s conversion.Scope) error {
	return autoConvert_v1_NodeVolumeConfig_To_config_NodeVolumeConfig(in, out, s)
}

func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) {
	if volumeID == "" {
		return types.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID}
	}

	var volume types.Volume
	resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return volume, nil, wrapResponseError(err, resp, "volume", volumeID)
	}

	body, err := ioutil.ReadAll(resp.body)
	if err != nil {
		return volume, nil, err
	}
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&volume)
	return volume, body, err
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetRenderedContent sets the RenderedContent field's value.

func (s *RenderUiTemplateOutput) SetRenderedContent(v string) *RenderUiTemplateOutput {
	s.RenderedContent = &v
	return s
}

def add_environment(env, version)
      if self.content_view_environments.where(:environment_id => env.id).empty?
        label = generate_cp_environment_label(env)
        ContentViewEnvironment.create!(:name => label,
                                       :label => label,
                                       :cp_id => generate_cp_environment_id(env),
                                       :environment_id => env.id,
                                       :content_view => self,
                                       :content_view_version => version
                                      )
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Lookup returns a list of handlers with the given
// given type, or nil if none exist

func (r *registry) Lookup(handlerType HandlerType) interface{} {
	if handlerType == Auth {
		return r.filters
	} else if handlerType == Decoration {
		return r.decorators
	} else if handlerType == Endorsement {
		return r.endorsers
	} else if handlerType == Validation {
		return r.validators
	}

	return nil
}

func (m *mux) Handle(method, path string, handle MuxHandler) {
	hthandle := func(rw http.ResponseWriter, req *http.Request, htparams map[string]string) {
		params := req.URL.Query()
		for n, p := range htparams {
			params.Set(n, p)
		}
		handle(rw, req, params)
	}
	m.handles[method+path] = handle
	m.router.Handle(method, path, hthandle)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set a new Customer

@param  \Softpampa\Moip\Payments\Resources\Customers  $customer
@return $this

public function setCustomer($customer)
    {
        $this->data->customer = new stdClass;
        $this->data->customer = $customer;

        return $this;
    }

protected function applyHttpAttributes($http, $postData)
    {
        $postData['protocol_version'] = '1.1';
        $postData['client'] = 'october';

        $postData['server'] = base64_encode(serialize([
            'php'   => PHP_VERSION,
            'url'   => Url::to('/'),
            'since' => PluginVersion::orderBy('created_at')->value('created_at')
        ]));

        if ($projectId = Parameter::get('system::project.id')) {
            $postData['project'] = $projectId;
        }

        if (Config::get('cms.edgeUpdates', false)) {
            $postData['edge'] = 1;
        }

        if ($this->key && $this->secret) {
            $postData['nonce'] = $this->createNonce();
            $http->header('Rest-Key', $this->key);
            $http->header('Rest-Sign', $this->createSignature($postData, $this->secret));
        }

        if ($credentials = Config::get('cms.updateAuth')) {
            $http->auth($credentials);
        }

        $http->noRedirect();
        $http->data($postData);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Validate preference schema
@param {Object} schema
@return {boolean}

function validate(schema) {
        var key, item;
        for (key in schema) {
            if (schema.hasOwnProperty(key)) {
                item = schema[key];
                if (!item.text) {
                    console.error("[PreferenceManager] missing required field: 'text' of '" + key + "'");
                }
                if (!item.type) {
                    console.error("[PreferenceManager] missing required field: 'type' of '" + key + "'");
                }
                if (item.type !== "Section" && typeof item['default'] === "undefined") {
                    console.error("[PreferenceManager] missing required field: 'default' of '" + key + "'");
                }
                if (item.type === "Combo" || item.type === "Dropdown") {
                    if (item.options && item.options.length > 0) {
                        var i, len;
                        for (i = 0, len = item.options.length; i < len; i++) {
                            if (typeof item.options[i].value === "undefined") {
                                console.error("[PreferenceManager] missing required field of option item: 'value' of '" + key + "'");
                            }
                            if (typeof item.options[i].text === "undefined") {
                                console.error("[PreferenceManager] missing required field of option item: 'text' of '" + key + "'");
                            }
                        }
                    } else {
                        console.error("[PreferenceManager] missing required field or no items: 'options' of '" + key + "'");
                    }
                }
            }
        }
        return true;
    }

public void marshall(Sunglasses sunglasses, ProtocolMarshaller protocolMarshaller) {

        if (sunglasses == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(sunglasses.getValue(), VALUE_BINDING);
            protocolMarshaller.marshall(sunglasses.getConfidence(), CONFIDENCE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Module类
@param {String} id      moduleID
@param {Array} deps    依赖模块
@param {Function} factory 工厂函数
@param {Object} root    相对定义的root

function Module(id, deps, factory, root) {
    if (arguments.length === 0) {
        throw new Error('Module: I need a agrument');
    }
    if ($.isFunction(id)) {
        factory = id;
        id = undefined;
        deps = emptyArr;
    } else if ($.isArray(id)) {
        deps = emptyArr;
        id = undefined;
    } else if ($.isFunction(deps)) {
        factory = deps;
        deps = emptyArr;
    }
    this.id = id ? getPath(id)[2] : id;
    this.status = 'uninitialized';
    if ($.isString(deps)) {
        deps = deps.split(',');
    }
    this.dependencies = deps;
    this.factory = factory;
    this.root = root || _; //默认挂靠在window全局，使用_，默认挂靠到MixJS上
    this.undef = []; //没有定义的模块
    this.id && (mapDefined[this.id] = 'uninitialized');
    this.checkDependencies(deps);
    this.define();
}

function createBuilder(name,ftask,builderFunc, tasks, parentBuilderInstance) {
        // create root block
        var builderInstance = {};
        builderInstance.name=name;
        builderInstance.ftask = ftask;
        builderInstance.childs = [];
        builderInstance.parent = parentBuilderInstance; // it can be null

        var rootTask={
            name: "rootTask",
            def: function () { return {}; },
            exec: function (scope, next) {
                if (scope.$$input==null){
                    next({});
                }
                else
                {
                    next(scope.$$input);
                }
            }
        };
        builderInstance.root = createBlock(builderInstance,tasks,null, rootTask,null);

        // we can support for child builder ( fork and join support)
        builderInstance.newInstance = function (name,builderFunc) {
            var newInstance = createBuilder(name,ftask,builderFunc, tasks, builderInstance);
            builderInstance.childs.push(newInstance);
            return newInstance;
        }

        // after end we let use to build the tasks schema
        if (builderFunc!=null){
            builderFunc(builderInstance.root);
        }
        builderInstance.runner=createRunner(builderInstance);

        return builderInstance;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // GetXId get the xid return window and error

func GetXId(xu *xgbutil.XUtil, pid int32) (xproto.Window, error) {
	if xu == nil {
		var err error
		xu, err = xgbutil.NewConn()
		if err != nil {
			// log.Println("xgbutil.NewConn errors is: ", err)
			return 0, err
		}
	}

	xid, err := GetXidFromPid(xu, pid)
	return xid, err
}

void setId(long id)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "setId", new Long(id));

        _consumerId = id;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "setId");
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// You should always use this function to get a new ListAffinityGroupTypesParams instance,
// as then you are sure you have configured all required params

func (s *AffinityGroupService) NewListAffinityGroupTypesParams() *ListAffinityGroupTypesParams {
	p := &ListAffinityGroupTypesParams{}
	p.p = make(map[string]interface{})
	return p
}

def set_matrix(self, X, input_type):
        """"""
        if input_type == 'data':
            self.set_data_matrix(X)
        elif input_type == 'adjacency':
            self.set_adjacency_matrix(X)
        elif input_type == 'affinity':
            self.set_affinity_matrix(X)
        else:
            raise ValueError("Unrecognized input_type: {0}".format(input_type))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Request command status.

    :param blink: Blink instance.
    :param network: Sync module network id.
    :param command_id: Command id to check.

def request_command_status(blink, network, command_id):

    url = "{}/network/{}/command/{}".format(blink.urls.base_url,
                                            network,
                                            command_id)
    return http_get(blink, url)

def cmd(send, msg, args):

    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")

Instruction: Given a code description, retrieve the corresponding code.


Question:
Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.

    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python

def slugify(string):

    string = re.sub('[^\w .-]', '', string)
    string = string.replace(" ", "-")
    return string

public static function slug($string, $separator = '-', array $options = [])
    {
        if (!static::$slugify instanceof Slugify) {
            static::$slugify = Slugify::create($options);
        }

        return mb_strtolower(static::$slugify->slugify($string, $separator));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Update command
@param string $v   segment of command
@param array $arg all others command line argumments

@return string Display user data

function cmdUpdate($v, $arg)
	{
		$report = [];
		$vendors = scandir(self::$vendorDir); //.php/Composer

		foreach($vendors as $vendor){
            		$vendorPath = self::$vendorDir.'/'.$vendor;

            		if ($vendor == '.' || $vendor == '..' || !is_dir($vendorPath)) {
                		continue;
            		}

            		$vendorFiles = scandir($vendorPath); //.php/Composer/devbr

			//varre todos os componentes "DEVBR"
			foreach ($vendorFiles as $componente) {
                		$componentePath = "$vendorPath/$componente"; //.php/Composer/devbr/html

				if ($componente == '.' || $componente == '..' || !is_dir($componentePath)) {
					continue;
				}

				if (is_dir("$componentePath/Config")) {
					//Coping all files (and directorys) in /Config
					$copy = static::copyDirectoryContents("$componentePath/Config", self::$configDir, false, self::$configDir);
                    			$report["$vendor/$componente"] = $copy;

					//Return to application installer
					echo "\n - Install $vendor/$componente:";

                    			//Copied
                    			$copied = count($copy['copied']);
                    			if ($copied > 0) {
                        			echo " $copied file(s) copied.";
                    			}

                    			//Permissions
                    			if (isset($copy['error']['permission'])) {
                        			echo " I can't allow to copy one or more files.";
                    			}

                    			//Files exists
                    			if (isset($copy['error']['overwrite'])) {
                        			echo ' '.($copied > 0 ? 'Some f':'F').'iles already existed.';
                    			}
				}
			}
            echo "\n";
		}

		//Saving a log file
		file_put_contents(self::$configDir.'/install.log.json', json_encode($report, JSON_PRETTY_PRINT));
	}

def _parse_line(self, line_no, line):

        try:
            matched = statement.parseString(line)
        except ParseException as exc:
            raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line)

        if 'symbol' in matched:
            self._parse_cmd(matched)
        elif 'filename' in matched:
            self._parse_include(matched)
        elif 'variable' in matched:
            self._parse_assignment(matched)
        elif 'configvar' in matched:
            self._parse_configvar(matched)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add a new channel to self.channels and initialize its user list.

        Called as event handler for RPL_NAMES events. Do not call directly.

def _add_channel_names(client, e):

        chan = IRCstr(e.channel)
        names = set([IRCstr(n) for n in e.name_list])
        client.channels[chan] = SeshetChannel(chan, names)

func (session *ProxySession) AddParticipant(req ParticipantRequest) (response Participant, exception *Exception, err error) {

	twilioUrl := fmt.Sprintf("%s/%s/%s/%s/%s/%s", ProxyBaseUrl, "Services", session.ServiceSid, "Sessions", session.Sid, "Participants")

	res, err := session.twilio.post(participantFormValues(req), twilioUrl)
	if err != nil {
		return response, exception, err
	}
	defer res.Body.Close()

	responseBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return response, exception, err
	}

	if res.StatusCode != http.StatusCreated {
		exception = new(Exception)
		err = json.Unmarshal(responseBody, exception)

		// We aren't checking the error because we don't actually care.
		// It's going to be passed to the client either way.
		return response, exception, err
	}

	err = json.Unmarshal(responseBody, &response)
	return response, exception, err

}

Instruction: Given a code description, retrieve the corresponding code.


Question:
saves entry to cache

@param string $original     original string
@param array  $translations translations

@return void

private function saveToCache($original, $translations)
    {
        $cacheKey = $this->getCacheKey($original);
        $cacheContent = $this->cache->fetch($cacheKey);
        if (is_array($cacheContent)) {
            $cacheContent[$original] = $translations;
        } else {
            $cacheContent = [$original => $translations];
        }

        $this->cache->save($cacheKey, $cacheContent);
    }

public function format(ParameterBag $trackingParameters)
    {
        $cu = null;

        if (
            $trackingParameters->has('c')
            && $trackingParameters->has('u')
        ) {
            $cu = sprintf(
                '%s~%s',
                $trackingParameters->get('c'),
                $trackingParameters->get('u')
            );
        }

        return [
            'cu' => $cu,
        ];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// fileCreateNotification creates FSNotifications from paths for file
// create events.

func fileCreateNotification(file data.Path, writer keybase1.UID,
	localTime time.Time) *keybase1.FSNotification {
	n := baseFileEditNotification(file, writer, localTime)
	n.NotificationType = keybase1.FSNotificationType_FILE_CREATED
	return n
}

public function setWebHook($url)
    {
        $this->data->notification = new stdClass;
        $this->data->notification->webhook = new stdClass;
        $this->data->notification->webhook->url = $url;

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a predicate for checking whether an object has a given
        set of `key:value` pairs.

def matches(self):

        def ret(obj, *args):
            if self.obj is obj:
                return True  # avoid comparing an object to itself.

            for key in self.obj:
                if self.obj[key] != obj[key]:
                    return False

            return True

        return self._wrap(ret)

function() {
      var designSet = this._designSet;

      if (this.type in designSet.value) {
        var designType = designSet.value[this.type];

        if ('decorate' in designSet.value[this.type]) {
          this.isDecorated = true;
        } else {
          this.isDecorated = false;
        }

        if (this.name in designSet.property) {
          this.isMultiValue = ('multiValue' in designSet.property[this.name]);
          this.isStructuredValue = ('structuredValue' in designSet.property[this.name]);
        }
      }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScaleStatus.

func (in *ScaleStatus) DeepCopy() *ScaleStatus {
	if in == nil {
		return nil
	}
	out := new(ScaleStatus)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// handleSingleHistogramUpdate updates the Histogram and CM Sketch using these feedbacks. All the feedbacks for
// the same index or column are gathered in `rows`.

func (h *Handle) handleSingleHistogramUpdate(is infoschema.InfoSchema, rows []chunk.Row) (err error) {
	physicalTableID, histID, isIndex := rows[0].GetInt64(0), rows[0].GetInt64(1), rows[0].GetInt64(2)
	defer func() {
		if err == nil {
			err = errors.Trace(h.deleteOutdatedFeedback(physicalTableID, histID, isIndex))
		}
	}()
	h.mu.Lock()
	table, ok := h.getTableByPhysicalID(is, physicalTableID)
	h.mu.Unlock()
	// The table has been deleted.
	if !ok {
		return nil
	}
	var tbl *statistics.Table
	if table.Meta().GetPartitionInfo() != nil {
		tbl = h.GetPartitionStats(table.Meta(), physicalTableID)
	} else {
		tbl = h.GetTableStats(table.Meta())
	}
	var cms *statistics.CMSketch
	var hist *statistics.Histogram
	if isIndex == 1 {
		idx, ok := tbl.Indices[histID]
		if ok && idx.Histogram.Len() > 0 {
			idxHist := idx.Histogram
			hist = &idxHist
			cms = idx.CMSketch.Copy()
		}
	} else {
		col, ok := tbl.Columns[histID]
		if ok && col.Histogram.Len() > 0 {
			colHist := col.Histogram
			hist = &colHist
		}
	}
	// The column or index has been deleted.
	if hist == nil {
		return nil
	}
	q := &statistics.QueryFeedback{}
	for _, row := range rows {
		err1 := statistics.DecodeFeedback(row.GetBytes(3), q, cms, mysql.HasUnsignedFlag(hist.Tp.Flag))
		if err1 != nil {
			logutil.Logger(context.Background()).Debug("decode feedback failed", zap.Error(err))
		}
	}
	err = h.dumpStatsUpdateToKV(physicalTableID, isIndex, q, hist, cms)
	return errors.Trace(err)
}

def on_data(self, raw_data):

        try:
            data = json.loads(raw_data)
        except ValueError:
            logger.error('value error: %s' % raw_data)
            return

        unique_id = data.get('id')

        if self._error_handler(data, unique_id):
            return False

        operation = data['op']
        if operation == 'connection':
            self._on_connection(data, unique_id)
        elif operation == 'status':
            self._on_status(data, unique_id)
        elif operation in ['mcm', 'ocm']:
            # historic data does not contain unique_id
            if self.stream_unique_id not in [unique_id, 'HISTORICAL']:
                logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
                               (unique_id, self.stream_unique_id))
                return
            self._on_change_message(data, unique_id)

Instruction: Given a code description, retrieve the corresponding code.


Question: // NeedValue indicates whether the aggregate function should record value.

func NeedValue(name string) bool {
	switch name {
	case ast.AggFuncSum, ast.AggFuncAvg, ast.AggFuncFirstRow, ast.AggFuncMax, ast.AggFuncMin,
		ast.AggFuncGroupConcat, ast.AggFuncBitOr, ast.AggFuncBitAnd, ast.AggFuncBitXor:
		return true
	default:
		return false
	}
}

func (db *DB) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result {
	return MustExecContext(ctx, db, query, args...)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Sort the elements in the specified List according to their natural order.

public static <T extends Comparable<? super T>> void sort (List<T> a)
    {
        sort(a, new Comparator<T>() {
            public int compare (T o1, T o2) {
                if (o1 == o2) { // catches null == null
                    return 0;
                } else if (o1 == null) {
                    return 1;
                } else if (o2 == null) {
                    return -1;
                }
                return o1.compareTo(o2); // null-free
            }
        });
    }

public static <T extends Iterable<U>, U> Comparator<T> lexComparator(Comparator<U> elemComp) {
        return new LexComparator<>(elemComp);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Trim tags in the dom.

@param SimpleHtmlDom $element

@return void

private function removeWhitespaceAroundTags(SimpleHtmlDom $element)
    {
        if (isset(self::$trimWhitespaceFromTags[$element->tag])) {
            $node = $element->getNode();

            /** @var \DOMNode[] $candidates */
            $candidates = [];
            if ($node->childNodes->length > 0) {
                $candidates[] = $node->firstChild;
                $candidates[] = $node->lastChild;
                $candidates[] = $node->previousSibling;
                $candidates[] = $node->nextSibling;
            }

            foreach ($candidates as &$candidate) {
                if ($candidate === null) {
                    continue;
                }

                if ($candidate->nodeType === \XML_TEXT_NODE) {
                    $candidate->nodeValue = \preg_replace(self::$regExSpace, ' ', $candidate->nodeValue);
                }
            }
        }
    }

function strip(html) {
        var tmp = document.createElement('DIV');
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || '';
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
获得组件中现存的指定的fix类型组件
@param which [0,1,2,3]，0-3的整数的数组，对应上，右，下，左
@returns {Array}，[nodeTop, nodeRight, nodeBottom, nodeLeft]，返回获取到的dom节点，如果该位置没有节点则返回 undefined

function (which) {
        var top = document.getElementsByClassName('RRFixTop'),
            right = document.getElementsByClassName('RRFixRight'),
            bottom = document.getElementsByClassName('RRFixBottom'),
            left = document.getElementsByClassName('RRFixLeft');
        if (top && top.length > 1) {
            console.error('fixes的元素同一方向只允许存在一个，top方向有多个fixes元素存在')
        }
        if (right && right.length > 1) {
            console.error('fixes的元素同一方向只允许存在一个，right方向有多个fixes元素存在')
        }
        if (bottom && bottom.length > 1) {
            console.error('fixes的元素同一方向只允许存在一个，bottom方向有多个fixes元素存在')
        }
        if (left && left.length > 1) {
            console.error('fixes的元素同一方向只允许存在一个，left方向有多个fixes元素存在')
        }
        var getF = function (node, i) {
            switch (i) {
                case 0:
                    node[0] = top[0] || false;
                    break;
                case 1:
                    node[1] = right[0] || false;
                    break;
                case 2:
                    node[2] = bottom[0] || false;
                    break;
                case 3:
                    node[3] = left[0] || false;
                    break;
                default:
                    throw new Error('方法：getFixes，参数：which，是个只能包含0-3之间整数的数组，或者为空')
            }
        };
        var node = [];
        if (which && which.length > 0) {
            for (var a = 0; a < which.length; a++) {
                getF(node, which[a])
            }
        } else {
            var _witch = [0, 1, 2, 3];
            for (var b = 0; b < _witch.length; b++) {
                getF(node, _witch[b])
            }
        }
        return node;
    }

function grouped(array, groups, order) {
  if (!groups) { groups = [returnFalse]; }
  var sorted = [];
  var ordered = [];
  var remaining = array.slice();
  var unmatchedPosition = groups.indexOf('unmatched');
  groups.forEach(function(criteria, index) {
    if (index === unmatchedPosition) { return; }
    var tieBreakers = [];
    if (index !== groups.length - 1) {
      tieBreakers = groups.slice(index + 1);
      if (index < unmatchedPosition) {
        tieBreakers.splice(unmatchedPosition - index - 1, 1);
      }
    }
    var spliced = splice(remaining, criteria, tieBreakers);
    var matched = spliced.matched;
    var unmatched = spliced.unmatched;
    sorted[index] = matched;
    remaining = unmatched;
  });
  if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
  sorted[unmatchedPosition] = remaining;
  if (Array.isArray(order)) {
    order.forEach(function(position, index) {
      ordered[index] = sorted[position];
    });
  } else {
    ordered = sorted;
  }
  return ordered.reduce(function(flat, group) {
    return flat.concat(group);
  }, []);
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Gets the MIME type of the embedded or inline image
@param string File extension
@access public
@return string MIME type of ext
@static

public static function _mime_types($ext = '')
    {
        $mimes = array(
            'hqx'   => 'application/mac-binhex40',
            'cpt'   => 'application/mac-compactpro',
            'doc'   => 'application/msword',
            'bin'   => 'application/macbinary',
            'dms'   => 'application/octet-stream',
            'lha'   => 'application/octet-stream',
            'lzh'   => 'application/octet-stream',
            'exe'   => 'application/octet-stream',
            'class' => 'application/octet-stream',
            'psd'   => 'application/octet-stream',
            'so'    => 'application/octet-stream',
            'sea'   => 'application/octet-stream',
            'dll'   => 'application/octet-stream',
            'oda'   => 'application/oda',
            'pdf'   => 'application/pdf',
            'ai'    => 'application/postscript',
            'eps'   => 'application/postscript',
            'ps'    => 'application/postscript',
            'smi'   => 'application/smil',
            'smil'  => 'application/smil',
            'mif'   => 'application/vnd.mif',
            'xls'   => 'application/vnd.ms-excel',
            'ppt'   => 'application/vnd.ms-powerpoint',
            'wbxml' => 'application/vnd.wap.wbxml',
            'wmlc'  => 'application/vnd.wap.wmlc',
            'dcr'   => 'application/x-director',
            'dir'   => 'application/x-director',
            'dxr'   => 'application/x-director',
            'dvi'   => 'application/x-dvi',
            'gtar'  => 'application/x-gtar',
            'php'   => 'application/x-httpd-php',
            'php4'  => 'application/x-httpd-php',
            'php3'  => 'application/x-httpd-php',
            'phtml' => 'application/x-httpd-php',
            'phps'  => 'application/x-httpd-php-source',
            'js'    => 'application/x-javascript',
            'swf'   => 'application/x-shockwave-flash',
            'sit'   => 'application/x-stuffit',
            'tar'   => 'application/x-tar',
            'tgz'   => 'application/x-tar',
            'xhtml' => 'application/xhtml+xml',
            'xht'   => 'application/xhtml+xml',
            'zip'   => 'application/zip',
            'mid'   => 'audio/midi',
            'midi'  => 'audio/midi',
            'mpga'  => 'audio/mpeg',
            'mp2'   => 'audio/mpeg',
            'mp3'   => 'audio/mpeg',
            'aif'   => 'audio/x-aiff',
            'aiff'  => 'audio/x-aiff',
            'aifc'  => 'audio/x-aiff',
            'ram'   => 'audio/x-pn-realaudio',
            'rm'    => 'audio/x-pn-realaudio',
            'rpm'   => 'audio/x-pn-realaudio-plugin',
            'ra'    => 'audio/x-realaudio',
            'rv'    => 'video/vnd.rn-realvideo',
            'wav'   => 'audio/x-wav',
            'bmp'   => 'image/bmp',
            'gif'   => 'image/gif',
            'jpeg'  => 'image/jpeg',
            'jpg'   => 'image/jpeg',
            'jpe'   => 'image/jpeg',
            'png'   => 'image/png',
            'tiff'  => 'image/tiff',
            'tif'   => 'image/tiff',
            'css'   => 'text/css',
            'html'  => 'text/html',
            'htm'   => 'text/html',
            'shtml' => 'text/html',
            'txt'   => 'text/plain',
            'text'  => 'text/plain',
            'log'   => 'text/plain',
            'rtx'   => 'text/richtext',
            'rtf'   => 'text/rtf',
            'xml'   => 'text/xml',
            'xsl'   => 'text/xml',
            'mpeg'  => 'video/mpeg',
            'mpg'   => 'video/mpeg',
            'mpe'   => 'video/mpeg',
            'qt'    => 'video/quicktime',
            'mov'   => 'video/quicktime',
            'avi'   => 'video/x-msvideo',
            'movie' => 'video/x-sgi-movie',
            'doc'   => 'application/msword',
            'word'  => 'application/msword',
            'xl'    => 'application/excel',
            'eml'   => 'message/rfc822',
        );
        return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
    }

protected function _getUploadInfoString() {
        $maxFileSize = $this->getUploadMaxFilesize();
        $allowedExtensions = $this->getAllowedExtensions();
        $lastExtension = array_pop($allowedExtensions);

        $translator = $this->getTranslator();
        $uploadInfoStr = $translator->translate('Only %1$s and %2$s files with a maximum of %3$s MB are allowed');
        $uploadInfoStr = sprintf($uploadInfoStr, implode(', ', $allowedExtensions), $lastExtension, $maxFileSize);

        return $uploadInfoStr;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Store and return packages for install

def store(self, packages):

        dwn, install, comp_sum, uncomp_sum = ([] for i in range(4))
        # name = data[0]
        # location = data[1]
        # size = data[2]
        # unsize = data[3]
        for pkg in packages:
            for pk, loc, comp, uncomp in zip(self.data[0], self.data[1],
                                             self.data[2], self.data[3]):
                if (pk and pkg == split_package(pk)[0] and
                        pk not in install and
                        split_package(pk)[0] not in self.blacklist):
                    dwn.append("{0}{1}/{2}".format(self.mirror, loc, pk))
                    install.append(pk)
                    comp_sum.append(comp)
                    uncomp_sum.append(uncomp)
        if not install:
            for pkg in packages:
                for pk, loc, comp, uncomp in zip(self.data[0], self.data[1],
                                                 self.data[2], self.data[3]):
                    name = split_package(pk)[0]
                    if (pk and pkg in name and name not in self.blacklist):
                        self.matching = True
                        dwn.append("{0}{1}/{2}".format(self.mirror, loc, pk))
                        install.append(pk)
                        comp_sum.append(comp)
                        uncomp_sum.append(uncomp)
        dwn.reverse()
        install.reverse()
        comp_sum.reverse()
        uncomp_sum.reverse()
        if self.repo == "slack":
            dwn, install, comp_sum, uncomp_sum = self.patches(dwn, install,
                                                              comp_sum,
                                                              uncomp_sum)
        return [dwn, install, comp_sum, uncomp_sum]

function Resource( pkg, config ) {
	var key;

	// Properties
	this.pkg = pkg;
	this.config = {};

	// Initialization
	for ( key in config ) {
		if ( Object.prototype.hasOwnProperty.call( config, key ) ) {
			this.config[key] = config[key];
		}
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Return a numeric ordering for a model name.

def get_cms_model_order(model_name):

    for (name, order) in iteritems(appsettings.FLUENT_DASHBOARD_CMS_MODEL_ORDER):
        if name in model_name:
            return order
    return 999

protected function set_new_sortorder() {
        $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid'));
        $this->raw_set('sortorder', $this->count_records($search));
    }

Instruction: Given a code description, retrieve the corresponding code.