Question:
Update the specified resource in storage.

@param  \Illuminate\Http\Request  $request
@param  int  $id
@return \Illuminate\Http\RedirectResponse

public function update(Request $request, $id)
    {
        $this->roles->findOrFail($id)->update($request->only('name', 'label'));
        return \Redirect::route('admin.roles.index', [
         ])->withMessage(trans('acl::role.roles-controller-successfully_updated'));
    }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
Set the Tint ColorStateList

@param tintStateList ColorStateList

public void setColorStateList(ColorStateList tintStateList) {
        if (tintStateList == null)
            tintStateList = ColorStateList.valueOf(Color.BLACK);
        mColorStateList = tintStateList;
        onStateChange(getState());
    }

def handle_and_track_state_change(self, state_change: StateChange):

        for greenlet in self.handle_state_change(state_change):
            self.add_pending_greenlet(greenlet)

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


Question:
Updates field value of Relation field type identified by given $row data,
removing relation data.

@param array $row

protected function removeRelationFromRelationField(array $row)
    {
        $query = $this->dbHandler->createUpdateQuery();
        $query
            ->update('ezcontentobject_attribute')
            ->set('data_int', $query->bindValue(null, null, PDO::PARAM_INT))
            ->set('sort_key_int', $query->bindValue(0, null, PDO::PARAM_INT))
            ->where(
                $query->expr->lAnd(
                    $query->expr->eq(
                        $this->dbHandler->quoteColumn('id'),
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
                    ),
                    $query->expr->eq(
                        $this->dbHandler->quoteColumn('version'),
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
                    )
                )
            );

        $query->prepare()->execute();
    }

private function parseCet(ResponseInterface $response, $photoSavePath = '', $saveName = '')
    {
        $body = $this->checkAndThrow($response);

        $crawler = new Crawler($body);
        // 教务信息
        $ret['info'] = [
            'year'   => $crawler->filter('#Label1')->text(),
            'term'   => $crawler->filter('#Label2')->text(),
            'remark' => $crawler->filter('#Label3')->text(),
        ];
        // 可报名列表
        $ret['list'] = Parser::table($crawler, '#DBGrid', [
            ['chk', function (Crawler $crawler, $getValueMethod) {
                return $crawler->filter('input')->attr('name');
            }],
            'name', 'type', '', 'can_apply', 'require', 'fit', 'limit', 'remark', 'markup',
        ], 0, 1);
        // 已报名列表
        $ret['applied'] = Parser::table($crawler, '#DBGridInfo', [
            'no', 'name', '', '', 'id_card', 'is_pay', 'original_no', 'reserve_type', 'reserve_grade', ['delete_id', function (Crawler $crawler, $getValueMethod) {
                if (preg_match('/\'(.*?)\'/', $crawler->filter('a')->attr('href'), $matches)) {
                    return str_replace('$', ":", $matches[1]);
                }

                return '';
            }],
        ], 8);
        // 学生信息
        $ret['student'] = [
            'photo'   => $crawler->filter('#xszp')->attr('src'),
            'id_card' => $crawler->filter('#Labsfzh')->text(),
        ];
        // 是否下载学生照片
        if ($photoSavePath) {
            if (!$saveName) {
                $saveName = 'student-photo-' . $this->getUsername() . '.png';
            }
            // 头像下载地址
            $downloadUrl = Config::get('url.student_photo');
            // 下载文件
            $response = $this->request('get', [$downloadUrl, [], [
                'sink' => $photoSavePath . $saveName,
            ]]);

            $ret['student']['photo_save'] = $saveName;
        }

        return $ret;
    }

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


Question:
{@inheritDoc}

@return \Cake\Collection\Iterator\FilterIterator

public function reject(callable $c)
    {
        return new FilterIterator($this->unwrap(), function ($key, $value, $items) use ($c) {
            return !$c($key, $value, $items);
        });
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        parent::visit($visitor, $generator, $data->content);
        $visitor->setHeader(
            'Location',
            $this->router->generate(
                'ezpublish_rest_loadContent',
                array('contentId' => $data->content->contentInfo->id)
            )
        );
        $visitor->setStatus(201);
    }

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


Question:
// setTasksDesiredState sets the desired state for all tasks for the given slots to the
// requested state

func (r *Orchestrator) setTasksDesiredState(ctx context.Context, batch *store.Batch, slots []orchestrator.Slot, newDesiredState api.TaskState) {
	for _, slot := range slots {
		for _, t := range slot {
			err := batch.Update(func(tx store.Tx) error {
				// time travel is not allowed. if the current desired state is
				// above the one we're trying to go to we can't go backwards.
				// we have nothing to do and we should skip to the next task
				if t.DesiredState > newDesiredState {
					// log a warning, though. we shouln't be trying to rewrite
					// a state to an earlier state
					log.G(ctx).Warnf(
						"cannot update task %v in desired state %v to an earlier desired state %v",
						t.ID, t.DesiredState, newDesiredState,
					)
					return nil
				}
				// update desired state
				t.DesiredState = newDesiredState

				return store.UpdateTask(tx, t)
			})

			// log an error if we get one
			if err != nil {
				log.G(ctx).WithError(err).Errorf("failed to update task to %v", newDesiredState.String())
			}
		}
	}
}

public function update_timecheckstate($time) {
        global $DB;
        if ($this->attempt->timecheckstate !== $time) {
            $this->attempt->timecheckstate = $time;
            $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id' => $this->attempt->id));
        }
    }

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


Question: Decodes byte <str> into <unicode>. Ignores any non-utf8 chars in <str>s

def safely_decode(unicode_or_str, encoding='utf-8'):
  '''  '''
  if isinstance(unicode_or_str, unicode):
    ustr = unicode_or_str
  elif isinstance(unicode_or_str, str):
    ustr = unicode_or_str.decode(encoding, 'ignore')
  else:
    raise Exception(u'Not of type unicode or str')

  return ustr

function encode(buffer, extra) {
  if (!extra) extra = 0
  var blen = buffer.length
  var lenbytes = vencode(blen)
  var mb = new Buffer(extra + blen + lenbytes.length)
  for (var i = 0; i < lenbytes.length; i++) {
    mb.writeUInt8(lenbytes[i], extra + i)
  }
  buffer.copy(mb, lenbytes.length + extra, 0, blen)
  return mb
}

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


Question:
adds methods to a constructor prototype
@method
@memberof Kinetic.Util.prototype
@param {Function} constructor
@param {Object} methods

function(constructor, methods) {
            var key;

            for (key in methods) {
                constructor.prototype[key] = methods[key];
            }
        }

public function bind(MapInterface $values): self
    {
        if (
            (string) $values->keyType() !== 'string' ||
            (string) $values->valueType() !== 'mixed'
        ) {
            throw new \TypeError('Argument 1 must be of type MapInterface<string, mixed>');
        }

        $this
            ->arguments
            ->filter(static function(string $name, Argument $argument): bool {
                return !$argument->optional() && !$argument->hasDefault();
            })
            ->foreach(static function(string $name) use ($values): void {
                if (!$values->contains($name)) {
                    throw new MissingArgument($name);
                }
            });
        $this
            ->arguments
            ->filter(static function(string $name) use ($values): bool {
                return $values->contains($name);
            })
            ->foreach(static function(string $name, Argument $argument) use ($values): void {
                $argument->validate($values->get($name));
            });

        $self = clone $this;
        $self->values = $values;

        return $self;
    }

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


Question:
Find users with verified emails.

@param \Cake\ORM\Query $query Query object
@param array $options Options
@return Query

public function findEmailVerified(Query $query, array $options) {
		$query->where([
			$this->_table->aliasField($this->_field('emailVerified')) => true,
		]);

		return $query;
	}

public function checkPassword(): bool
    {
        if (!isset($this->regex)) {
            return true;
        }

        return filter_var($this->password, FILTER_VALIDATE_REGEXP, [
            'options' => [
                'regexp' => $this->regex
            ]
        ]);
    }

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


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

func (s *RelationalDatabase) SetTags(v []*Tag) *RelationalDatabase {
	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: // literalType parses a literal type and returns a LiteralType AST

func (p *Parser) literalType() (*ast.LiteralType, error) {
	defer un(trace(p, "ParseLiteral"))

	return &ast.LiteralType{
		Token: p.tok.HCLToken(),
	}, nil
}

void buildCSSTypesDictionary()
  {
    String description;
    String value;
    TextSearchDictionaryEntry de;

    //search eval() expression
    description = "text/css";
    value = "text/css";
    de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009);
    v.add(de);

  }

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


Question: Byte swap (32 bit or 64 bit registers only) (i486).

public final void bswap(Register dst)
  {
    assert(dst.type() == REG_GPD || dst.type() == REG_GPQ);
    emitX86(INST_BSWAP, dst);
  }

def execute(self, state: GlobalState):

        address = _get_address_from_state(state)
        has_overflow = self._overflow_cache.get(address, False)
        has_underflow = self._underflow_cache.get(address, False)
        if has_overflow or has_underflow:
            return
        opcode = state.get_current_instruction()["opcode"]
        funcs = {
            "ADD": [self._handle_add],
            "SUB": [self._handle_sub],
            "MUL": [self._handle_mul],
            "SSTORE": [self._handle_sstore],
            "JUMPI": [self._handle_jumpi],
            "RETURN": [self._handle_return, self._handle_transaction_end],
            "STOP": [self._handle_transaction_end],
            "EXP": [self._handle_exp],
        }
        for func in funcs[opcode]:
            func(state)

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


Question:
from A means node.level == 0
            from . import B means node.level == 1
            from .A means node.level == 1

