Question:
Create stream.

@param scope           scope.
@param stream          stream name.
@param config          stream configuration.
@param createTimestamp creation timestamp.
@return creation status.

@Task(name = "createStream", version = "1.0", resource = "{scope}/{stream}")
    public CompletableFuture<CreateStreamStatus.Status> createStream(String scope, String stream, StreamConfiguration config, long createTimestamp) {
        return execute(
                new Resource(scope, stream),
                new Serializable[]{scope, stream, config, createTimestamp},
                () -> createStreamBody(scope, stream, config, createTimestamp));
    }

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:
Returns a dict of lists for all :class:`~plexapi.settings.Setting`
            objects grouped by setting group.

def groups(self):

        groups = defaultdict(list)
        for setting in self.all():
            groups[setting.group].append(setting)
        return dict(groups)

def _get_setup(self, result):
        """"""
        self.__devices = {}

        if ('setup' not in result.keys() or
                'devices' not in result['setup'].keys()):
            raise Exception(
                "Did not find device definition.")

        for device_data in result['setup']['devices']:
            device = Device(self, device_data)
            self.__devices[device.url] = device

        self.__location = result['setup']['location']
        self.__gateway = result['setup']['gateways']

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


Question:
{@inheritdoc}

@see \Concrete\Core\Attribute\ObjectInterface::getAttributeValueObject()

@return \Concrete\Core\Entity\Attribute\Value\SiteValue|null

public function getAttributeValueObject($ak, $createIfNotExists = false)
    {
        $result = null;
        if (!is_object($ak)) {
            $ak = SiteKey::getAttributeKeyByHandle($ak);
        }
        if ($ak !== null) {
            $result = $this->getObjectAttributeCategory()->getAttributeValue($ak, $this);
            if ($result === null && $createIfNotExists) {
                $result = new SiteValue();
                $result->setSite($this);
                $result->setAttributeKey($ak);
            }
        }

        return $result;
    }

public function doSetValue($value)
    {
        $items = $value;
        if ($value instanceof PropertyValue) {
            $items = $value->getValue();
        }

        if (null == $items) {
            return;
        }

        // check value for single value
        if (array_keys($items) !== range(0, count($items) - 1)) {
            $items = [$items];
        }

        $this->properties = [];

        for ($i = 0; $i < count($items); ++$i) {
            $item = $items[$i];
            $type = $this->initProperties($i, $item['type']);

            /** @var PropertyInterface $subProperty */
            foreach ($type->getChildProperties() as $subProperty) {
                if (!isset($item[$subProperty->getName()])) {
                    continue;
                }

                $subName = $subProperty->getName();
                $subValue = $item[$subName];

                if ($subValue instanceof PropertyValue) {
                    $subValueProperty = new PropertyValue($subName, $subValue);
                    $subProperty->setPropertyValue($subValueProperty);
                    $item[$subName] = $subValueProperty;
                } else {
                    $subProperty->setValue($subValue);
                }
            }

            $items[$i] = $item;
        }

        if ($value instanceof PropertyValue) {
            $value->setValue($items);
        }
    }

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


Question:
<p>
The recurring price charged to run this reserved DB instance.
</p>

@param recurringCharges
The recurring price charged to run this reserved DB instance.

public void setRecurringCharges(java.util.Collection<RecurringCharge> recurringCharges) {
        if (recurringCharges == null) {
            this.recurringCharges = null;
            return;
        }

        this.recurringCharges = new com.amazonaws.internal.SdkInternalList<RecurringCharge>(recurringCharges);
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question: Overridden `apply_filter` to perform tasks for hierarchy child

def apply_filter(self, *args, **kwargs):
        """"""
        if self.filter is not None:
            # make sure self.filter knows about root manual indices
            self.filter.retrieve_manual_indices()

        # Copy event data from hierarchy parent
        self.hparent.apply_filter()
        # update event index
        event_count = np.sum(self.hparent._filter)
        self._events = {}
        self._events["index"] = np.arange(1, event_count + 1)
        # set non-scalar column data
        if "contour" in self.hparent:
            self._events["contour"] = ChildContour(self)
        if "image" in self.hparent:
            self._events["image"] = ChildImage(self)
        if "mask" in self.hparent:
            self._events["mask"] = ChildMask(self)
        if "trace" in self.hparent:
            trdict = {}
            for flname in dfn.FLUOR_TRACES:
                if flname in self.hparent["trace"]:
                    trdict[flname] = ChildTrace(self, flname)
            self._events["trace"] = trdict
        # update config
        self.config["experiment"]["event count"] = event_count

        self._init_filters()
        super(RTDC_Hierarchy, self).apply_filter(*args, **kwargs)

def default_action_block
      proc do
        begin
          record = if resource.singular
                    parent_model = resource.parent.model.find(parent_resource_id)
                    parent_model.send resource.name
                  else
                    record = model.find(params[:id])
                  end

          record.update(instance_eval(&@strong_params))
          body record.reload
        rescue ActionController::ParameterMissing => error
          body error.message
          status :bad_request
        end
      end
    end

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


Question: // Inverse S-Box 5

func (bb BoundingBox) Equals(test BoundingBox) bool {
	bblen := len(bb)
	testlen := len(test)
	if (bblen == 0) && (testlen == 0) {
		return true
	}
	if (bblen == 0) || (testlen == 0) || (bblen != testlen) {
		return false
	}
	for inx := 0; inx < bblen; inx++ {
		if bb[inx] != test[inx] {
			return false
		}
	}
	return true
}

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


Question: Retrieves instances of the TestRule and MethodRule classes

private List<Object> getRuleInstances(Object testInstance) throws Exception {
        List<Object> ruleInstances = new ArrayList<Object>();

        List<Field> fieldsWithRuleAnnotation =
            SecurityActions.getFieldsWithAnnotation(testInstance.getClass(), Rule.class);
        if (fieldsWithRuleAnnotation.isEmpty()) {
            List<Method> methodsWithAnnotation =
                SecurityActions.getMethodsWithAnnotation(testInstance.getClass(), Rule.class);
            if (methodsWithAnnotation.isEmpty()) {
                // there isn't any rule in the test class
                return null;
            } else {
                log.warning("Please note that methods annotated with @Rule are not fully supported in Arquillian. "
                    + "Specifically, if you want to enrich a field in your Rule implementation class.");

                return ruleInstances;
            }
        } else {
            for (Field field : fieldsWithRuleAnnotation) {
                Object fieldInstance = field.get(testInstance);
                if (isRule(fieldInstance)) {
                    ruleInstances.add(fieldInstance);
                }
            }
        }
        return ruleInstances;
    }

public function add_rules( array $rules ) {
		foreach ( $rules as $name => $rule ) {
			$this->add_rule( $name, $rule );
		}

		return $this;
	}

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


Question:
creates a base def object
@param info
@returns {{type: [null]}}

function baseDef (info) {
  const { name, isList, isNonNull } = info
  const def = {
    type: isList ? [ name ] : name
  }
  if (isNonNull) def.nullable = false
  return def
}

def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None):
        '''
        '''
        rows = number_of_rows
        conn = self.database_caller_creator(name)

        if custom:
            self.custom_db_creator(rows, conn, custom)
            conn.close()
            sys.exit(0)

        self.data_filler_simple_registration(rows, conn)
        self.data_filler_detailed_registration(rows, conn)
        self.data_filler_company(rows, conn)
        self.data_filler_user_agent(rows, conn)
        self.data_filler_customer(rows, conn)
        conn.close()

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


Question:
rightscale requires arrays in query parameters to have no index,
ex: tag[]=deploy:type=testing&tag[]=deploy:type=production

private function prepareQuery($params = []) {
		if(!is_array($params)) {
			return $params;
		}

		$query = [];

		foreach($params as $key => $value) {
			if(is_array($value)) {
				foreach($value as $element) {
					$query[] = sprintf(
						'%s[]=%s',
						$key,
						urlencode($element)
					);
				}
			} else {
				$query[] = sprintf(
					'%s=%s',
					$key,
					urlencode($value)
				);
			}
		}

		return implode("&",$query);
	}