def handle_relative_import(self, node):

        no_file = os.path.abspath(os.path.join(self.filenames[-1], os.pardir))
        skip_init = False

        if node.level == 1:
            # Same directory as current file
            if node.module:
                name_with_dir = os.path.join(no_file, node.module.replace('.', '/'))
                if not os.path.isdir(name_with_dir):
                    name_with_dir = name_with_dir + '.py'
            # e.g. from . import X
            else:
                name_with_dir = no_file
                # We do not want to analyse the init file of the current directory
                skip_init = True
        else:
            parent = os.path.abspath(os.path.join(no_file, os.pardir))
            if node.level > 2:
                # Perform extra `cd ..` however many times
                for _ in range(0, node.level - 2):
                    parent = os.path.abspath(os.path.join(parent, os.pardir))
            if node.module:
                name_with_dir = os.path.join(parent, node.module.replace('.', '/'))
                if not os.path.isdir(name_with_dir):
                    name_with_dir = name_with_dir + '.py'
            # e.g. from .. import X
            else:
                name_with_dir = parent

        # Is it a file?
        if name_with_dir.endswith('.py'):
            return self.add_module(
                module=(node.module, name_with_dir),
                module_or_package_name=None,
                local_names=as_alias_handler(node.names),
                import_alias_mapping=retrieve_import_alias_mapping(node.names),
                from_from=True
            )
        return self.from_directory_import(
            (node.module, name_with_dir),
            not_as_alias_handler(node.names),
            as_alias_handler(node.names),
            retrieve_import_alias_mapping(node.names),
            skip_init=skip_init
        )

def get_neighbors( self, peer_hostport, con=None, path=None, peer_table=None ):

        if path is None:
            path = self.atlasdb_path

        if self.neighbors_timeout is None:
            self.neighbors_timeout = atlas_neighbors_timeout()

        peer_hostport = self.canonical_peer( peer_hostport )

        neighbors = None
        if peer_hostport == self.my_hostport:
            neighbors = atlas_get_live_neighbors( None, peer_table=peer_table )
        else:
            neighbors = atlas_peer_get_neighbors( self.my_hostport, peer_hostport, timeout=self.neighbors_timeout, peer_table=peer_table, path=path, con=con )

        if neighbors is not None:
            log.debug("%s: neighbors of %s are (%s): %s" % (self.my_hostport, peer_hostport, len(neighbors), ",".join(neighbors)))
        else:
            log.error("%s: failed to ask %s for neighbors" % (self.my_hostport, peer_hostport))

        return neighbors

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


Question: // SetId sets the Id field's value.

func (s *UpdateHostedZoneCommentInput) SetId(v string) *UpdateHostedZoneCommentInput {
	s.Id = &v
	return s
}

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

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

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


Question: *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*

def main(arguments=None):

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="qubits"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from . import workspace
        ws = workspace(
            log=log,
            pathToWorkspace=pathToWorkspace
        )
        ws.setup()
        return

    # IMPORT THE SIMULATION SETTINGS
    (allSettings,
     programSettings,
     limitingMags,
     sampleNumber,
     peakMagnitudeDistributions,
     explosionDaysFromSettings,
     extendLightCurveTail,
     relativeSNRates,
     lowerRedshiftLimit,
     upperRedshiftLimit,
     redshiftResolution,
     restFrameFilter,
     kCorrectionTemporalResolution,
     kCorPolyOrder,
     kCorMinimumDataPoints,
     extinctionType,
     extinctionConstant,
     hostExtinctionDistributions,
     galacticExtinctionDistribution,
     surveyCadenceSettings,
     snLightCurves,
     surveyArea,
     CCSNRateFraction,
     transientToCCSNRateFraction,
     extraSurveyConstraints,
     lightCurvePolyOrder,
     logLevel) = cu.read_in_survey_parameters(
        log,
        pathToSettingsFile=pathToSettingsFile
    )

    logFilePath = pathToOutputDirectory + "/qubits.log"
    del log
    log = _set_up_command_line_tool(
        level=str(logLevel),
        logFilePath=logFilePath
    )

    # dbConn, log = cu.settings(
    #     pathToSettingsFile=pathToSettingsFile,
    #     dbConn=False,
    #     log=True
    # )

    ## START LOGGING ##
    startTime = dcu.get_now_sql_datetime()
    log.info('--- STARTING TO RUN THE qubits AT %s' % (startTime,))

    resultsDict = {}

    pathToOutputPlotDirectory = pathToOutputDirectory + "/plots/"
    dcu.dryx_mkdir(
        log,
        directoryPath=pathToOutputPlotDirectory
    )

    pathToResultsFolder = pathToOutputDirectory + "/results/"
    dcu.dryx_mkdir(
        log,
        directoryPath=pathToResultsFolder
    )

    if not programSettings['Extract Lightcurves from Spectra'] and not programSettings['Generate KCorrection Database'] and not programSettings['Run the Simulation'] and not programSettings['Compile and Plot Results']:
        print "All stages of the simulatation have been switched off. Please switch on at least one stage of the simulation under the 'Programming Settings' in the settings file `%(pathToSettingsFile)s`" % locals()

    # GENERATE THE DATA FOR SIMULATIONS
    if programSettings['Extract Lightcurves from Spectra']:
        log.info('generating the Lightcurves')
        dg.generate_model_lightcurves(
            log=log,
            pathToSpectralDatabase=pathToSpectralDatabase,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            explosionDaysFromSettings=explosionDaysFromSettings,
            extendLightCurveTail=extendLightCurveTail,
            polyOrder=lightCurvePolyOrder
        )
        print "The lightcurve file can be found here: %(pathToOutputDirectory)stransient_light_curves.yaml" % locals()
        print "The lightcurve plots can be found in %(pathToOutputPlotDirectory)s" % locals()

    if programSettings['Generate KCorrection Database']:
        log.info('generating the kcorrection data')
        dg.generate_kcorrection_listing_database(
            log,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToSpectralDatabase=pathToSpectralDatabase,
            restFrameFilter=restFrameFilter,
            temporalResolution=kCorrectionTemporalResolution,
            redshiftResolution=redshiftResolution,
            redshiftLower=lowerRedshiftLimit,
            redshiftUpper=upperRedshiftLimit + redshiftResolution)
        log.info('generating the kcorrection polynomials')
        dg.generate_kcorrection_polynomial_database(
            log,
            pathToOutputDirectory=pathToOutputDirectory,
            restFrameFilter=restFrameFilter,
            kCorPolyOrder=kCorPolyOrder,  # ORDER OF THE POLYNOMIAL TO FIT
            kCorMinimumDataPoints=kCorMinimumDataPoints,
            redshiftResolution=redshiftResolution,
            redshiftLower=lowerRedshiftLimit,
            redshiftUpper=upperRedshiftLimit + redshiftResolution,
            plot=programSettings['Generate KCorrection Plots'])

        print "The k-correction database has been generated here: %(pathToOutputDirectory)sk_corrections" % locals()
        if programSettings['Generate KCorrection Plots']:
            print "The k-correction polynomial plots can also be found in %(pathToOutputDirectory)sk_corrections" % locals()

    if programSettings['Run the Simulation']:
        # CREATE THE OBSERVABLE UNIVERSE!
        log.info('generating the redshift array')
        redshiftArray = u.random_redshift_array(
            log,
            sampleNumber,
            lowerRedshiftLimit,
            upperRedshiftLimit,
            redshiftResolution=redshiftResolution,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])
        resultsDict['Redshifts'] = redshiftArray.tolist()

        log.info('generating the SN type array')
        snTypesArray = u.random_sn_types_array(
            log,
            sampleNumber,
            relativeSNRates,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])
        resultsDict['SN Types'] = snTypesArray.tolist()

        log.info('generating peak magnitudes for the SNe')
        peakMagnitudesArray = u.random_peak_magnitudes(
            log,
            peakMagnitudeDistributions,
            snTypesArray,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the SN host extictions array')
        hostExtinctionArray = u.random_host_extinction(
            log,
            sampleNumber,
            extinctionType,
            extinctionConstant,
            hostExtinctionDistributions,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the SN galactic extictions array')
        galacticExtinctionArray = u.random_galactic_extinction(
            log,
            sampleNumber,
            extinctionType,
            extinctionConstant,
            galacticExtinctionDistribution,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the raw lightcurves for the SNe')
        rawLightCurveDict = u.generate_numpy_polynomial_lightcurves(
            log,
            snLightCurves=snLightCurves,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the k-correction array for the SNe')
        kCorrectionArray = u.build_kcorrection_array(
            log,
            redshiftArray,
            snTypesArray,
            snLightCurves,
            pathToOutputDirectory=pathToOutputDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the observed lightcurves for the SNe')
        observedFrameLightCurveInfo, peakAppMagList = u.convert_lightcurves_to_observered_frame(
            log,
            snLightCurves=snLightCurves,
            rawLightCurveDict=rawLightCurveDict,
            redshiftArray=redshiftArray,
            snTypesArray=snTypesArray,
            peakMagnitudesArray=peakMagnitudesArray,
            kCorrectionArray=kCorrectionArray,
            hostExtinctionArray=hostExtinctionArray,
            galacticExtinctionArray=galacticExtinctionArray,
            restFrameFilter=restFrameFilter,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            polyOrder=lightCurvePolyOrder,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the survey observation cadence')
        cadenceDictionary = ss.survey_cadence_arrays(
            log,
            surveyCadenceSettings,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('determining if the SNe are discoverable by the survey')
        discoverableList = ss.determine_if_sne_are_discoverable(
            log,
            redshiftArray=redshiftArray,
            limitingMags=limitingMags,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info(
            'determining the day (if and) when each SN is first discoverable by the survey')
        ripeDayList = ss.determine_when_sne_are_ripe_for_discovery(
            log,
            redshiftArray=redshiftArray,
            limitingMags=limitingMags,
            discoverableList=discoverableList,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            plot=programSettings['Plot Simulation Helper Plots'])

        # log.info('determining the day when each SN is disappears fainter than the survey limiting mags')
        # disappearDayList = determine_when_discovered_sne_disappear(
        #     log,
        #     redshiftArray=redshiftArray,
        #     limitingMags=limitingMags,
        #     ripeDayList=ripeDayList,
        #     observedFrameLightCurveInfo=observedFrameLightCurveInfo,
        #     plot=programSettings['Plot Simulation Helper Plots'])

        log.info('determining if and when each SN is discovered by the survey')
        lightCurveDiscoveryDayList, surveyDiscoveryDayList, snCampaignLengthList = ss.determine_if_sne_are_discovered(
            log,
            limitingMags=limitingMags,
            ripeDayList=ripeDayList,
            cadenceDictionary=cadenceDictionary,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            extraSurveyConstraints=extraSurveyConstraints,
            plot=programSettings['Plot Simulation Helper Plots'])

        resultsDict[
            'Discoveries Relative to Peak Magnitudes'] = lightCurveDiscoveryDayList
        resultsDict[
            'Discoveries Relative to Survey Year'] = surveyDiscoveryDayList
        resultsDict['Campaign Length'] = snCampaignLengthList
        resultsDict['Cadence Dictionary'] = cadenceDictionary
        resultsDict['Peak Apparent Magnitudes'] = peakAppMagList

        now = datetime.now()
        now = now.strftime("%Y%m%dt%H%M%S")
        fileName = pathToOutputDirectory + \
            "/simulation_results_%s.yaml" % (now,)
        stream = file(fileName, 'w')
        yamlContent = dict(allSettings.items() + resultsDict.items())
        yaml.dump(yamlContent, stream, default_flow_style=False)
        stream.close()

        print "The simulation output file can be found here: %(fileName)s. Remember to update your settings file 'Simulation Results File Used for Plots' parameter with this filename before compiling the results." % locals()
        if programSettings['Plot Simulation Helper Plots']:
            print "The simulation helper-plots found in %(pathToOutputPlotDirectory)s" % locals()

    # COMPILE AND PLOT THE RESULTS
    if programSettings['Compile and Plot Results']:
        pathToYamlFile = pathToOutputDirectory + "/" + \
            programSettings['Simulation Results File Used for Plots']
        result_log = r.log_the_survey_settings(log, pathToYamlFile)
        snSurveyDiscoveryTimes, lightCurveDiscoveryTimes, snTypes, redshifts, cadenceDictionary, peakAppMagList, snCampaignLengthList = r.import_results(
            log, pathToYamlFile)
        snRatePlotLink, totalRate, tooFaintRate, shortCampaignRate = r.determine_sn_rate(
            log,
            lightCurveDiscoveryTimes,
            snSurveyDiscoveryTimes,
            redshifts,
            surveyCadenceSettings=surveyCadenceSettings,
            lowerRedshiftLimit=lowerRedshiftLimit,
            upperRedshiftLimit=upperRedshiftLimit,
            redshiftResolution=redshiftResolution,
            surveyArea=surveyArea,
            CCSNRateFraction=CCSNRateFraction,
            transientToCCSNRateFraction=transientToCCSNRateFraction,
            peakAppMagList=peakAppMagList,
            snCampaignLengthList=snCampaignLengthList,
            extraSurveyConstraints=extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """
## Results ##

This simulated survey discovered a total of **%s** transients per year. An extra **%s** transients were detected but deemed too faint to constrain a positive transient identification and a further **%s** transients where detected but an observational campaign of more than **%s** days could not be completed to ensure identification. See below for the various output plots.

        """ % (totalRate, tooFaintRate, shortCampaignRate, extraSurveyConstraints["Observable for at least ? number of days"])
        cadenceWheelLink = r.plot_cadence_wheel(
            log,
            cadenceDictionary,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (cadenceWheelLink,)
        discoveryMapLink = r.plot_sn_discovery_map(
            log,
            snSurveyDiscoveryTimes,
            peakAppMagList,
            snCampaignLengthList,
            redshifts,
            extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (discoveryMapLink,)
        ratioMapLink = r.plot_sn_discovery_ratio_map(
            log,
            snSurveyDiscoveryTimes,
            redshifts,
            peakAppMagList,
            snCampaignLengthList,
            extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (ratioMapLink,)
        result_log += """%s""" % (snRatePlotLink,)

        now = datetime.now()
        now = now.strftime("%Y%m%dt%H%M%S")
        mdLogPath = pathToResultsFolder + \
            "simulation_result_log_%s.md" % (now,)
        mdLog = open(mdLogPath, 'w')
        mdLog.write(result_log)
        mdLog.close()

        dmd.convert_to_html(
            log=log,
            pathToMMDFile=mdLogPath,
            css="amblin"
        )

        print "Results can be found here: %(pathToResultsFolder)s" % locals()
        html = mdLogPath.replace(".md", ".html")
        print "Open this file in your browser: %(html)s" % locals()

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return

def init_read_line(self):
        """"""
        format_list = self._format_list
        self._re_cvt = self.match_input_fmt(format_list)
        regexp0_str = "".join([subs[0] for subs in self._re_cvt])
        self._regexp_str = regexp0_str
        self._re = re.compile(regexp0_str)
        self._match_exps = [
            subs[1] for subs in self._re_cvt if subs[1] is not None
        ]
        self._divisors = [subs[2] for subs in self._re_cvt if subs[2] is not None]
        self._in_cvt_fns = [
            subs[3] for subs in self._re_cvt if subs[3] is not None
        ]
        self._read_line_init = True

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


Question: // WithCidr adds the cidr to the get fqdn cache params

func (o *GetFqdnCacheParams) WithCidr(cidr *string) *GetFqdnCacheParams {
	o.SetCidr(cidr)
	return o
}

public function set(string $uri, string $query, EsiResponse $data)
    {

        if ($this->is_memcached)
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), 0);
        else
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), $this->flags, 0);
    }

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


Question:
Return an instance of this class.
@codeCoverageIgnore
@since 1.0.0

@param array $request_data Current REQUEST superglobals

@return ui A single instance of this class

public static function get_instance( $request_data ) {

		// If the single instance hasn't been set, set it now.
		if ( isset( self::$instance ) ) {
			self::$instance->data = $request_data;
		} else {
			self::$instance       = new self;
			self::$instance->data = $request_data;
			self::$instance->auto_load();
		}

		return self::$instance;

	}

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question:
Gets the value(s) for mapping ().
creating it if it does
not exist. Will not return null.

Definition:
Identifies a concept from an external specification that roughly corresponds to this element

public java.util.List<Mapping> getMapping() {
		if (myMapping == null) {
			myMapping = new java.util.ArrayList<Mapping>();
		}
		return myMapping;
	}

protected String nodeType(short type) {
        switch(type) {
        case Node.ELEMENT_NODE:                return "Element";
        case Node.DOCUMENT_TYPE_NODE:          return "Document Type";
        case Node.ENTITY_NODE:                 return "Entity";
        case Node.ENTITY_REFERENCE_NODE:       return "Entity Reference";
        case Node.NOTATION_NODE:               return "Notation";
        case Node.TEXT_NODE:                   return "Text";
        case Node.COMMENT_NODE:                return "Comment";
        case Node.CDATA_SECTION_NODE:          return "CDATA Section";
        case Node.ATTRIBUTE_NODE:              return "Attribute";
        case Node.PROCESSING_INSTRUCTION_NODE: return "Processing Instruction";
        default: break;
        }
        return Short.toString(type);
    }

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


Question:
Gets the contents of the files that are involved in the log message.

@param string $file File path

@return array

private function getFileContents($file)
    {
        if (!isset($this->filesContent[$file])) {
            $this->filesContent[$file] = file_exists($file) ? file($file) : [];
        }

        return $this->filesContent[$file];
    }

public static function readFile($strFilePath)
    {
        $result = "";
        $handle = fopen($strFilePath, "r");
        while (!feof($handle)) {
            $result .= fread($handle, 8000);
        }
        fclose($handle);

        return $result;
    }

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


Question:
Retrieves the first unscanned scan node.

    Returns:
      SourceScanNode: scan node or None if not available.

def GetUnscannedScanNode(self):

    root_scan_node = self._scan_nodes.get(self._root_path_spec, None)
    if not root_scan_node or not root_scan_node.scanned:
      return root_scan_node

    return root_scan_node.GetUnscannedSubNode()

def _scan_directory(directory, sentinel, depth=0):
    '''
    '''
    directory = os.path.abspath(directory)
    real_directory = os.path.realpath(directory)

    if depth < max_directory_depth and real_directory not in sentinel \
            and os.path.isdir(directory):
        sentinel.add(real_directory)

        for item in os.listdir(directory):
            if item in ('.', '..'):
                # I'm not sure if this is even needed any more.
                continue

            p = os.path.abspath(os.path.join(directory, item))
            if (os.path.isdir(p) and _dir_ignore.search(p)) \
                    or (os.path.isfile(p) and _ext_ignore.search(p)):
                continue

            yield p

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


Question: Configures a {@link com.google.inject.Binder} via the exposed methods.

@Override
    protected void configure() {

        // Create HK2 service locator and bind jersey injections
        ServiceLocator locator = ServiceLocatorFactory.getInstance().create(null);
        bind(ServiceLocator.class).toInstance(locator);

        bind(VertxContainer.class).to(DefaultVertxContainer.class);
        bind(JerseyServer.class).to(GuiceJerseyServer.class);
        bind(JerseyHandler.class).to(DefaultJerseyHandler.class);
        bind(JerseyOptions.class).to(DefaultJerseyOptions.class);
        bind(JerseyServerOptions.class).to(DefaultJerseyOptions.class);
        bind(ContainerResponseWriterProvider.class).to(VertxResponseWriterProvider.class);
        bind(MessageBodyWriter.class).to(WriteStreamBodyWriter.class).in(Singleton.class);
        bind(ApplicationConfigurator.class).toProvider(Providers.of(null));

        Multibinder.newSetBinder(binder(), VertxRequestProcessor.class);
        Multibinder.newSetBinder(binder(), VertxResponseProcessor.class);
        Multibinder.newSetBinder(binder(), VertxPostResponseProcessor.class);

        Multibinder.newSetBinder(binder(), ContainerRequestFilter.class);
        Multibinder.newSetBinder(binder(), ContainerResponseFilter.class);
        Multibinder.newSetBinder(binder(), ReaderInterceptor.class);
        Multibinder.newSetBinder(binder(), WriterInterceptor.class);
        Multibinder.newSetBinder(binder(), ModelProcessor.class);
        Multibinder.newSetBinder(binder(), ContainerLifecycleListener.class);
        Multibinder.newSetBinder(binder(), ApplicationEventListener.class);
        Multibinder.newSetBinder(binder(), ExceptionMapper.class);

    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

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


Question: Check is it have generated MoxyReflector without usage of reflection API

private static boolean hasMoxyReflector() {
		if (hasMoxyReflector != null) {
			return hasMoxyReflector;
		}

		try {
			new MoxyReflector();

			hasMoxyReflector = true;
		} catch (NoClassDefFoundError error) {
			hasMoxyReflector = false;
		}

		return hasMoxyReflector;
	}

public static <T> T readKryo(File file) {
    try {
      byte[] bytes = CompressionUtil.decodeBZRaw(Files.readAllBytes(file.toPath()));
      Input input = new Input(buffer.get(), 0, bytes.length);
      return (T) new KryoReflectionFactorySupport().readClassAndObject(input);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

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


Question: // UnsetLocalSection removes the entire named section from the system config

func (c *Configuration) UnsetLocalSection(key string) (string, error) {
	return c.gitConfigWrite("--local", "--remove-section", key)
}

public function apply(AbstractNode $node)
    {
        if (preg_match('#[A-Za-z0-9]+Constants$#', $node->getName()) === 0 ||
            preg_match('#\\\\Shared\\\\#', $node->getNamespaceName()) !== 0) {
            return;
        }

        $message = sprintf(
            'The environment configuration is not lie in "Shared" layer. That violates the rule "%s"',
            static::RULE
        );

        $this->addViolation($node, [$message]);
    }

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


Question:
Gets a single data point.

@param array $indices An array of all value indices

@return string

public function datum($indices)
    {
        $this->assertData();

        $index = $this->index($indices);
        if (isset($this->data[$index])) {
            return $this->data[$index];
        } else {
            return null;
        }
    }

protected function extractPayload($model, $comments = '')
    {
        $payload = [];
        preg_match('/@payload\ (.*)\n/i', $comments, $doc);
        $isArray = false;
        if (count($doc)) {
            $namespace = str_replace('{__API__}', $model, $doc[1]);
            if (false !== strpos($namespace, '[') && false !== strpos($namespace, ']')) {
                $namespace = str_replace(']', '', str_replace('[', '', $namespace));
                $isArray = true;
            }
            $payload = $this->extractModelFields($namespace);
            $reflector = new \ReflectionClass($namespace);
            $shortName = $reflector->getShortName();
        } else {
            $namespace = $model;
            $shortName = $model;
        }

        return [$namespace, $shortName, $payload, $isArray];
    }

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


Question:
Merge subquery statement if contains.

@return Select select statement

public SelectStatement mergeSubqueryStatement() {
        SelectStatement result = processLimitForSubquery();
        processItems(result);
        processOrderByItems(result);
        result.setParametersIndex(getParametersIndex());
        return result;
    }

def _generate_reversed_sql(self, keys, changed_keys):

        for key in keys:
            if key not in changed_keys:
                continue
            app_label, sql_name = key
            old_item = self.from_sql_graph.nodes[key]
            new_item = self.to_sql_graph.nodes[key]
            if not old_item.reverse_sql or old_item.reverse_sql == RunSQL.noop or new_item.replace:
                continue

            # migrate backwards
            operation = ReverseAlterSQL(sql_name, old_item.reverse_sql, reverse_sql=old_item.sql)
            sql_deps = [n.key for n in self.from_sql_graph.node_map[key].children]
            sql_deps.append(key)
            self.add_sql_operation(app_label, sql_name, operation, sql_deps)

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


Question: Allows for objects with no required groups

def check_membership(self, groups):
        '''  '''
        if not groups or groups == ['']:
            return True
        if self.request.user.is_superuser:
            return True
        user_groups = self.request.user.groups.values_list("name", flat=True)
        return set(groups).intersection(set(user_groups))

def can_produce_rules(self):

        if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"):
            return False
        return javabridge.call(self.jobject, "canProduceRules", "()Z")

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


Question:
Returns current url.

@param \Psr\Http\Message\UriInterface $uri Server Request
@param bool $getFullUrl Get the full URL or just the path
@return string

protected function _getUrlFromRequest(UriInterface $uri, $getFullUrl = false)
    {
        if (property_exists($uri, 'base')) {
            $uri = $uri->withPath($uri->base . $uri->getPath());
        }

        if ($getFullUrl) {
            return (string)$uri;
        }

        return $uri->getPath();
    }

public static String toUrl(ProviderInfo providerInfo) {
        String uri = providerInfo.getProtocolType() + "://" + providerInfo.getHost() + ":" + providerInfo.getPort();
        uri += StringUtils.trimToEmpty(providerInfo.getPath());
        StringBuilder sb = new StringBuilder();
        if (providerInfo.getRpcVersion() > 0) {
            sb.append("&").append(ProviderInfoAttrs.ATTR_RPC_VERSION).append("=").append(providerInfo.getRpcVersion());
        }
        if (providerInfo.getSerializationType() != null) {
            sb.append("&").append(ProviderInfoAttrs.ATTR_SERIALIZATION).append("=")
                .append(providerInfo.getSerializationType());
        }
        for (Map.Entry<String, String> entry : providerInfo.getStaticAttrs().entrySet()) {
            sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
        if (sb.length() > 0) {
            uri += sb.replace(0, 1, "?").toString();
        }
        return uri;
    }

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


Question: Take action when AbortProcessing is raised.

def AbortProcessing(obj, eng, callbacks, exc_info):
        """"""
        msg = "Processing was aborted for object: {0}".format(obj.id)
        eng.log.debug(msg)
        raise Break

def source
      case options[:processors].present?
      when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors])
      else
        @env.send(@method_name)
      end
    end

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


Question: [VARIABLE "my_job_name"]

public boolean cancelJobFromId(String jobName) {
    // [START ]
    JobId jobId = JobId.of(jobName);
    boolean success = bigquery.cancel(jobId);
    if (success) {
      // job was cancelled
    } else {
      // job was not found
    }
    // [END ]
    return success;
  }

public ListJobsRequest withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

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


Question:
Given two collections ``a`` and ``b``, this will return the mean of all
    distances. ``distance_function`` is used to determine the distance between
    two elements.

    Example::

        >>> single([1, 2], [3, 100], lambda x, y: abs(x-y))
        26

def average(a, b, distance_function):

    distances = [distance_function(x, y)
                 for x in a for y in b]
    return sum(distances) / len(distances)

def find_path(self, test_function=None, on_targets=False):

        assert self.has_referential_domain(), "need context set"

        if not test_function:
            test_function = lambda x, y: True

        def find_path_inner(part, prefix):
            name, structure = part
            if test_function(name, structure):
                yield prefix + [name]
            if isinstance(structure, DictCell):
                for sub_structure in structure:
                    for prefix2 in find_path_inner(sub_structure,\
                            prefix[:] + [name]):
                        yield prefix2

        prefix = []
        if on_targets:
            # apply search to the first target
            results = []
            for _, instance in self.iter_singleton_referents():
                for part in instance:
                    for entry in find_path_inner(part, prefix[:]):
                        results.append(['target'] + entry)
                while results:
                    yield results.pop()
                break # only use first instance
        else:
            # apply search to self
            for part in self:
                for entry in find_path_inner(part, prefix[:]):
                    yield entry

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


Question: // headerTDKey = headerPrefix + num (uint64 big endian) + hash + headerTDSuffix

func headerTDKey(number uint64, hash common.Hash) []byte {
	return append(headerKey(number, hash), headerTDSuffix...)
}

protected function mb_chr($code)
    {
        if (function_exists('mb_chr')) {
            return mb_chr($code);
        } else {
            if (0x80 > $code %= 0x200000) {
                $s = chr($code);
            } elseif (0x800 > $code) {
                $s = chr(0xc0 | $code >> 6) . chr(0x80 | $code & 0x3f);
            } elseif (0x10000 > $code) {
                $s = chr(0xe0 | $code >> 12) . chr(0x80 | $code >> 6 & 0x3f) . chr(0x80 | $code & 0x3f);
            } else {
                $s = chr(0xf0 | $code >> 18) . chr(0x80 | $code >> 12 & 0x3f) . chr(0x80 | $code >> 6 & 0x3f) . chr(0x80 | $code & 0x3f);
            }

            return $s;
        }
    }

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


Question:
Get unread applications

@param \Jobs\Entity\JobInterface $job
@return array|bool|\Doctrine\MongoDB\ArrayIterator|\Doctrine\MongoDB\Cursor|\Doctrine\MongoDB\EagerCursor|mixed|null

public function loadUnreadApplicationsForJob($job)
    {
        $auth=$this->getService('AuthenticationService');
        $qb=$this->createQueryBuilder()
                  ->field("readBy")->notIn(array($auth->getUser()->getId()))
                  ->field("job")->equals(new \MongoId($job->getId()));
        return $qb->getQuery()->execute();
    }

func (s *DbSession) FindAll(query Q, document Document) (interface{}, error) {
	fn := func(q *mgo.Query, result interface{}) error {
		return q.All(result)
	}
	return s.executeFindAll(query, document, fn)
}

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


Question:
Decode the Global ID and get just the ID.

@param  string  $globalID
@return string

public function decodeID(string $globalID): string
    {
        [$type, $id] = self::decode($globalID);

        return $id;
    }

function preGenHash(sIdf, oStateData){
			var sEncodedIdf = window.encodeURIComponent(sIdf);
			var sEncodedData = window.encodeURIComponent(window.JSON.stringify(oStateData));
			return sEncodedIdf + sIdSeperator + sEncodedData;
		}

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


Question: Set color for all filling operations

def set_fill_color(self,r,g=-1,b=-1):
        ""
        if((r==0 and g==0 and b==0) or g==-1):
            self.fill_color=sprintf('%.3f g',r/255.0)
        else:
            self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
        self.color_flag=(self.fill_color!=self.text_color)
        if(self.page>0):
            self._out(self.fill_color)

def _change_to_noFill_bg(self):

        self._remove_bg()
        bg = self.get_or_add_bg()
        bg.add_noFill_bgPr()
        return bg

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


Question: 1D projection operator

def prox_gradf_lim12(x, step, j=None, Xs=None, boundary=None):
    """"""
    # TODO: split boundary in x1 and x2 and use appropriate operator
    if j == 0:
        x -= step*grad_fx(Xs[0][0], Xs[1][0])
    if j == 1:
        y = x
        y -= step*grad_fy(Xs[0][0], Xs[1][0])
    return prox_lim12(x, step, j=j, Xs=Xs, boundary=boundary)

public Matrix3d scale(double xyz, Matrix3d dest) {
        return scale(xyz, xyz, xyz, dest);
    }

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


Question:
pop

@param string $queue

@return QueueMessage
@throws \Exception
@throws \InvalidArgumentException
@throws \Throwable

public function pop($queue = null)
    {
        $queue = $queue ?: $this->queue;

        $now = new \DateTimeImmutable('now');

        $sql = 'SELECT * FROM ' . $this->table .
            ' WHERE queue = :queue AND visibility < :visibility' .
            ' AND (reserved IS NULL OR reserved < :reserved)' .
            ' FOR UPDATE';

        $this->pdo->beginTransaction();

        $stat = $this->pdo->prepare($sql);
        $stat->bindValue(':queue', $queue);
        $stat->bindValue(':visibility', $now->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
        $stat->bindValue(
            ':reserved',
            $now->modify('-' . $this->timeout . 'seconds')->format('Y-m-d H:i:s'),
            \PDO::PARAM_STR
        );

        try {
            $stat->execute();

            $data = $stat->fetch(\PDO::FETCH_ASSOC);

            if (!$data) {
                $this->pdo->commit();

                return null;
            }

            $data['attempts']++;

            $sql = 'UPDATE ' . $this->table . ' SET reserved = :reserved, attempts = :attempts WHERE id = :id';

            $stat = $this->pdo->prepare($sql);
            $stat->bindValue(':reserved', $now->format('Y-m-d H:i:s'));
            $stat->bindValue(':attempts', $data['attempts'] + 1);
            $stat->bindValue(':id', $data['id']);

            $stat->execute();

            $this->pdo->commit();
        } catch (\Throwable $t) {
            $this->pdo->rollBack();
            throw $t;
        }

        $message = new QueueMessage();

        $message->setId($data['id']);
        $message->setAttempts($data['attempts']);
        $message->setBody(json_decode($data['body'], true));
        $message->setRawBody($data['body']);
        $message->setQueueName($queue);

        return $message;
    }

public function createPromise($replyTo, $correlationId, $timeout)
    {
        $replyQueue = $this->context->createQueue($replyTo);

        $receive = function (Promise $promise, $promiseTimeout) use ($replyQueue, $timeout, $correlationId) {
            $runTimeout = $promiseTimeout ?: $timeout;
            $endTime = time() + ((int) ($runTimeout / 1000));
            $consumer = $this->context->createConsumer($replyQueue);

            do {
                if ($message = $consumer->receive($runTimeout)) {
                    if ($message->getCorrelationId() === $correlationId) {
                        $consumer->acknowledge($message);

                        return $message;
                    }

                    $consumer->reject($message, true);
                }
            } while (time() < $endTime);

            throw TimeoutException::create($runTimeout, $correlationId);
        };

        $receiveNoWait = function () use ($replyQueue, $correlationId) {
            static $consumer;

            if (null === $consumer) {
                $consumer = $this->context->createConsumer($replyQueue);
            }

            if ($message = $consumer->receiveNoWait()) {
                if ($message->getCorrelationId() === $correlationId) {
                    $consumer->acknowledge($message);

                    return $message;
                }

                $consumer->reject($message, true);
            }
        };

        $finally = function (Promise $promise) use ($replyQueue) {
            if ($promise->isDeleteReplyQueue() && method_exists($this->context, 'deleteQueue')) {
                $this->context->deleteQueue($replyQueue);
            }
        };

        return new Promise($receive, $receiveNoWait, $finally);
    }

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


Question:
Call for the first image being tracked

@param image Most recent video image.

public void initialize(PyramidDiscrete<I> image ) {
		if( previousDerivX == null || previousDerivX.length != image.getNumLayers()
				|| previousImage.getInputWidth() != image.getInputWidth() || previousImage.getInputHeight() != image.getInputHeight() ) {
			declareDataStructures(image);
		}

		for( int i = 0; i < image.getNumLayers(); i++ ) {
			gradient.process(image.getLayer(i), previousDerivX[i], previousDerivY[i]);
		}

		previousImage.setTo(image);
	}

public function capture($transaction_id, $args)
    {
        $url = 'transactions/' . $transaction_id . '/captures';

        $api_response = $this->paylike->client->request('POST', $url, $args);

        return $api_response->json['transaction'];
    }

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


Question: // for existing usage

func SumTarLayer(tarReader io.Reader, json io.Reader, out io.Writer) (string, error) {
	return SumTarLayerVersioned(tarReader, json, out, tarsum.Version0)
}

func (w *Worktree) Status() (Status, error) {
	var hash plumbing.Hash

	ref, err := w.r.Head()
	if err != nil && err != plumbing.ErrReferenceNotFound {
		return nil, err
	}

	if err == nil {
		hash = ref.Hash()
	}

	return w.status(hash)
}

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


Question:
Has

@access public
@param string $id
@return bool

public function has($id) {
		$source = $id;
		while (is_string($source) && isset($this->getter[$source])) {
			$source = $this->getter[$source];
		}
		if (!is_string($source)) {
			return $source instanceof \Closure;
		} else {
			if (isset($this->instance[$source]) || class_exists($source)) {
				return true;
			}
			return false;
		}
	}

protected function getUserInfo($uid) {
        static $userinfo=array();
        if(!isset($userinfo[$uid])){
             $userinfo[$uid] = Db::table($this->prefix.$this->_config['auth_user'])->where(array('uid'=>$uid))->find();
        }
        return $userinfo[$uid];
    }

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


Question:
Method checks if Amazon Login button can be showed

@return bool
@throws oxConnectionException

public function showAmazonPayButton()
    {
        return (
            $this->isActive() === true
            && $this->getConfig()->isSsl() === true
            && $this->getModule()->isActive() === true
            && (string)$this->getSession()->getVariable('amazonOrderReferenceId') === ''
        );
    }

def do_connect(self, arg):
        '''  '''
        if self.arm.is_connected():
            print(self.style.error('Error: ', 'Arm is already connected.'))
        else:
            try:
                port = self.arm.connect()
                print(self.style.success('Success: ',
                                         'Connected to \'{}\'.'.format(port)))
            except r12.ArmException as e:
                print(self.style.error('Error: ', str(e)))

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


Question:
Force path to be a directory

..and ensure the trailing separator (except for root path)

@param string $path

@return string

public static function directory( string $path ): string {
    return ltrim( rtrim( $path, static::DIRECTORY_SEPARATOR ) . static::DIRECTORY_SEPARATOR, static::DIRECTORY_SEPARATOR );
  }

def in_source_dir(*paths)
      paths.reduce(source) do |base, path|
        Jekyll.sanitized_path(base, path)
      end
    end

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


Question: Store code or a file. Returns a tuple containing the uid and shortid

def store(
            self, type, nick, time, fmt=None, code=None, filename=None,
            mime=None, data=None, makeshort=True):

        uid = str(uuid.uuid4())
        shortid = short_key() if makeshort else None

        paste = assign_params(self.build_paste, locals())()
        self._store(uid, paste, data)
        if nick:
            self._storeLog(nick, time, uid)
        return uid, shortid

def get_identities(self, item):

        item = item['data']
        for identity in self.issue_roles:
            if item[identity]:
                user = self.get_sh_identity(item[identity])
                if user:
                    yield user

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


Question:
/*
Remove the CommitPoint(s) in the commitsToDelete list by decRef'ing
all files from each SegmentInfos.
*/

func (fd *IndexFileDeleter) deleteCommits() {
	if size := len(fd.commitsToDelete); size > 0 {
		// First decref all files that had been referred to by the
		// now-deleted commits:
		for _, commit := range fd.commitsToDelete {
			if fd.infoStream.IsEnabled("IFD") {
				fd.infoStream.Message("IFD", "deleteCommits: now decRef commit '%v'",
					commit.segmentsFileName)
			}
			fd.decRefFiles(commit.files)
		}
		fd.commitsToDelete = nil

		// Now compact commits to remove deleted ones (preserving the sort):
		var writeTo = 0
		for readFrom, commit := range fd.commits {
			if !commit.IsDeleted() && readFrom != writeTo {
				fd.commits[writeTo] = commit
				writeTo++
			}
		}
		for i, _ := range fd.commits[writeTo:] {
			fd.commits[i] = nil
		}
		fd.commits = fd.commits[:writeTo]
	}
}

private function clearEntities()
    {
        $this->nodeEntities = array();
        $this->relationEntities = array();

        $this->nodeEntitiesToRemove = array();
        $this->relationEntitiesToRemove = array();

        $this->startNodeRelations = array();
        $this->endNodeRelations = array();
    }

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


Question:
Counts all the Record entries in the database
@param Query $query
@return int

public function countByQuery($query)
    {
        $queryCount = clone $query;
        $queryCount->setCols('count(*) as count');
        $result = $this->getDB()->execute($queryCount);

        if ($result->numRows()) {
            $row = $result->fetchResult();

            return (int)$row['count'];
        }

        return false;
    }

protected function _ensureTrackData()
    {
        if (! isset($this->_respTrackData['gtr_code'], $this->_respTrackData['gtr_name'])) {
            $select = $this->db->select();
            $select->from('gems__tracks')
                ->where('gtr_id_track = ?', $this->_respTrackData['gr2t_id_track']);

            if ($trackData = $this->db->fetchRow($select)) {
                $this->_respTrackData = $this->_respTrackData + $trackData;
            } else {
                $trackId = $this->_respTrackId;
                throw new \Gems_Exception("Track data missing for respondent track $trackId.");
            }
        }
    }

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


Question:
// List plans.
//
//

func (s *PlansService) List(ctx context.Context, opt *PlansListOpts) (*plan.PlanList, error) {
	planList := &plan.PlanList{}
	return planList, s.client.List(ctx, plansUrl, opt, planList)
}

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question: append change from VCD file signal data series

def value_change(self, vcdId, value):
        ''''''
        self.idcode2series[vcdId].append((self.now, value))

def update(self):
        """"""
        self.filename = self.parent.info.dataset.filename

        self.chan = self.parent.info.dataset.header['chan_name']
        for chan in self.chan:
            self.idx_chan.addItem(chan)

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


Question: Round-robin slave balancer

def rotate_slaves(self):
        ""
        slaves = self.sentinel_manager.discover_slaves(self.service_name)
        if slaves:
            if self.slave_rr_counter is None:
                self.slave_rr_counter = random.randint(0, len(slaves) - 1)
            for _ in xrange(len(slaves)):
                self.slave_rr_counter = (
                    self.slave_rr_counter + 1) % len(slaves)
                slave = slaves[self.slave_rr_counter]
                yield slave
        # Fallback to the master connection
        try:
            yield self.get_master_address()
        except MasterNotFoundError:
            pass
        raise SlaveNotFoundError('No slave found for %r' % (self.service_name))

@Override
    public void rebalance() {
        double target = evenDistribution();
        final double myLoad = myLoad();
        if (myLoad > target) {
            LOG.info("Smart Rebalance triggered. Load: %s. Target: %s", myLoad, target);
            drainToLoad((long) target);
        }
    }

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


Question: Draw the figures and those that are shared and have been changed

def draw(self):
        """"""
        for fig in self.figs2draw:
            fig.canvas.draw()
        self._figs2draw.clear()

public ItemsSketch<T> getResult() {
    if (gadget_ == null) {
      return ItemsSketch.getInstance(maxK_, comparator_);
    }
    return ItemsSketch.copy(gadget_); //can't have any externally owned handles.
  }

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


Question:
Load Configs Properties From Given Configuration

@return StdArray|false

function load()
    {
        if ( $this->_isProcessingLoad() )
            throw new \RuntimeException(sprintf(
                'Conflict while loading config (%s); another process interrupt loading (%s).'
                    , $this->path
                    , static::$isProcessingLoading
            ));

        $this->_setFlagProcessingLoad();

        $path = $this->path;

        ## Try to load specified config
        #
        $config = $this->_loadGlobPattern($path);

        $fallBackDirectories = [];

        ## First try too load on initial system directory
        #
        $fallBackDir = rtrim( PT_DIR_CONFIG_INITIAL , '\\/' );
        if (strpos($fallBackDir, dirname($path)) !== 0)
            array_push(
                $fallBackDirectories
                , $fallBackDir
            );

        ## Looking in Default Config Directory
        #
        $fallBackDir = rtrim( PT_DIR_CONFIG , '\\/' );
        if (strpos($fallBackDir, dirname($path)) !== 0)
            array_push(
                $fallBackDirectories
                , $fallBackDir
            );

        if ($preConfig = $this->_loadFromDirectories($fallBackDirectories) )
            $config = ($config) ? $preConfig->withMergeRecursive($config) : $preConfig;

        $this->_setFlagProcessingLoad(false);
        return $config;
    }

private function setDefinitionProperties(Definition $definition, array $array)
    {
        if (isset($array['public'])) {
            $definition->setPublic($array['public']);
        }

        if (isset($array['abstract'])) {
            $definition->setAbstract($array['abstract']);
        }

        if (isset($array['scope'])) {
            $definition->setScope($array['scope']);
        }

        if (isset($array['file'])) {
            $definition->setFile($array['file']);
        }
    }

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


Question: Adds the match stage according to the operator.

protected function addMatch(Builder $aggregationBuilder, string $field, string $matchField, string $operator, string $value)
    {
        switch ($operator) {
            case self::PARAMETER_BETWEEN:
                $rangeValue = explode('..', $value);

                $rangeValue = $this->normalizeBetweenValues($rangeValue);
                if (null === $rangeValue) {
                    return;
                }

                $aggregationBuilder->match()->field($matchField)->gte($rangeValue[0])->lte($rangeValue[1]);

                break;
            case self::PARAMETER_GREATER_THAN:
                $value = $this->normalizeValue($value, $operator);
                if (null === $value) {
                    return;
                }

                $aggregationBuilder->match()->field($matchField)->gt($value);

                break;
            case self::PARAMETER_GREATER_THAN_OR_EQUAL:
                $value = $this->normalizeValue($value, $operator);
                if (null === $value) {
                    return;
                }

                $aggregationBuilder->match()->field($matchField)->gte($value);

                break;
            case self::PARAMETER_LESS_THAN:
                $value = $this->normalizeValue($value, $operator);
                if (null === $value) {
                    return;
                }

                $aggregationBuilder->match()->field($matchField)->lt($value);

                break;
            case self::PARAMETER_LESS_THAN_OR_EQUAL:
                $value = $this->normalizeValue($value, $operator);
                if (null === $value) {
                    return;
                }

                $aggregationBuilder->match()->field($matchField)->lte($value);

                break;
        }
    }

public function selectElemMatch(string $fieldName, $expression) : self
    {
        if ($expression instanceof Expr) {
            $expression = $expression->getQuery();
        }
        $this->query['select'][$fieldName] = ['$elemMatch' => $expression];
        return $this;
    }

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


Question:
Sets the entity search metadata from the metadata mapping.

@param   Metadata\EntityMetadata     $metadata
@param   array                       $mapping
@return  Metadata\EntityMetadata

protected function setSearch(Metadata\EntityMetadata $metadata, array $mapping)
    {
        $clientKey = isset($mapping['key']) ? $mapping['key'] : null;
        if (null === $clientKey) {
            // Search is not enabled for this model.
            return $metadata;
        }

        $factory = $this->getSearchMetadataFactory($clientKey);

        $search = $factory->createInstance($mapping);

        $metadata->setSearch($search);
        return $metadata;
    }

private TSMeta parseTSMetaQS(final HttpQuery query) {
    final String tsuid = query.getQueryStringParam("tsuid");
    final TSMeta meta;
    if (tsuid != null && !tsuid.isEmpty()) {
      meta = new TSMeta(tsuid);
    } else {
      meta = new TSMeta();
    }

    final String display_name = query.getQueryStringParam("display_name");
    if (display_name != null) {
      meta.setDisplayName(display_name);
    }

    final String description = query.getQueryStringParam("description");
    if (description != null) {
      meta.setDescription(description);
    }

    final String notes = query.getQueryStringParam("notes");
    if (notes != null) {
      meta.setNotes(notes);
    }

    final String units = query.getQueryStringParam("units");
    if (units != null) {
      meta.setUnits(units);
    }

    final String data_type = query.getQueryStringParam("data_type");
    if (data_type != null) {
      meta.setDataType(data_type);
    }

    final String retention = query.getQueryStringParam("retention");
    if (retention != null && !retention.isEmpty()) {
      try {
        meta.setRetention(Integer.parseInt(retention));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'retention' value");
      }
    }

    final String max = query.getQueryStringParam("max");
    if (max != null && !max.isEmpty()) {
      try {
        meta.setMax(Float.parseFloat(max));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'max' value");
      }
    }

    final String min = query.getQueryStringParam("min");
    if (min != null && !min.isEmpty()) {
      try {
        meta.setMin(Float.parseFloat(min));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'min' value");
      }
    }

    return meta;
  }

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


Question:
Creates new keyword for given category.

@param int $categoryId
@param Request $request

@return Response

public function postAction($categoryId, Request $request)
    {
        /** @var KeywordInterface $keyword */
        $keyword = $this->getKeywordRepository()->createNew();
        $category = $this->getCategoryRepository()->findCategoryById($categoryId);
        $keyword->setKeyword($request->get('keyword'));
        $keyword->setLocale($request->get('locale'));

        $keyword = $this->getKeywordManager()->save($keyword, $category);

        $this->getEntityManager()->persist($keyword);
        $this->getEntityManager()->flush();

        return $this->handleView($this->view($keyword));
    }

protected function computeInPathParameters()
	{
		foreach ($this->openApiFileContent['paths'] as $path => $operations) {
			foreach ($operations as $httpMethod => $operation) {
				if (isset($operation['tags'])) {
					$extractedTags = [];
					foreach ($operation['tags'] as $tag) {
						$split = explode(':', $tag);
						if (count($split) == 2) {
							switch ($split[0]) {
								case 'Manager' :
									if (!isset($extractedTags['Managers'])) {
										$extractedTags['Managers'] = [];
									}
									$extractedTags['Managers'][] = $split[1];
									break;
								case 'Resource' :
									if (!isset($extractedTags['Resources'])) {
										$extractedTags['Resources'] = [];
									}
									$extractedTags['Resources'][] = $split[1];
									break;
							}
						}
					}

					foreach ($extractedTags as $tagType => $typeTags) {
						foreach ($typeTags as $typeTag) {
							switch ($tagType) {
								case 'Managers' :
									$this->prepareManager($typeTag);
									$this->managersData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation);
									break;

								case 'Resources' :
									$this->prepareResource($typeTag);
									$this->resourcesData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation, ucfirst($typeTag), $this->resourcesData[ucfirst($typeTag)]['properties']);
									break;
							}
						}
					}
				}
			}
		}
	}

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


Question:
Ready the CookieJar, loading a saved session if available
    @rtype: cookielib.LWPCookieJar

def cookiejar(name='session'):

    log = logging.getLogger('ipsv.common.cookiejar')
    spath = os.path.join(config().get('Paths', 'Data'), '{n}.txt'.format(n=name))
    cj = cookielib.LWPCookieJar(spath)
    log.debug('Attempting to load session file: %s', spath)
    if os.path.exists(spath):
        try:
            cj.load()
            log.info('Successfully loaded a saved session / cookie file')
        except cookielib.LoadError as e:
            log.warn('Session / cookie file exists, but could not be loaded', exc_info=e)

    return cj

def _add_warc_snapshot(self, filename, url):
        ''''''
        _logger.debug('Adding snapshot record.')

        extension = os.path.splitext(filename)[1]
        content_type = {
            '.pdf': 'application/pdf',
            '.html': 'text/html',
            '.png': 'image/png',
            '.gif': 'image/gif'
            }[extension]

        record = WARCRecord()
        record.set_common_fields('resource', content_type)
        record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \
            .format(wpull.url.percent_encode_query_value(url))

        if self._action_warc_record:
            record.fields['WARC-Concurrent-To'] = \
                self._action_warc_record.fields[WARCRecord.WARC_RECORD_ID]

        with open(filename, 'rb') as in_file:
            record.block_file = in_file

            self._warc_recorder.set_length_and_maybe_checksums(record)
            self._warc_recorder.write_record(record)

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


Question:
Fetch feedback messages in a stack

        :param stackid: Id of the stack
        :param offset: the pagination offset
        :param limit: the pagination limit

def get_feedback_in_stack(self, stackid, offset=0, limit=10):

        if self.standard_grant_type is not "authorization_code":
            raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.")

        response = self._req('/messages/feedback/{}'.format(stackid), {
            'offset' : offset,
            'limit' : limit
        })

        messages = []

        for item in response['results']:

            m = Message()
            m.from_dict(item)

            messages.append(m)

        return {
            "results" : messages,
            "has_more" : response['has_more'],
            "next_offset" : response['next_offset']
        }

public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if (!$exception instanceof OutOfBoundsException) {
            return;
        }

        $pageNumber = $exception->getPageNumber();
        $pageCount = $exception->getPageCount();

        if ($pageCount < 1) {
            return; // No pages...so let the exception fall through.
        }

        $queryBag = clone $event->getRequest()->query;

        if ($pageNumber > $pageCount) {
            $queryBag->set($exception->getRedirectKey(), $pageCount);
        } elseif ($pageNumber < 1) {
            $queryBag->set($exception->getRedirectKey(), 1);
        } else {
            return; // Super weird, because current page is within the bounds, fall through.
        }

        if (null !== $qs = http_build_query($queryBag->all(), '', '&')) {
            $qs = '?'.$qs;
        }

        // Create identical uri except for the page key in the query string which
        // was changed by this listener.
        //
        // @see Symfony\Component\HttpFoundation\Request::getUri()
        $request = $event->getRequest();
        $uri = $request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo().$qs;

        $event->setResponse(new RedirectResponse($uri));
    }

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


Question:
Convert the stack trace to a List in order to be rendered in the error template.

@param error error object
@return List containing the stack trace for the object

private List<String> getStackTrace(Object error) {
        if (fullStack && error instanceof Throwable) {
            List<String> stackTrace = new ArrayList<>();
            for (StackTraceElement t : ((Throwable) error).getStackTrace()) {
                stackTrace.add(t.toString());
            }
            return stackTrace;
        } else {
            return Collections.emptyList();
        }
    }

def _format_arg(arg):
    """"""
    # Check that the argument conforms to one of the acceptable types, a string
    # (when the default exception type is used), an exception type (when the
    # default exception message is used) or a list/tuple to specify both
    # exception type and exception message
    if not (_isexception(arg) or isinstance(arg, (str, tuple, list))):
        raise TypeError("Illegal custom contract exception definition")
    # Check that when the argument is a list or tuple, they only have at most
    # 2 items, the exception type and the exception message
    if isinstance(arg, (tuple, list)) and ((not arg) or (len(arg) > 2)):
        raise TypeError("Illegal custom contract exception definition")
    # When only an exception message is given (and the default RuntimeError
    # exception type is used), check that the message is not empty
    if isinstance(arg, str) and (not arg):
        raise ValueError("Empty custom contract exception message")
    # When only an exception message is defined,
    # use the default exception type
    if isinstance(arg, str):
        return {"msg": arg, "type": RuntimeError}
    # When only an exception type is defined,
    # use the default exception message
    if _isexception(arg):
        return {"msg": "Argument `*[argument_name]*` is not valid", "type": arg}
    # If a list/tuple definition is used, check that if is not a string, it is
    # a valid exception type (i.e. that it actually raises an exception)
    if (len(arg) == 1) and (not isinstance(arg[0], str)) and (not _isexception(arg[0])):
        raise TypeError("Illegal custom contract exception definition")
    if (len(arg) == 2) and (
        not (
            (isinstance(arg[0], str) and _isexception(arg[1]))
            or (isinstance(arg[1], str) and _isexception(arg[0]))
        )
    ):
        raise TypeError("Illegal custom contract exception definition")
    # Check that the exception definition has a non-empty exception message
    # when a list/tuple definition is used
    if (len(arg) == 1) and isinstance(arg[0], str) and (not arg[0]):
        raise ValueError("Empty custom contract exception message")
    if (len(arg) == 2) and (
        (isinstance(arg[0], str) and (not arg[0]))
        or (isinstance(arg[1], str) and (not arg[1]))
    ):
        raise ValueError("Empty custom contract exception message")
    # Return conforming dictionary with default exception type and exception
    # message applied (if necessary)
    if len(arg) == 1:
        return {
            "msg": (
                arg[0]
                if isinstance(arg[0], str)
                else "Argument `*[argument_name]*` is not valid"
            ),
            "type": arg[0] if _isexception(arg[0]) else RuntimeError,
        }
    # len(arg) == 2
    return {
        "msg": arg[0] if isinstance(arg[0], str) else arg[1],
        "type": arg[0] if _isexception(arg[0]) else arg[1],
    }

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


Question: // SetAbsolutePath sets the AbsolutePath field's value.

func (s *Folder) SetAbsolutePath(v string) *Folder {
	s.AbsolutePath = &v
	return s
}

def set_metadata(self, layer_id, version_id, fp):

        base_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
        self._metadata.set(base_url, fp)

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


Question: Reading socket and receiving message from server. Check the CRC32.

def recv_message(self, debug=False):

        if debug:
            packet = self.sock.recv(1024)  # reads how many bytes to read
            hexdump(packet)

        packet_length_data = self.sock.recv(4)  # reads how many bytes to read

        if len(packet_length_data) < 4:
            raise Exception("Nothing in the socket!")
        packet_length = struct.unpack("<I", packet_length_data)[0]
        packet = self.sock.recv(packet_length - 4)  # read the rest of bytes from socket

        # check the CRC32
        if not crc32(packet_length_data + packet[0:-4]) == struct.unpack('<I', packet[-4:])[0]:
            raise Exception("CRC32 was not correct!")
        x = struct.unpack("<I", packet[:4])
        auth_key_id = packet[4:12]
        if auth_key_id == b'\x00\x00\x00\x00\x00\x00\x00\x00':
            # No encryption - Plain text
            (message_id, message_length) = struct.unpack("<QI", packet[12:24])
            data = packet[24:24+message_length]
        elif auth_key_id == self.auth_key_id:
            pass
            message_key = packet[12:28]
            encrypted_data = packet[28:-4]
            aes_key, aes_iv = self.aes_calculate(message_key, direction="from server")
            decrypted_data = crypt.ige_decrypt(encrypted_data, aes_key, aes_iv)
            assert decrypted_data[0:8] == self.server_salt
            assert decrypted_data[8:16] == self.session_id
            message_id = decrypted_data[16:24]
            seq_no = struct.unpack("<I", decrypted_data[24:28])[0]
            message_data_length = struct.unpack("<I", decrypted_data[28:32])[0]
            data = decrypted_data[32:32+message_data_length]
        else:
            raise Exception("Got unknown auth_key id")
        return data

func (h HealthcheckType) String() string {
	switch h {
	case HCTypeDNS:
		return "DNS"
	case HCTypeHTTP:
		return "HTTP"
	// TODO(angusc): Drop HTTPS as a separate type.
	case HCTypeHTTPS:
		return "HTTP" // NB: Not HTTPS
	case HCTypeICMP:
		return "ICMP"
	case HCTypeRADIUS:
		return "RADIUS"
	case HCTypeTCP:
		return "TCP"
	// TODO(angusc): Drop TCPTLS as a separate type.
	case HCTypeTCPTLS:
		return "TCP" // NB: Not TCPTLS
	case HCTypeUDP:
		return "UDP"
	}
	return "(unknown)"
}

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


Question:
Load disambiguation rules from an XML file. Use {@link JLanguageTool#addRule} to add
these rules to the checking process.
@return a List of {@link DisambiguationPatternRule} objects

protected List<DisambiguationPatternRule> loadPatternRules(String filename) throws ParserConfigurationException, SAXException, IOException {
    DisambiguationRuleLoader ruleLoader = new DisambiguationRuleLoader();
    return ruleLoader.getRules(JLanguageTool.getDataBroker().getFromResourceDirAsStream(filename));
  }

@Override
    protected AstNode parseCreateStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        if (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX)) {
            return parseCreateIndex(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_FUNCTION)) {
            return parseCreateFunction(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_PROCEDURE)) {
            return parseCreateProcedure(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_ROLE)) {
            return parseCreateRole(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_SYNONYM)) {
            return parseCreateSynonym(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_TRIGGER)) {
            return parseCreateTrigger(tokens, parentNode);
        }

        return super.parseCreateStatement(tokens, parentNode);

    }

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


Question:
Returns {@link Observable} with one item 1 but only after query
dependencies have been fully emitted (and ignored).

@param query

@return {@link Observable} with one element 1

static Observable<Integer> singleIntegerAfterDependencies(Query query) {
        return concatButIgnoreFirstSequence(query.depends(), Observable.just(1));
    }

function () {
        var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;

        self.$el = $(self.getEl());
        self.state.set('rendered', true);

        // Bind on<event> settings
        for (name in settings) {
          if (name.indexOf("on") === 0) {
            self.on(name.substr(2), settings[name]);
          }
        }

        if (self._eventsRoot) {
          for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) {
            parentEventsRoot = parent._eventsRoot;
          }

          if (parentEventsRoot) {
            for (name in parentEventsRoot._nativeEvents) {
              self._nativeEvents[name] = true;
            }
          }
        }

        bindPendingEvents(self);

        if (settings.style) {
          elm = self.getEl();
          if (elm) {
            elm.setAttribute('style', settings.style);
            elm.style.cssText = settings.style;
          }
        }

        if (self.settings.border) {
          box = self.borderBox;
          self.$el.css({
            'border-top-width': box.top,
            'border-right-width': box.right,
            'border-bottom-width': box.bottom,
            'border-left-width': box.left
          });
        }

        // Add instance to lookup
        var root = self.getRoot();
        if (!root.controlIdLookup) {
          root.controlIdLookup = {};
        }

        root.controlIdLookup[self._id] = self;

        for (var key in self._aria) {
          self.aria(key, self._aria[key]);
        }

        if (self.state.get('visible') === false) {
          self.getEl().style.display = 'none';
        }

        self.bindStates();

        self.state.on('change:visible', function (e) {
          var state = e.value, parentCtrl;

          if (self.state.get('rendered')) {
            self.getEl().style.display = state === false ? 'none' : '';

            // Need to force a reflow here on IE 8
            self.getEl().getBoundingClientRect();
          }

          // Parent container needs to reflow
          parentCtrl = self.parent();
          if (parentCtrl) {
            parentCtrl._lastRect = null;
          }

          self.fire(state ? 'show' : 'hide');

          ReflowQueue.add(self);
        });

        self.fire('postrender', {}, false);
      }

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


Question:
Stops the stopwatch. Future reads will return the fixed duration that had
elapsed up to this point.

@return this {@code Stopwatch} instance
@throws IllegalStateException if the stopwatch is already stopped.

public Stopwatch stop() {
    long tick = System.nanoTime();
    isRunning = false;
    elapsedNanos += tick - startTick;
    return this;
  }

def _state_machine(self):

        role_str = {ROOT_PORT: 'ROOT_PORT          ',
                    DESIGNATED_PORT: 'DESIGNATED_PORT    ',
                    NON_DESIGNATED_PORT: 'NON_DESIGNATED_PORT'}
        state_str = {PORT_STATE_DISABLE: 'DISABLE',
                     PORT_STATE_BLOCK: 'BLOCK',
                     PORT_STATE_LISTEN: 'LISTEN',
                     PORT_STATE_LEARN: 'LEARN',
                     PORT_STATE_FORWARD: 'FORWARD'}

        if self.state is PORT_STATE_DISABLE:
            self.ofctl.set_port_status(self.ofport, self.state)

        while True:
            self.logger.info('[port=%d] %s / %s', self.ofport.port_no,
                             role_str[self.role], state_str[self.state],
                             extra=self.dpid_str)

            self.state_event = hub.Event()
            timer = self._get_timer()
            if timer:
                timeout = hub.Timeout(timer)
                try:
                    self.state_event.wait()
                except hub.Timeout as t:
                    if t is not timeout:
                        err_msg = 'Internal error. Not my timeout.'
                        raise RyuException(msg=err_msg)
                    new_state = self._get_next_state()
                    self._change_status(new_state, thread_switch=False)
                finally:
                    timeout.cancel()
            else:
                self.state_event.wait()

            self.state_event = None

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


Question: Restores previously created event client.

def _restore_event_client(self):
        """"""
        if not self._event_client:
            self._event_client = self._start_event_client()
            return
        self._event_client.host_port = self.host_port
        self._event_client.device_port = self.device_port
        self._event_client.connect()

function handleChannelConvertedEvent(msg) {
    return (dispatch, getState) => {
        const channelId = msg.data.channel_id;
        if (channelId) {
            const channel = getChannel(getState(), channelId);
            if (channel) {
                dispatch({
                    type: ChannelTypes.RECEIVED_CHANNEL,
                    data: {...channel, type: General.PRIVATE_CHANNEL},
                });
            }
        }
    };
}

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


Question:
Calling Fantasy Credit API

        Arg:
            match_key: key of the match
        Return:
            json data

def get_fantasy_credits(self, match_key):

        fantasy_credit_url = self.api_path_v3 + "fantasy-match-credits/" + match_key + "/"
        response = self.get_response(fantasy_credit_url)
        return response

public function favorite($accountId, $mediaId, $isFavorite = true, $mediaType = 'movie')
    {
        return $this->postJson('account/' . $accountId . '/favorite', [
            'media_id'   => $mediaId,
            'media_type' => $mediaType,
            'favorite'   => $isFavorite
        ]);
    }

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


Question:
Format the duration as a long string e.g.
4 hours 3 days 1 second

@return string

public function longFormat($duration)
	{
		if( isset($duration) ) $this->__construct($duration);
		if( $this->hoursSection >= 1 )
		{
			return sprintf(
				' %s ' . str_plural('hour', $this->hoursSection) .
				' %s ' . str_plural('minute', $this->minutesSection) .
				' %s ' . str_plural('second', $this->secondsSection)
				, $this->hoursSection, $this->minutesSection, $this->secondsSection);
		}
		if( $this->minutesSection >= 1 && $this->secondsSection )
		{
			return sprintf(
				' %s ' . str_plural('minute', $this->minutesSection) .
				' %s ' . str_plural('second', $this->secondsSection)
				, $this->minutesSection, $this->secondsSection);
		}
		if( $this->minutesSection >= 1 )
		{
			return sprintf(
				' %s ' . str_plural('minute', $this->minutesSection)
				, $this->minutesSection);
		}

		return sprintf(' %s ' . str_plural('second', $this->secondsSection), $this->secondsSection);
	}

protected function _setDefaultDateTimeValue($oObject, $sLocalDateFormat, $sLocalTimeFormat, $blOnlyDate)
    {
        $aDFormats = $this->_defineDateFormattingRules();
        $aTFormats = $this->_defineTimeFormattingRules();

        $sReturn = $aDFormats[$sLocalDateFormat][2];
        if (!$blOnlyDate) {
            $sReturn .= " " . $aTFormats[$sLocalTimeFormat][2];
        }

        if ($oObject instanceof \OxidEsales\Eshop\Core\Field) {
            $oObject->setValue(trim($sReturn));
        } else {
            $oObject->value = trim($sReturn);
        }
        // increasing(decreasing) field lenght
        $oObject->fldmax_length = strlen($oObject->value);
    }

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


Question: Handle all requests to Stats Servlet {@inheritDoc}

@Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {
    final Map<String, Object> ret = new HashMap<>();

    if (hasParam(req, ACTION_PARAM)) {
      final String action = getParam(req, ACTION_PARAM);
      if (action.equals(STATS_SET_REPORTINGINTERVAL)) {
        handleChangeMetricInterval(req, ret);
      } else if (action.equals(STATS_SET_CLEANINGINTERVAL)) {
        handleChangeCleaningInterval(req, ret);
      } else if (action.equals(STATS_SET_MAXREPORTERPOINTS)) {
        handleChangeEmitterPoints(req, ret);
      } else if (action.equals(STATS_GET_ALLMETRICSNAME)) {
        handleGetAllMMetricsName(req, ret);
      } else if (action.equals(STATS_GET_METRICHISTORY)) {
        handleGetMetricHistory(req, ret);
      } else if (action.equals(STATS_SET_ENABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, true);
      } else if (action.equals(STATS_SET_DISABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, false);
      } else {
        ret.put(RESPONSE_ERROR, "Invalid action");
      }
    }

    JSONUtils.toJSON(ret, resp.getOutputStream(), true);
  }

public function build(): SetRequestInterceptionRequest
	{
		$instance = new SetRequestInterceptionRequest();
		if ($this->patterns === null) {
			throw new BuilderException('Property [patterns] is required.');
		}
		$instance->patterns = $this->patterns;
		return $instance;
	}

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


Question: // SetResponseTemplates sets the ResponseTemplates field's value.

func (s *PutIntegrationResponseInput) SetResponseTemplates(v map[string]*string) *PutIntegrationResponseInput {
	s.ResponseTemplates = v
	return s
}

def read_template_source(filename):
    """"""
    # Import this late to be sure we don't trigger settings machinery too
    # early.
    from django.conf import settings

    if not settings.configured:
        settings.configure()

    with open(filename, "rb") as f:
        text = f.read().decode(settings.FILE_CHARSET)

    return text

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