@Override
    public Request<ReplaceRouteTableAssociationRequest> getDryRunRequest() {
        Request<ReplaceRouteTableAssociationRequest> request = new ReplaceRouteTableAssociationRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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


Question: If the count is zero schedule a new fast

function pingServer(_self, _server, cb) {
      // Measure running time
      var start = new Date().getTime();

      // Emit the server heartbeat start
      emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name });

      // Execute ismaster
      _server.command(
        'admin.$cmd',
        {
          ismaster: true
        },
        {
          monitoring: true,
          socketTimeout: self.s.options.connectionTimeout || 2000
        },
        function(err, r) {
          if (self.state === DESTROYED || self.state === UNREFERENCED) {
            // Move from connectingProxies
            moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server);
            _server.destroy();
            return cb(err, r);
          }

          // Calculate latency
          var latencyMS = new Date().getTime() - start;

          // We had an error, remove it from the state
          if (err) {
            // Emit the server heartbeat failure
            emitSDAMEvent(self, 'serverHeartbeatFailed', {
              durationMS: latencyMS,
              failure: err,
              connectionId: _server.name
            });
            // Move from connected proxies to disconnected proxies
            moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server);
          } else {
            // Update the server ismaster
            _server.ismaster = r.result;
            _server.lastIsMasterMS = latencyMS;

            // Server heart beat event
            emitSDAMEvent(self, 'serverHeartbeatSucceeded', {
              durationMS: latencyMS,
              reply: r.result,
              connectionId: _server.name
            });
          }

          cb(err, r);
        }
      );
    }

def reset(self):

        self.counter += 1
        local_counter = self.counter

        def timer_timeout():
            if self.counter == local_counter and self.running:
                self.callback()

        self.loop.call_later(self.timeout, timer_timeout)

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


Question: // Removes the state from the set, if count decrs to 0

func (sis *SortedIntSet) decr(num int) {
	if sis.useTreeMap {
		count, ok := sis.dict[num]
		assert(ok)
		if count == 1 {
			delete(sis.dict, num)
			// Fall back to simple arrays once we touch zero again
			if len(sis.dict) == 0 {
				sis.useTreeMap = false
				sis.values = sis.values[:0] // reuse slice
				sis.counts = sis.counts[:0] // reuse slice
			}
		} else {
			sis.dict[num] = count - 1
		}
		return
	}

	for i, v := range sis.values {
		if v == num {
			sis.counts[i]--
			if sis.counts[i] == 0 {
				limit := len(sis.values) - 1
				if i < limit {
					sis.values = append(sis.values[:i], sis.values[i+1:]...)
					sis.counts = append(sis.counts[:i], sis.counts[i+1:]...)
				} else {
					sis.values = sis.values[:i]
					sis.counts = sis.counts[:i]
				}
			}
			return
		}
	}

	panic("should not be here!")
}

public function set(array $data, $id = null) {
        $id = null === $id ? $this->idGen++ : $id;
        $this->data[$id] = $data;
        self::$dirty[$this->class] = true;
        return $id;
    }

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


Question:
Read properties file.

@param fileName the file name
@return the properties

public static Properties readPropertiesFile(String fileName) {
		InputStream in = getInputStream(fileName);
		if (in != null) {
			return readPropertiesStream(in);
		}
		return new Properties();
	}

private function parseParameters(\DOMDocument $xml, $file)
    {
        if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) {
            $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter', $file));
        }
    }

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


Question:
Create a multiple set bind with a varargs list of pattern variables, like a,b,c in set S. This is used by several
obligations.

protected PMultipleBind getMultipleSetBind(PExp setExp,
			ILexNameToken... patternNames)
	{
		ASetMultipleBind setBind = new ASetMultipleBind();
		List<PPattern> patternList = new Vector<PPattern>();

		for (ILexNameToken patternName : patternNames)
		{
			AIdentifierPattern pattern = new AIdentifierPattern();
			pattern.setName(patternName.clone());
			patternList.add(pattern);
		}

		setBind.setPlist(patternList);
		setBind.setSet(setExp.clone());

		return setBind;
	}

public function httpMkCalendar(RequestInterface $request, ResponseInterface $response)
    {
        $body = $request->getBodyAsString();
        $path = $request->getPath();

        $properties = [];

        if ($body) {
            try {
                $mkcalendar = $this->server->xml->expect(
                    '{urn:ietf:params:xml:ns:caldav}mkcalendar',
                    $body
                );
            } catch (\Sabre\Xml\ParseException $e) {
                throw new BadRequest($e->getMessage(), 0, $e);
            }
            $properties = $mkcalendar->getProperties();
        }

        // iCal abuses MKCALENDAR since iCal 10.9.2 to create server-stored
        // subscriptions. Before that it used MKCOL which was the correct way
        // to do this.
        //
        // If the body had a {DAV:}resourcetype, it means we stumbled upon this
        // request, and we simply use it instead of the pre-defined list.
        if (isset($properties['{DAV:}resourcetype'])) {
            $resourceType = $properties['{DAV:}resourcetype']->getValue();
        } else {
            $resourceType = ['{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar'];
        }

        $this->server->createCollection($path, new MkCol($resourceType, $properties));

        $response->setStatus(201);
        $response->setHeader('Content-Length', 0);

        // This breaks the method chain.
        return false;
    }

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


Question: Generator that yields data for selection paste

def selection_paste_data_gen(self, selection, data, freq=None):
        """"""

        (bb_top, bb_left), (bb_bottom, bb_right) = \
            selection.get_grid_bbox(self.grid.code_array.shape)
        bbox_height = bb_bottom - bb_top + 1
        bbox_width = bb_right - bb_left + 1

        for row, row_data in enumerate(itertools.cycle(data)):
            # Break if row is not in selection bbox
            if row >= bbox_height:
                break

            # Duplicate row data if selection is wider than row data
            row_data = list(row_data)
            duplicated_row_data = row_data * (bbox_width // len(row_data) + 1)
            duplicated_row_data = duplicated_row_data[:bbox_width]

            for col in xrange(len(duplicated_row_data)):
                if (bb_top, bb_left + col) not in selection:
                    duplicated_row_data[col] = None

            yield duplicated_row_data

function getInputExcerpt(input, pos, len) {
  var excerpt = asEscapedString(input.slice(pos, pos + len));

  // Pad the output if necessary.
  if (excerpt.length < len) {
    return excerpt + common.repeat(' ', len - excerpt.length).join('');
  }
  return excerpt;
}

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


Question:
Load current state into an array of data

@return array

protected function getState()
    {
        $data = [];
        foreach ($this->serialisedProperties as $property) {
            $data[$property] = $this->$property;
        }
        return $data;
    }

function(next) {
        var source = config.getSource(asset.source);

        async.parallel([
          getFromSource.bind(null, source, asset, fromVersion, config),
          getFromSource.bind(null, source, asset, toVersion, config)
        ], next);
      }

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


Question: // peek returns the next rune without advancing the reader.

func (s *Scanner) peek() rune {
	peek, _, err := s.buf.ReadRune()
	if err != nil {
		return eof
	}

	s.buf.UnreadRune()
	return peek
}

def _worker(self):
        """"""
        while self.working:
            try:
                genome_id, genome, config = self.inqueue.get(
                    block=True,
                    timeout=0.2,
                    )
            except queue.Empty:
                continue
            f = self.eval_function(genome, config)
            self.outqueue.put((genome_id, genome, f))

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


Question: :meth:`.WNetworkNativeTransportProto.bind_socket` method implementation

def bind_socket(self, config):

		address = config[self.__bind_socket_config.section][self.__bind_socket_config.address_option]
		port = config.getint(self.__bind_socket_config.section, self.__bind_socket_config.port_option)
		return WIPV4SocketInfo(address, port)

def send_packet(self):
        """"""
        waiter, packet = self.client.waiters.popleft()
        self.logger.debug('sending packet: %s', binascii.hexlify(packet))
        self.client.active_transaction = waiter
        self.client.in_transaction = True
        self.client.active_packet = packet
        self.reset_cmd_timeout()
        self.transport.write(packet)

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


Question:
Execute console command.

@param \Symfony\Component\Console\Input\InputInterface   $input
@param \Symfony\Component\Console\Output\OutputInterface $output

@return void

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $migrationsTemplate = base_path().'/storage/migrations';
        $migration = $input->getArgument('migration');

        $file = file($migrationsTemplate);
        $items = '';
        $goahead = false;
        foreach ($file as $fn) {
            $item = $fn;
            $nameexp = explode('_', $item);

            for ($i = 0; $i < 4; $i++) {
                array_shift($nameexp);
            }

            foreach ($nameexp as $key => $i) {
                $nameexp[$key] = ucwords($i);
            }

            $name = str_replace('_', '', str_replace('.php', '', implode('_', $nameexp)));

            $path = base_path().'/database/'.$item;

            if (file_exists(trim($path))) {
                if (empty($migration)) {
                    $goahead = true;
                } else {
                    if ($migration == trim($name)) {
                        $goahead = true;
                    }
                }

                if ($goahead) {
                    // update migrations table
                    if ($this->isMigrated($item, $output)) {
                        $output->writeln('Item: '.trim($name).' is already pushed to the database');
                    } else {
                        $output->writeln('Migrating '.trim($name).' migration');
                        require_once trim($path);
                        $class = '\\'.trim($name);
                        $c = new $class();
                        $c->up();
                        $this->changeMigrationTable($item);
                    }
                }
            }
        }
    }

public SassValue invoke(List<?> arguments) {
    try {
      ArrayList<Object> values = new ArrayList<>(argumentConverters.size());

      for (ArgumentConverter argumentConverter : argumentConverters) {
        Object value = argumentConverter.convert(arguments, importStack, context);
        values.add(value);
      }

      Object result = method.invoke(object, values.toArray());

      return TypeUtils.convertToSassValue(result);
    } catch (Throwable throwable) {
      StringWriter stringWriter = new StringWriter();
      PrintWriter printWriter = new PrintWriter(stringWriter);

      String message = throwable.getMessage();
      if (StringUtils.isNotEmpty(message)) {
        printWriter.append(message).append(System.lineSeparator());
      }
      throwable.printStackTrace(printWriter);

      return new SassError(stringWriter.toString());
    }
  }

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


Question:
Use StatusSync to dynamically add the available
data urls to poll new data from.

@param \Vatsimphp\Sync\StatusSync $sync
@param string                     $type - the type of urls to use (ie dataUrls)

@throws \Vatsimphp\Exception\RuntimeException

public function registerUrlFromStatus(\Vatsimphp\Sync\StatusSync $sync, $type)
    {
        $urls = $sync->loadData()->get($type)->toArray();
        if (empty($urls)) {
            throw new RuntimeException(
                'Error loading urls from StatusSync'
            );
        }
        $this->registerUrl($urls, true);

        return true;
    }

def do_login(self, http_session):

        response = http_session.get(self.LOGIN_URL)
        action_url = parse_form_action_url(response.text)

        # Stop login it action url is not found
        if not action_url:
            logger.debug(response.text)
            raise VkParseError("Can't parse form action url")

        login_form_data = {'email': self._login, 'pass': self._password}
        login_response = http_session.post(action_url, login_form_data)
        logger.debug('Cookies: %s', http_session.cookies)

        response_url_query = parse_url_query_params(
            login_response.url, fragment=False)

        logger.debug('response_url_query: %s', response_url_query)
        act = response_url_query.get('act')

        # Check response url query params firstly
        if 'sid' in response_url_query:
            self.require_auth_captcha(
                response=login_response,
                query_params=response_url_query,
                login_form_data=login_form_data,
                http_session=http_session)

        elif act == 'authcheck':
            self.require_2fa(html=login_response.text,
                             http_session=http_session)

        elif act == 'security_check':
            self.require_phone_number(html=login_response.text,
                                      session=http_session)

        session_cookies = ('remixsid' in http_session.cookies,
                           'remixsid6' in http_session.cookies)
        if any(session_cookies):
            logger.info('VK session is established')
            return True
        else:
            message = 'Authorization error: incorrect password or ' \
                      'authentication code'
            logger.error(message)
            raise VkAuthError(message)

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


Question:
Validates the `validatable` object based on it's validation rules.

@return bool true if the object is valid, false otherwise.
@throws NostoException if the rule validator is not found.

public function validate()
    {
        $valid = true;
        foreach ($this->object->validationRules() as $rule) {
            if (isset($rule[0], $rule[1])) {
                $properties = $rule[0];
                $validator = 'validate' . $rule[1];
                if (!method_exists($this, $validator)) {
                    throw new NostoException(sprintf(
                        'Nosto validator "%s" does not exist.',
                        $validator
                    ));
                }
                $params = array_merge(array($properties), array_slice($rule, 2));
                $isValid = call_user_func_array(array($this, $validator), $params);
                if (!$isValid) {
                    $valid = false;
                }
            }
        }

        return $valid;
    }

public function error($rule=null) {
		if($rule === null)
			return $this->self;
		elseif(isset($this->rules[$rule]))
			return $this->rules[$rule];
		elseif($attribute = $this->attribute($rule))
			return $attribute->error();
	}

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


Question:
Let you get a module config object
@param moduleName String the name of the module
@returns {*}

function getModuleConfig(moduleName) {
                    if (!angular.isString(moduleName)) {
                        throw new Error('You need to give the name of the module to get');
                    }
                    if (!modules[moduleName]) {
                        return null;
                    }
                    return angular.copy(modules[moduleName]);
                }

public void marshall(DescribeConfigurationRevisionRequest describeConfigurationRevisionRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeConfigurationRevisionRequest.getConfigurationId(), CONFIGURATIONID_BINDING);
            protocolMarshaller.marshall(describeConfigurationRevisionRequest.getConfigurationRevision(), CONFIGURATIONREVISION_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:
// PgDescriptionByObjoidClassoidObjsubid retrieves a row from 'pg_catalog.pg_description' as a PgDescription.
//
// Generated from index 'pg_description_o_c_o_index'.

func PgDescriptionByObjoidClassoidObjsubid(db XODB, objoid pgtypes.Oid, classoid pgtypes.Oid, objsubid int) (*PgDescription, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, ctid, objoid, classoid, objsubid, description ` +
		`FROM pg_catalog.pg_description ` +
		`WHERE objoid = $1 AND classoid = $2 AND objsubid = $3`

	// run query
	XOLog(sqlstr, objoid, classoid, objsubid)
	pd := PgDescription{}

	err = db.QueryRow(sqlstr, objoid, classoid, objsubid).Scan(&pd.Tableoid, &pd.Cmax, &pd.Xmax, &pd.Cmin, &pd.Xmin, &pd.Ctid, &pd.Objoid, &pd.Classoid, &pd.Objsubid, &pd.Description)
	if err != nil {
		return nil, err
	}

	return &pd, nil
}

def create_subgroup_global(self, id, title, description=None, vendor_guid=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - id
        """ID"""
        path["id"] = id

        # REQUIRED - title
        """The title of the new outcome group."""
        data["title"] = title

        # OPTIONAL - description
        """The description of the new outcome group."""
        if description is not None:
            data["description"] = description

        # OPTIONAL - vendor_guid
        """A custom GUID for the learning standard"""
        if vendor_guid is not None:
            data["vendor_guid"] = vendor_guid

        self.logger.debug("POST /api/v1/global/outcome_groups/{id}/subgroups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/global/outcome_groups/{id}/subgroups".format(**path), data=data, params=params, single_item=True)

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


Question: // SetResourceOwner sets the ResourceOwner field's value.

func (s *ListResourcesInput) SetResourceOwner(v string) *ListResourcesInput {
	s.ResourceOwner = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
Determines the new element which will gain the focus.

@param {sap.ui.ux3.ToolPopup} context to get/set instance values
@private

function (context) {
                var oElement;
                var oFocusControl;
                var that = context;
                var defaultFocusableElements = [that._mParameters.firstFocusable, that._mParameters.lastFocusable];
                // jQuery custom selectors ":sapTabbable"
                var aTabbables = jQuery(":sapTabbable", that.$()).get();

                // search the first tabbable element
                for (var i = 0; i < aTabbables.length; i++) {
                    if (defaultFocusableElements.indexOf(aTabbables[i].id) === -1) {
                        oElement = aTabbables[i];
                        break;
                    }
                }

                // If a tabbable element is part of a control, focus the control instead
                // jQuery Plugin "control"
                oFocusControl = jQuery(oElement).control();
                if (oFocusControl[0]) {
                    var oFocusDomRef = oFocusControl[0].getFocusDomRef();
                    oElement = oFocusDomRef || oElement;
                } else {
                    // if there is no tabbable element in the content use the first fake
                    // element to set the focus to the toolpopup
                    oElement = defaultFocusableElements[0] ? window.document.getElementById(defaultFocusableElements[0]) : null;
                }

                // oElement might not be available if this function is called during destroy
                if (oElement) {
                    if (oElement) {
                        oElement.focus();
                    }
                    that._sInitialFocusId = oElement.id;
                }
            }

func (s *AnalyticsS3BucketDestination) SetBucket(v string) *AnalyticsS3BucketDestination {
	s.Bucket = &v
	return s
}

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


Question:
If it is a status update message and images are provided, add them.

@param $twitterMessage
@return mixed

private function addImagesIfGiven($twitterMessage)
    {
        if (is_a($twitterMessage, TwitterStatusUpdate::class) && $twitterMessage->getImages()) {
            $this->twitter->setTimeouts(10, 15);

            $twitterMessage->imageIds = collect($twitterMessage->getImages())->map(function (TwitterImage $image) {
                $media = $this->twitter->upload('media/upload', ['media' => $image->getPath()]);

                return $media->media_id_string;
            });
        }

        return $twitterMessage;
    }

public function get_sha1() {

        if ($this->plugin && $this->editor) {
            $plugin = $this->get_submission_plugin();
            $options = portfolio_format_text_options();
            $options->context = context_module::instance($this->cmid);

            $text = format_text($plugin->get_editor_text($this->editor, $this->sid),
                                $plugin->get_editor_format($this->editor, $this->sid),
                                $options);
            $textsha1 = sha1($text);
            $filesha1 = '';
            try {
                $filesha1 = $this->get_sha1_file();
            } catch (portfolio_caller_exception $e) {
                // No files.
            }
            return sha1($textsha1 . $filesha1);
        }
        return $this->get_sha1_file();
    }

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


Question:
Adds a POST parameter if not already present

@param string $name
@param string $value
@return boolean true if added false if not

public function addPostParameter($name, $value)
    {
        if (!$this->hasGetPostParamValue($name, true))
        {
            $this->postParams[$name] = $value;
            return true;
        }
        else
        {
            return false;
        }
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question:
initializePropertyMaps
Initialize the Property Maps which must each contain an entry for every supported
Destination Property which is to be encoded or set via this class.

private static void initializePropertyMaps() {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "initializePropertyMap");

    // Add all the supported properties to the PropertyMaps:
    // PR, DM, and TL use the PhantomPropertyCoder as they are encoded/decoded
    // separately rather than by using their PropertyCoder.
    // They need to be included in the map so that methods can extract information
    // and set them.
    // Any property with a shortName which maps to null but be added with one of
    // the general coders - currently StringPropertyCoder or IntegerPropertyCoder.
    // NOTE: If SuppressIfDefaultInJNDI is not null, the LongName MUST match that defined in
    // JmsInternalConstants
    // Parameters:
    //        PropertyCoder               ( LongName                            ShortName), IntValue,  ValueType    , DefaultValue             SuppressIfDefaultInJNDI)
    addToMaps(new PhantomPropertyCoder    (JmsInternalConstants.PRIORITY             , PR),  PR_INT,   Integer.class, Integer.valueOf(Message.DEFAULT_PRIORITY) ,null);
    addToMaps(new PhantomPropertyCoder    (JmsInternalConstants.DELIVERY_MODE        , DM),  DM_INT,   String.class , ApiJmsConstants.DELIVERY_MODE_APP         ,null);
    addToMaps(new PhantomPropertyCoder    (JmsInternalConstants.TIME_TO_LIVE         , TL),  TL_INT,   Long.class   , Long.valueOf(Message.DEFAULT_TIME_TO_LIVE),null);
    addToMaps(new ReadAheadCoder          ("readAhead"                               , RA),  RA_INT,   String.class , ApiJmsConstants.READ_AHEAD_AS_CONNECTION  ,null);
    addToMaps(new ShortStringPropertyCoder("topicName"                               , TN),  TN_INT,   String.class , null                                      ,null);
    addToMaps(new ShortStringPropertyCoder("topicSpace"                              , TS),  TS_INT,   String.class , JmsTopicImpl.DEFAULT_TOPIC_SPACE          ,null);
    addToMaps(new ShortStringPropertyCoder("queueName"                               , QN),  QN_INT,   String.class , null                                      ,null);
    addToMaps(new OnOffPropertyCoder      (JmsInternalConstants.SCOPE_TO_LOCAL_QP    , QP),  QP_INT,   String.class , ApiJmsConstants.SCOPE_TO_LOCAL_QP_OFF     ,JmsQueueImpl.class);
    addToMaps(new OnOffPropertyCoder      (JmsInternalConstants.PRODUCER_PREFER_LOCAL, PL),  PL_INT,   String.class , ApiJmsConstants.PRODUCER_PREFER_LOCAL_ON  ,JmsQueueImpl.class);
    addToMaps(new OnOffPropertyCoder      (JmsInternalConstants.PRODUCER_BIND        , PB),  PB_INT,   String.class , ApiJmsConstants.PRODUCER_BIND_OFF         ,JmsQueueImpl.class);
    addToMaps(new OnOffPropertyCoder      (JmsInternalConstants.GATHER_MESSAGES      , GM),  GM_INT,   String.class , ApiJmsConstants.GATHER_MESSAGES_OFF       ,JmsQueueImpl.class);
    addToMaps(new StringPropertyCoder     (JmsInternalConstants.BUS_NAME             , BN),  BN_INT,   String.class , null                                      ,null);
    addToMaps(new IntegerPropertyCoder    (JmsInternalConstants.BLOCKED_DESTINATION  , BD),  BD_INT,   Integer.class, null                                      ,null);
    addToMaps(new StringPropertyCoder     ("destName"                                , DN),  DN_INT,   String.class , null                                      ,null);
    addToMaps(new StringPropertyCoder     ("destDiscrim"                             , DD),  DD_INT,   String.class , null                                      ,null);

    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "propertyMap" + propertyMap);
    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "reverseMap" + reverseMap);
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "initializePropertyMap");
  }

func (s *Stack) createFileBasedConfigMaps(configMaps corev1.ConfigMapInterface) ([]childResource, error) {
	var resources []childResource
	for name, config := range s.Spec.Configs {
		if config.File == "" {
			continue
		}

		fileName := filepath.Base(config.File)
		content, err := ioutil.ReadFile(config.File)
		if err != nil {
			return resources, err
		}

		configMap, err := configMaps.Create(toConfigMap(s.Name, name, fileName, content))
		if err != nil {
			return resources, err
		}
		resources = append(resources, &configMapChildResource{client: configMaps, configMap: configMap})
	}
	return resources, nil
}

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


Question:
切换数据源对象

@param null $id
@return mixed

public static function Using($id = null)
    {
        if (!$id) {
            //初始运行
            self::$using_dbo_id = self::$default_dbo_id;
        } else {
            //切换dbo id
            if ($id != self::$using_dbo_id) {
                self::$using_dbo_id = $id;
            }
        }
        return self::dbo(self::$using_dbo_id);
    }

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question: // addKey saves the specified key to the registry

func (c *ClientsetCAStore) addKey(name string, keysetType kops.KeysetType, item *kops.KeysetItem) error {
	create := false
	client := c.clientset.Keysets(c.namespace)
	keyset, err := client.Get(name, v1.GetOptions{})
	if err != nil {
		if errors.IsNotFound(err) {
			keyset = nil
		} else {
			return fmt.Errorf("error reading keyset %q: %v", name, err)
		}
	}
	if keyset == nil {
		keyset = &kops.Keyset{}
		keyset.Name = name
		keyset.Spec.Type = keysetType
		create = true
	}
	keyset.Spec.Keys = append(keyset.Spec.Keys, *item)
	if create {
		if _, err := client.Create(keyset); err != nil {
			return fmt.Errorf("error creating keyset %q: %v", name, err)
		}
	} else {
		if _, err := client.Update(keyset); err != nil {
			return fmt.Errorf("error updating keyset %q: %v", name, err)
		}
	}
	return nil
}

func (s *CreateSMBFileShareInput) SetKMSKey(v string) *CreateSMBFileShareInput {
	s.KMSKey = &v
	return s
}

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


Question:
Write a LABELSST record or a LABEL record. Which one depends on BIFF version

@param int $row Row index (0-based)
@param int $col Column index (0-based)
@param string $str The string
@param int $xfIndex Index to XF record

private function _writeString($row, $col, $str, $xfIndex)
	{
		$this->_writeLabelSst($row, $col, $str, $xfIndex);
	}

def index(i=nil, &blk)
      @index = i || blk if i || !blk.nil?
      @index ||= Familia.index
      @index
    end

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


Question: Start a new paragraph.

def start_paragraph(self, stylename=None):
        """"""
        # Use the next paragraph style if one was set.
        if stylename is None:
            stylename = self._next_p_style or 'normal-paragraph'
        self.start_container(P, stylename=stylename)

def _page_gen(self):

        track = ""
        for page in self.__pages__:
            track += "/{page}".format(page=page)
        return track

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


Question: Initializes the curl resource

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

private function loadDrupal(FileLoader $loader, ContainerBuilder $container, array $config)
    {
        if (isset($config['drupal'])) {
            $loader->load('drivers/drupal.yml');
            $container->setParameter('drupal.driver.drupal.drupal_root', $config['drupal']['drupal_root']);
        }
    }

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


Question: // SetTags sets the Tags field's value.

func (s *CreateStreamInput) SetTags(v map[string]*string) *CreateStreamInput {
	s.Tags = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
<p>
An object containing information about one or more disk mappings.
</p>

@param attachedDiskMapping
An object containing information about one or more disk mappings.

public void setAttachedDiskMapping(java.util.Map<String, java.util.List<DiskMap>> attachedDiskMapping) {
        this.attachedDiskMapping = attachedDiskMapping;
    }

def _update_requires_resolution_inputs(self):

        input_paths = [quad[1] for quad in self.requires_resolution]
        results = resolve_multiple_existing_paths(input_paths)
        for input_name, input_value, input_class, input_index in self.requires_resolution:
            project = results[input_value]['project']
            folderpath = results[input_value]['folder']
            entity_result = results[input_value]['name']
            if input_class is None:
                if entity_result is not None:
                    if isinstance(entity_result, basestring):
                        # Case: -ifoo=job-012301230123012301230123
                        # Case: -ifoo=analysis-012301230123012301230123
                        assert(is_job_id(entity_result) or
                               (is_analysis_id(entity_result)))
                        input_value = entity_result
                    elif is_hashid(input_value):
                        input_value = {'$dnanexus_link': entity_result['id']}
                    elif 'describe' in entity_result:
                        # Then findDataObjects was called (returned describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['describe']['project'],
                                                          "id": entity_result['id']}}
                    else:
                        # Then resolveDataObjects was called in a batch (no describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                          "id": entity_result['id']}}
                if input_index >= 0:
                    if self.inputs[input_name][input_index] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name][input_index] = input_value
                else:
                    if self.inputs[input_name] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name] = input_value
            else:
                msg = 'Value provided for input field "' + input_name + '" could not be parsed as ' + \
                      input_class + ': '
                if input_value == '':
                    raise DXCLIError(msg + 'empty string cannot be resolved')
                if entity_result is None:
                    raise DXCLIError(msg + 'could not resolve \"' + input_value + '\" to a name or ID')
                try:
                    dxpy.bindings.verify_string_dxid(entity_result['id'], input_class)
                except DXError as details:
                    raise DXCLIError(msg + str(details))
                if is_hashid(input_value):
                    input_value = {'$dnanexus_link': entity_result['id']}
                elif 'describe' in entity_result:
                    # Then findDataObjects was called (returned describe hash)
                    input_value = {'$dnanexus_link': {"project": entity_result['describe']['project'],
                                                      "id": entity_result['id']}}
                else:
                    # Then resolveDataObjects was called in a batch (no describe hash)
                    input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                      "id": entity_result['id']}}
                if input_index != -1:
                    # The class is an array, so append the resolved value
                    self.inputs[input_name].append(input_value)
                else:
                    self.inputs[input_name] = input_value

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


Question:
%prog patch reference.fasta reads.fasta

    Run PBJelly with reference and reads.

def patch(args):

    from jcvi.formats.base import write_file
    from jcvi.formats.fasta import format

    p = OptionParser(patch.__doc__)
    p.add_option("--cleanfasta", default=False, action="store_true",
                 help="Clean FASTA to remove description [default: %default]")
    p.add_option("--highqual", default=False, action="store_true",
                 help="Reads are of high quality [default: %default]")
    p.set_home("pbjelly")
    p.set_cpus()
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    ref, reads = args
    cpus = opts.cpus
    cmd = op.join(opts.pbjelly_home, "setup.sh")
    setup = "source {0}".format(cmd)
    if not which("fakeQuals.py"):
        sh(setup)

    pf = ref.rsplit(".", 1)[0]
    pr, px = reads.rsplit(".", 1)
    # Remove description line
    if opts.cleanfasta:
        oref = pf + ".f.fasta"
        oreads = pr + ".f.fasta"
        format([ref, oref])
        format([reads, oreads])
        ref, reads = oref, oreads

    # Check if the FASTA has qual
    ref, refq = fake_quals(ref)
    convert_reads = not px in ("fq", "fastq", "txt")
    if convert_reads:
        reads, readsq = fake_quals(reads)
        readsfiles = " ".join((reads, readsq))
    else:
        readsfiles = reads

    # Make directory structure
    dref, dreads = "data/reference", "data/reads"
    cwd = os.getcwd()
    reference = op.join(cwd, "{0}/{1}".format(dref, ref))
    reads = op.join(cwd, "{0}/{1}".format(dreads, reads))
    if not op.exists(reference):
        sh("mkdir -p {0}".format(dref))
        sh("cp {0} {1}/".format(" ".join((ref, refq)), dref))
    if not op.exists(reads):
        sh("mkdir -p {0}".format(dreads))
        sh("cp {0} {1}/".format(readsfiles, dreads))

    outputDir = cwd
    p = Protocol(outputDir, reference, reads, highqual=opts.highqual)
    p.write_xml()

    # Build the pipeline
    runsh = [setup]
    for action in "setup|mapping|support|extraction".split("|"):
        runsh.append("Jelly.py {0} Protocol.xml".format(action))

    runsh.append('Jelly.py assembly Protocol.xml -x "--nproc={0}"'.format(cpus))
    runsh.append("Jelly.py output Protocol.xml")

    runfile = "run.sh"
    contents = "\n".join(runsh)
    write_file(runfile, contents)

def put_stream(self, rel_path, metadata=None, cb=None):

        from io import IOBase

        if not isinstance(rel_path, basestring):
            rel_path = rel_path.cache_key

        repo_path = os.path.join(self.cache_dir, rel_path.strip("/"))

        if not os.path.isdir(os.path.dirname(repo_path)):
            os.makedirs(os.path.dirname(repo_path))

        if os.path.exists(repo_path):
            os.remove(repo_path)

        sink = open(repo_path, 'wb')

        upstream = self.upstream

        class flo(IOBase):

            '''This File-Like-Object class ensures that the file is also
            sent to the upstream after it is stored in the FSCache. '''

            def __init__(self, sink, upstream, repo_path, rel_path):

                self._sink = sink
                self._upstream = upstream
                self._repo_path = repo_path
                self._rel_path = rel_path

            @property
            def rel_path(self):
                return self._rel_path

            def write(self, str_):
                self._sink.write(str_)

            def close(self):
                if not self._sink.closed:
                    # print "Closing put_stream.flo {}
                    # is_closed={}!".format(self._repo_path, self._sink.closed)

                    self._sink.close()

                    if self._upstream and not self._upstream.readonly and not self._upstream.usreadonly:
                        self._upstream.put(
                            self._repo_path,
                            self._rel_path,
                            metadata=metadata)

            def __enter__(self): # Can be used as a context!
                return self

            def __exit__(self, type_, value, traceback):
                if type_:
                    return False

                self.close()

        self.put_metadata(rel_path, metadata)

        return flo(sink, upstream, repo_path, rel_path)

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


Question: // UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller.

func (id *ObjectId) UnmarshalJSON(data []byte) error {
	if len(data) != 26 || data[0] != '"' || data[25] != '"' {
		return errors.New(fmt.Sprintf("Invalid ObjectId in JSON: %s", string(data)))
	}
	var buf [12]byte
	_, err := hex.Decode(buf[:], data[1:25])
	if err != nil {
		return errors.New(fmt.Sprintf("Invalid ObjectId in JSON: %s (%s)", string(data), err))
	}
	*id = ObjectId(string(buf[:]))
	return nil
}

def _encode_key(self, obj):
        """"""

        if obj.__class__ is str:
            return self._encode_str(obj)

        if obj.__class__ is UUID:
            return '"' + str(obj) + '"'

        # __mm_serialize__ is called before any isinstance checks (but after exact type checks)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode_key(data)

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        # if everything else failed try the default() method and re-raise any TypeError
        # exceptions as more specific "not a valid dict key" TypeErrors
        try:
            value = self.default(obj)
        except TypeError:
            raise TypeError('{!r} is not a valid dictionary key'.format(obj))

        return self._encode_key(value)

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


Question: more convenient use of the API

public Optional<SectionHeader> maybeGetSectionTableEntry(SectionTable table) {
        checkArgument(table != null, "table must not be null");
        List<SectionHeader> sections = table.getSectionHeaders();
        // loop through all section headers to check if entry is within section
        for (SectionHeader header : sections) {
            long vSize = header.getAlignedVirtualSize();
            // corkami: "a section can have a null VirtualSize: in this case,
            // only the SizeOfRawData is taken into consideration. "
            // see: https://code.google.com/p/corkami/wiki/PE#section_table
            if (vSize == 0) {
                vSize = header.getAlignedSizeOfRaw();
            }
            long vAddress = header.getAlignedVirtualAddress();
            logger.debug("check if rva is within " + vAddress + " and "
                    + (vAddress + vSize));
            // return header if data entry va points into it
            if (rvaIsWithin(new VirtualLocation(vAddress, vSize))) {
                return Optional.of(header);
            }
        }
        logger.warn("there is no entry that matches data dir entry RVA "
                + virtualAddress);
        return Optional.absent();
    }

public function request($method, $endpoint, array $params = array(), $isVault = false)
    {
        return $this->doRequest($method, $endpoint, $params, $isVault);
    }

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


Question: /* --- Overridden methods ---

@Override
    protected ResolutionResult resolveDependencies(String projectFolder, String topLevelFolder, Set<String> bomFiles) {
        logger.debug("gradleAggregateModules={}",gradleAggregateModules);
        // In order to use the gradle wrapper, we define the top folder that contains the wrapper
        this.gradleCli.setTopLevelFolderGradlew(topLevelFolder);
        // each bom-file ( = build.gradle) represents a module - identify its folder and scan it using 'gradle dependencies'
        Map<AgentProjectInfo, Path> projectInfoPathMap = new HashMap<>();
        Collection<String> excludes = new HashSet<>();

        //        // Get the list of projects as paths
        //        List<String> projectsList = null;
        //        if (bomFiles.size() > 1) {
        //            projectsList = collectProjects(topLevelFolder);
        //        }
        //        if (projectsList == null) {
        //            logger.warn("Command \"gradle projects\" did not return a list of projects");
        //        }
        if (gradleRunPreStep) {
            downloadMissingDependencies(projectFolder);
        }

        for (String bomFile : bomFiles) {
            String bomFileFolder = new File(bomFile).getParent();
            File bomFolder = new File(new File(bomFile).getParent());
            String moduleName = bomFolder.getName();
            //            String moduleRelativeName = Constants.EMPTY_STRING;
            //            try {
            //                String canonicalPath = bomFolder.getCanonicalPath();
            //                // Relative name by replacing the root folder with "." - will look something like .\abc\def
            //                moduleRelativeName = Constants.DOT + canonicalPath.replaceFirst(Pattern.quote(topLevelFolder), Constants.EMPTY_STRING);
            //            } catch (Exception e) {
            //                logger.debug("Error getting path - {} ", e.getMessage());
            //            }
            //            // making sure the module's folder was listed by "gradle projects" command
            //            if (!moduleRelativeName.isEmpty() && projectsList != null && !projectsList.contains(moduleRelativeName)) {
            //                logger.debug("Ignoring project at {} - because it was not listed by \"gradle projects\" command", moduleRelativeName);
            //                continue;
            //            }
            List<String> lines = getDependenciesTree(bomFileFolder, moduleName);
            if (lines != null) {
                List<DependencyInfo> dependencies = collectDependencies(lines, bomFileFolder, bomFileFolder.equals(topLevelFolder), bomFile);
                if (dependencies.size() > 0) {
                    AgentProjectInfo agentProjectInfo = new AgentProjectInfo();
                    agentProjectInfo.getDependencies().addAll(dependencies);
                    if (!gradleAggregateModules) {
                        Coordinates coordinates = new Coordinates();
                        coordinates.setArtifactId(moduleName);
                        agentProjectInfo.setCoordinates(coordinates);
                    }
                    projectInfoPathMap.put(agentProjectInfo, bomFolder.toPath());
                    if (ignoreSourceCode) {
                        excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder, extensionPattern(GRADLE_SCRIPT_EXTENSION), null));
                    }
                }
            }
        }
        topLevelFoldersNames.add(topLevelFolder.substring(topLevelFolder.lastIndexOf(fileSeparator) + 1));
        excludes.addAll(getExcludes());
        ResolutionResult resolutionResult;
        if (!gradleAggregateModules) {
            resolutionResult = new ResolutionResult(projectInfoPathMap, excludes, getDependencyType(), topLevelFolder);
        } else {
            resolutionResult = new ResolutionResult(projectInfoPathMap.keySet().stream()
                    .flatMap(project -> project.getDependencies().stream()).collect(Collectors.toList()), excludes, getDependencyType(), topLevelFolder);
        }
        logger.debug("total projects = {}",resolutionResult.getResolvedProjects().size());
        return resolutionResult;
    }

public void addWriter(PdfWriter writer) throws DocumentException {
        if (this.writer == null) {
            this.writer = writer;
            annotationsImp = new PdfAnnotationsImp(writer);
            return;
        }
        throw new DocumentException("You can only add a writer to a PdfDocument once.");
    }

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


Question:
Reads document content from the stream.

@param in input stream.
@throws IOException

private void readFromStream(InputStream in) throws IOException {
        document = DocumentFactory.newDocument(Json.read(in));
    }

@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withDescriptor:")
    public void sendDocument(Peer peer, String fileName, String mimeType, String descriptor) {
        sendDocument(peer, fileName, mimeType, null, descriptor);
    }

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


Question:
Obtain a binary version of an :class:`openpyxl.Workbook` representation of
    an Excel file.

def excel_to_bytes(wb: Workbook) -> bytes:

    memfile = io.BytesIO()
    wb.save(memfile)
    return memfile.getvalue()

def load_ipython_extension(ipython):
    """"""
    from google.cloud.bigquery.magics import _cell_magic

    ipython.register_magic_function(
        _cell_magic, magic_kind="cell", magic_name="bigquery"
    )

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


Question:
The result_code property.

        Args:
            value (string). the property value.

def result_code(self, value):

        if value == self._defaults['resultCode'] and 'resultCode' in self._values:
            del self._values['resultCode']
        else:
            self._values['resultCode'] = value

function verifyModifier(predicate, defaultMessage) {
        return function () {
          var message;
          if (predicate.apply(null, arguments) === false) {
            message = arguments[arguments.length - 1];
            throw new Error(check.unemptyString(message) ? message : defaultMessage);
          }
        };
      }

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


Question:
// updateNodeFromDriverLocked makes the changes to the node from a driver update
// but does not send the update to the server. c.configLock must be held before
// calling this func

func (c *Client) updateNodeFromDriverLocked(name string, info *structs.DriverInfo) bool {
	var hasChanged bool

	hadDriver := c.config.Node.Drivers[name] != nil
	if !hadDriver {
		// If the driver info has not yet been set, do that here
		hasChanged = true
		for attrName, newVal := range info.Attributes {
			c.config.Node.Attributes[attrName] = newVal
		}
	} else {
		oldVal := c.config.Node.Drivers[name]
		// The driver info has already been set, fix it up
		if oldVal.Detected != info.Detected {
			hasChanged = true
		}

		// If health state has change, trigger node event
		if oldVal.Healthy != info.Healthy || oldVal.HealthDescription != info.HealthDescription {
			hasChanged = true
			if info.HealthDescription != "" {
				event := &structs.NodeEvent{
					Subsystem: "Driver",
					Message:   info.HealthDescription,
					Timestamp: time.Now(),
					Details:   map[string]string{"driver": name},
				}
				c.triggerNodeEvent(event)
			}
		}

		for attrName, newVal := range info.Attributes {
			oldVal := c.config.Node.Drivers[name].Attributes[attrName]
			if oldVal == newVal {
				continue
			}

			hasChanged = true
			if newVal == "" {
				delete(c.config.Node.Attributes, attrName)
			} else {
				c.config.Node.Attributes[attrName] = newVal
			}
		}
	}

	// COMPAT Remove in Nomad 0.10
	// We maintain the driver enabled attribute until all drivers expose
	// their attributes as DriverInfo
	driverName := fmt.Sprintf("driver.%s", name)
	if info.Detected {
		c.config.Node.Attributes[driverName] = "1"
	} else {
		delete(c.config.Node.Attributes, driverName)
	}

	return hasChanged
}

public function locked()
    {
        $this->defaultData();
	    $resource = $this->getResource($this->getRequestParameter('id'));
	    $lockData = LockManager::getImplementation()->getLockData($resource);

	    $this->setData('topclass-label',
	        $this->hasRequestParameter('topclass-label') ? $this->getRequestParameter('topclass-label') : __('Resource')
        );

	    if (AclProxy::hasAccess($this->getSession()->getUser(), __CLASS__, 'forceRelease', array('uri' => $resource->getUri()))) {
	        $this->setData('id', $resource->getUri());
            $this->setData('forceRelease', true);
	    }

	    $this->setData('lockDate', $lockData->getCreationTime());
	    $this->setData('ownerHtml', UserHelper::renderHtmlUser($lockData->getOwnerId()));

	    if ($this->hasRequestParameter('view') && $this->hasRequestParameter('ext')) {
	        $this->setView($this->getRequestParameter('view'), $this->getRequestParameter('ext'));
	    } else {
	        $this->setView('Lock/locked.tpl', 'tao');
	    }
	}

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


Question:
Find and parse a docblock for a given class or method.

@param Stmt $stmt
@param array $uses

@return array|null

protected function getDocBlock(Stmt $stmt, array $uses = []): ?array
    {
        $comments = $stmt->getAttribute('comments');

        if (is_array($comments)) {
            foreach ($comments as $comment) {
                if ($comment instanceof Doc) {
                    return $this->processDocBlock($comment->getText(), $uses);
                }
            }
        }

        return null;
    }

public Parameter[] getBindParameters() {
		return bindNames.stream().map(this::getParam).filter(Objects::nonNull).toArray(Parameter[]::new);
	}

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


Question: // Write object writes the file set out by the GCSObjectParams

func (service *GCSService) WriteObject(ctx context.Context, params GCSObjectParams, r io.Reader) (int64, error) {
	obj := service.Client.Bucket(params.Bucket).Object(params.ID)

	w := obj.NewWriter(ctx)

	n, err := io.Copy(w, r)
	if err != nil {
		return 0, err
	}

	err = w.Close()
	if err != nil {
		if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == 404 {
			return 0, fmt.Errorf("gcsstore: the bucket %s could not be found while trying to write an object", params.Bucket)
		}
		return 0, err
	}

	return n, err
}

@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withDescriptor:")
    public void sendDocument(Peer peer, String fileName, String mimeType, String descriptor) {
        sendDocument(peer, fileName, mimeType, null, descriptor);
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *StaticKeySettings) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "StaticKeySettings"}
	if s.StaticKeyValue == nil {
		invalidParams.Add(request.NewErrParamRequired("StaticKeyValue"))
	}
	if s.StaticKeyValue != nil && len(*s.StaticKeyValue) < 32 {
		invalidParams.Add(request.NewErrParamMinLen("StaticKeyValue", 32))
	}
	if s.KeyProviderServer != nil {
		if err := s.KeyProviderServer.Validate(); err != nil {
			invalidParams.AddNested("KeyProviderServer", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
Cache was invalid , so render from compiled and write to cache

@param \Smarty_Template_Cached   $cached
@param \Smarty_Internal_Template $_template
@param                           $no_output_filter

@throws \Exception

public function updateCache(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template, $no_output_filter)
    {
        if ($_template->source->handler->uncompiled) {
            ob_start();
            $_template->source->render($_template);
        } else {
            ob_start();
            if (!isset($_template->compiled)) {
                $_template->loadCompiled();
            }
            $_template->compiled->render($_template);
        }
        if ($_template->smarty->debugging) {
            $_template->smarty->_debug->start_cache($_template);
        }
        $this->removeNoCacheHash($cached, $_template, $no_output_filter);
        $compile_check = $_template->smarty->compile_check;
        $_template->smarty->compile_check = false;
        if (isset($_template->parent) && $_template->parent->_objType == 2) {
            $_template->compiled->unifunc = $_template->parent->compiled->unifunc;
        }
        if (!$_template->cached->processed) {
            $_template->cached->process($_template, true);
        }
        $_template->smarty->compile_check = $compile_check;
        $cached->getRenderedTemplateCode($_template);
        if ($_template->smarty->debugging) {
            $_template->smarty->_debug->end_cache($_template);
        }
    }

public function populateTimestamp(Smarty_Template_Source $source)
    {
        $source->timestamp = $this->getTemplateTimestamp($source);
        $source->exists = !!$source->timestamp;
    }

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


Question: Stereographic forward equations--mapping lat,long to x,y

function forward$6(p) {
        var lon = p.x;
        var lat = p.y;
        var sinlat = Math.sin(lat);
        var coslat = Math.cos(lat);
        var A, X, sinX, cosX, ts, rh;
        var dlon = adjust_lon(lon - this.long0);

        if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) {
            //case of the origine point
            //trace('stere:this is the origin point');
            p.x = NaN;
            p.y = NaN;
            return p;
        }
        if (this.sphere) {
            //trace('stere:sphere case');
            A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
            p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
            p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
            return p;
        }
        else {
            X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI;
            cosX = Math.cos(X);
            sinX = Math.sin(X);
            if (Math.abs(this.coslat0) <= EPSLN) {
                ts = tsfnz(this.e, lat * this.con, this.con * sinlat);
                rh = 2 * this.a * this.k0 * ts / this.cons;
                p.x = this.x0 + rh * Math.sin(lon - this.long0);
                p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
                //trace(p.toString());
                return p;
            }
            else if (Math.abs(this.sinlat0) < EPSLN) {
                //Eq
                //trace('stere:equateur');
                A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
                p.y = A * sinX;
            }
            else {
                //other case
                //trace('stere:normal case');
                A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
                p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
            }
            p.x = A * cosX * Math.sin(dlon) + this.x0;
        }
        //trace(p.toString());
        return p;
    }

public function reverseByCoordinates($latitude, $longitude)
    {
        $query = $this->buildQuery('address', "{$latitude},{$longitude}");

        $response = $this->validateResponse(
            $this->getResponse($query)
        );

        return $this->buildResults($response['results']);
    }

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


Question:
Process a 'translate' Element in the XML stream.

@param cluster
@param cur Current document nod

private void processElementTranslate(GeneratorSingleCluster cluster, Node cur) {
    double[] offset = null;
    String vstr = ((Element) cur).getAttribute(ATTR_VECTOR);
    if(vstr != null && vstr.length() > 0) {
      offset = parseVector(vstr);
    }
    if(offset == null) {
      throw new AbortException("No translation vector given.");
    }

    // *** add new translation
    cluster.addTranslation(offset);

    // TODO: check for unknown attributes.
    XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
    while(iter.hasNext()) {
      Node child = iter.next();
      if(child.getNodeType() == Node.ELEMENT_NODE) {
        LOG.warning("Unknown element in XML specification file: " + child.getNodeName());
      }
    }
  }

public function post($query, Array $parameters = [], $autoParser = true) {
        curl_setopt_array($this->resource, [
            CURLOPT_POSTFIELDS => array_merge($parameters, [
                self::PARAMETER_QUERY => $query,
                self::PARAMETER_APIKEY => $this->apiKey
            ])
        ]);

        $dom = new \DOMDocument;
        $ret = curl_exec($this->resource);
        if (!$autoParser) return $ret;
        $dom->loadXML($ret);
        static::assert($dom);
        return $dom;
    }

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


Question:
Returns the data as an associative array.

@return array with all data

@throws BadValueException when no toArray method is available on an object value

public function toArray()
    {
        $data = array();

        foreach ($this as $key => $value) {
            if (is_object($value)) {
                if (!is_callable(array($value, 'toArray'))) {
                    throw new RuntimeException('Object does not implement toArray() method on key: ' . $key);
                }
                $data[$key] = $value->toArray();
            } else {
                $data[$key] = $value;
            }
        }

        return $data;
    }

public function get()
    {
        $rows = [];

        foreach ($this->db as $key => $value) {
            $rows[] = (object) [
                'key'   => $key,
                'value' => is_string($value) ? $value : print_r($value, true),
            ];
        }

        return $rows;
    }

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


Question: // Pause the container

func (c *Container) Pause(ctx context.Context) error {
	return c.process.(*proc.Init).Pause(ctx)
}

IAtom getUnplacedHeavyAtom(IAtomContainer molecule) {
        for (IAtom atom : molecule.atoms()) {
            if (isUnplacedHeavyAtom(atom))
                return atom;
        }
        return null;
    }

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


Question:
Get this Entity's type.

@todo: Refactor optional param away, pick snake or upper case to be universal.

@param  bool   $kebabCase
@return string

public function getType($kebabCase = false)
    {
        if($kebabCase)
        {
            return strtolower(str_replace('_', '-', $this->getTable()));
        }

        return strtoupper($this->getTable());
    }

public function button(string $title, $url = false, array $options = []): string
    {
        $options = Hash::merge([
            'icon' => 'arrow-right',
            'class' => 'btn btn-default btn-xs',
            'additionalClasses' => '',
        ], $options);

        $options['class'] .= ' ' . $options['additionalClasses'];
        if ($options['icon']) {
            $title = '<i class="fa fa-' . $options['icon'] . '"></i> ' . $title;
            $options['escape'] = false;
        }
        unset($options['additionalClasses'], $options['icon']);

        return $this->Html->link($title, $url, $options);
    }

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


Question:
{@inheritDoc}

@see java.sql.Wrapper#unwrap(java.lang.Class)

@Override
	public <T> T unwrap(final Class<T> iface) throws SQLException {
		if (iface != null && this.getClass().isAssignableFrom(iface)) {
			return iface.cast(this);
		}

		return wrapped.unwrap(iface);
	}

public String getSubString(long pos, int length) throws SQLException {

    if (pos < 1) {
      throw ExceptionMapper.getSqlException("position must be >= 1");
    }

    if (length < 0) {
      throw ExceptionMapper.getSqlException("length must be > 0");
    }

    try {
      String val = toString();
      return val.substring((int) pos - 1, Math.min((int) pos - 1 + length, val.length()));
    } catch (Exception e) {
      throw new SQLException(e);
    }
  }

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


Question:
/*
(non-Javadoc)

@see javax.security.enterprise.SecurityContext#getPrincipalsByType(java.lang.Class)

@Override
    public <T extends Principal> Set<T> getPrincipalsByType(Class<T> type) {
        //Get the caller principal from the caller subject
        Subject callerSubject = getCallerSubject();

        if (callerSubject != null) {
            //Get the prinicipals by type
            Set<T> principals = callerSubject.getPrincipals(type);
            return principals;
        }

        return null;

    }

def role_create(role, principal, endpoint_id):

    principal_type, principal_val = principal

    client = get_client()

    if principal_type == "identity":
        principal_val = maybe_lookup_identity_id(principal_val)
        if not principal_val:
            raise click.UsageError(
                "Identity does not exist. "
                "Use --provision-identity to auto-provision an identity."
            )
    elif principal_type == "provision-identity":
        principal_val = maybe_lookup_identity_id(principal_val, provision=True)
        principal_type = "identity"

    role_doc = assemble_generic_doc(
        "role", principal_type=principal_type, principal=principal_val, role=role
    )

    res = client.add_endpoint_role(endpoint_id, role_doc)
    formatted_print(res, simple_text="ID: {}".format(res["id"]))

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


Question: Records w warining in the warnings table.

def warning(type, message, lineno)
      RequestLogAnalyzer::Database::Warning.create!(warning_type: type.to_s, message: message, lineno: lineno)
    end

public Vector<Vector> getDeletedRecordsAsDataVector() {
		final Vector<Vector> data = new Vector<Vector>();
		for (final JKTableRecord rec : this.deletedRecords) {
			data.add(rec.toValuesVector());
		}
		return data;
	}

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


Question:
Authenticates against the supplied adapter

@param   AdapterInterface    $adapter
@return  \Zend\Authentication\Result
@throws  \Zend\Authentication\Exception\RuntimeException

public function authenticate( AdapterInterface $adapter = null )
    {
        $result = parent::authenticate( $adapter );

        if ( $result->isValid() )
        {
            $this->identityRefreshed = true;
        }

        return $result;
    }

function SmartyStreets(httpAdapter, auth_id, auth_token) {
    SmartyStreets.super_.call(this, httpAdapter);

    if(!auth_id && !auth_token){
      throw new Error('You must specify an auth-id and auth-token!');
    }

    this.auth_id = auth_id;
    this.auth_token = auth_token;
}

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