Question:
param.

@param name a {@link java.lang.String} object.
@param value a {@link java.lang.Object} object.
@return a {@link org.beangle.commons.dao.query.builder.OqlBuilder} object.

public OqlBuilder<T> param(String name, Object value) {
    params.put(name, value);
    return this;
  }

@Override
    @Path("/{dataType}")
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        String dataType = getSegment(path, 1);
        if (dataType == null)
            throw new ServiceException("Missing path segment: {dataType}");
        try {
            BaselineData baselineData = DataAccess.getBaselineData();
            if (dataType.equals("VariableTypes")) {
                List<VariableType> variableTypes = baselineData.getVariableTypes();
                JSONArray jsonArray = new JSONArray();
                for (VariableType variableType : variableTypes)
                    jsonArray.put(variableType.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else if (dataType.equals("TaskCategories")) {
                List<TaskCategory> taskCats = new ArrayList<TaskCategory>();
                taskCats.addAll(baselineData.getTaskCategories().values());
                Collections.sort(taskCats);
                JSONArray jsonArray = new JSONArray();
                for (TaskCategory taskCat : taskCats)
                    jsonArray.put(taskCat.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else {
                throw new ServiceException("Unsupported dataType: " + dataType);
            }
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }

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


Question:
Create the class based event callable.

@param  string                          $listener
@param  \Illuminate\Container\Container $container

@return callable

protected function createClassCallable($listener, $container)
    {
        list($class, $method) = $this->parseClassCallable($listener);

        return [$container->make($class), $method];
    }

protected static function isValidSetter(\ReflectionClass &$reflection, $name)
	{
		if (!$reflection->hasMethod($name))
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: no setter %s.', $reflection->getName(), $name)
			);
		}
		$setter = $reflection->getMethod($name);
		if (!$setter->isPublic())
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s is not public.', $reflection->getName(), $name)
			);
		}
		if ($setter->getNumberOfParameters() < 1)
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s should accept at least one parameter.', $reflection->getName(), $name)
			);
		}
		if ($setter->getNumberOfRequiredParameters() > 1)
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s requires too many parameters.', $reflection->getName(), $name)
			);
		}
		return true;
	}

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


Question: Draw/animate and show and/or save a autofig plot

def _show_or_save(self, save, show, animate,
                      draw_sidebars=True,
                      draw_title=True,
                      tight_layout=False,
                      subplot_grid=None,
                      **kwargs):

        if animate and not show and not save:
            logger.warning("setting show to True since animate=True and save not provided")
            show = True

        if animate:
            # prefer times over time
            times = kwargs.get('times', kwargs.get('time', None))
            save_kwargs = kwargs.get('save_kwargs', {})

            if times is None:
                # then let's try to get all SYNTHETIC times
                # it would be nice to only do ENABLED, but then we have to worry about compute
                # it would also be nice to worry about models... but then you should filter first
                logger.info("no times were providing, so defaulting to animate over all dataset times")
                times = []
                for dataset in self.datasets:
                    ps = self.filter(dataset=dataset, context='model')
                    if len(ps.times):
                        # for the case of meshes/spectra
                        times += [float(t) for t in ps.times]
                    else:
                        for param in ps.filter(qualifier='times').to_list():
                            times += list(param.get_value())

                times = sorted(list(set(times)))

            logger.info("calling autofig.animate(i={}, draw_sidebars={}, draw_title={}, tight_layout={}, save={}, show={}, save_kwargs={})".format(times, draw_sidebars, draw_title, tight_layout, save, show, save_kwargs))

            mplanim = self.gcf().animate(i=times,
                                         draw_sidebars=draw_sidebars,
                                         draw_title=draw_title,
                                         tight_layout=tight_layout,
                                         subplot_grid=subplot_grid,
                                         save=save,
                                         show=show,
                                         save_kwargs=save_kwargs)

            afig = self.gcf()

            # clear the autofig figure
            self.clf()

            return afig, mplanim

        else:
            time = kwargs.get('time', None)

            if isinstance(time, str):
                time = self.get_value(time, context=['component', 'system'])

            logger.info("calling autofig.draw(i={}, draw_sidebars={}, draw_title={}, tight_layout={}, save={}, show={})".format(time, draw_sidebars, draw_title, tight_layout, save, show))
            fig = self.gcf().draw(i=time,
                                  draw_sidebars=draw_sidebars,
                                  draw_title=draw_title,
                                  tight_layout=tight_layout,
                                  subplot_grid=subplot_grid,
                                  save=save, show=show)
            # clear the figure so next call will start over and future shows will work
            afig = self.gcf()
            self.clf()

            return afig, fig

def run(self):
    """"""
    self.graphite.start()
    while True:
      log.debug('Graphite pusher is sleeping for %d seconds', self.period)
      time.sleep(self.period)
      log.debug('Pushing stats to Graphite')
      try:
        self.push()
        log.debug('Done pushing stats to Graphite')
      except:
        log.exception('Exception while pushing stats to Graphite')
        raise

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


Question: Retrieve data from CDMRemote for one or more variables.

def fetch_data(self, **var):
        """"""
        varstr = ','.join(name + self._convert_indices(ind)
                          for name, ind in var.items())
        query = self.query().add_query_parameter(req='data', var=varstr)
        return self._fetch(query)

public static crvserver_binding get(nitro_service service, String name) throws Exception{
		crvserver_binding obj = new crvserver_binding();
		obj.set_name(name);
		crvserver_binding response = (crvserver_binding) obj.get_resource(service);
		return response;
	}

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


Question:
Returns first element in given {@code array}.
<p>
if {@code array} is null or of length zero, then returns {@code null}

public static <T> T getFirst(T array[]){
        return array!=null && array.length>0 ? array[0] : null;
    }

protected function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
    {
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
        $cellXML .= ' s="' . $styleId . '"';

        if (CellHelper::isNonEmptyString($cellValue)) {
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cellValue);
        } else if (CellHelper::isBoolean($cellValue)) {
            $cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
        } else if (CellHelper::isNumeric($cellValue)) {
            $cellXML .= '><v>' . $cellValue . '</v></c>';
        } else if (empty($cellValue)) {
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
                $cellXML .= '/>';
            } else {
                // don't write empty cells that do no need styling
                // NOTE: not appending to $cellXML is the right behavior!!
                $cellXML = '';
            }
        } else {
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
        }

        return $cellXML;
    }

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


Question: Input progess goes from 0 to 100

function ProgressBar(progress) {
  // Make it 50 characters length
  progress = Math.min(100, progress)
  var units = Math.round(progress / 2)
  return chalk.dim('[') + chalk.blue('=').repeat(units) + ' '.repeat(50 - units) + chalk.dim('] ') + chalk.yellow(progress + '%')
}

func New64(total int64) *ProgressBar {
	pb := &ProgressBar{
		Total:           total,
		RefreshRate:     DEFAULT_REFRESH_RATE,
		ShowPercent:     true,
		ShowCounters:    true,
		ShowBar:         true,
		ShowTimeLeft:    true,
		ShowElapsedTime: false,
		ShowFinalTime:   true,
		Units:           U_NO,
		ManualUpdate:    false,
		finish:          make(chan struct{}),
	}
	return pb.Format(FORMAT)
}

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


Question:
Gets a full URL to an icon for a particular block type.

@param \Concrete\Core\Entity\Block\BlockType\BlockType $bt

@return string

public function getBlockTypeIconURL($bt)
    {
        $url = $this->getBlockTypeAssetsURL($bt, FILENAME_BLOCK_ICON);
        if ($url != false) {
            return $url;
        } else {
            return BLOCK_TYPE_GENERIC_ICON;
        }
    }

public function build(ResultSpec $result): string
    {
        $response = [];
        $units = $result->getResults();

        foreach ($units as $unit) {
            /** @var AbstractResult $unit */
            if ($unit instanceof Result) {
                /** @var Result $unit */
                $response[] = [
                    'jsonrpc' => '2.0',
                    'result' => $this->preBuild($unit->getResult()),
                    'id'     => $unit->getId()
                ];
            } elseif ($unit instanceof Error) {
                /** @var Error $unit */
                $baseException = $unit->getBaseException();
                $response[] = [
                    'jsonrpc' => '2.0',
                    'error' => [
                        'code'    => $baseException->getJsonRpcCode(),
                        'message' => $this->getErrorMessage($baseException->getJsonRpcCode()),
                        'data'    => $baseException->getJsonRpcData()
                    ],
                    'id' => $unit->getId()
                ];
            }
        }

        if (empty($response)) {
            return '';
        }

        if ($result->isSingleResult()) {
            return json_encode($response[0]);
        }

        return json_encode($response);
    }

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


Question:
Get xml representation of the object.
        @return: The root node.
        @rtype: L{Element}

def xml(self):

        root = Element('Security', ns=wssens)
        root.set('mustUnderstand', str(self.mustUnderstand).lower())
        for t in self.tokens:
            root.append(t.xml())
        return root

protected void parse(CmsXmlContent content) {

        List<Locale> availableLocales = content.getLocales();
        for (Locale locale : availableLocales) {
            CmsXmlContentRootLocation location = new CmsXmlContentRootLocation(content, locale);
            CmsInheritanceReference ref = parseReference(location, locale);
            if (ref != null) {
                m_references.put(locale, ref);
            }
        }
    }

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public void setXSIZE(Integer newXSIZE) {
		Integer oldXSIZE = xsize;
		xsize = newXSIZE;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.IDD__XSIZE, oldXSIZE, xsize));
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question: Initialize the multiplexor with input and output streams.

protected void init(MuxServer server, int channel)
        throws IOException
    {
        this.server = server;
        this.channel = channel;

        this.url = null;

        chunkLength = 0;
    }

public void setPipelines(java.util.Collection<PipelineSummary> pipelines) {
        if (pipelines == null) {
            this.pipelines = null;
            return;
        }

        this.pipelines = new java.util.ArrayList<PipelineSummary>(pipelines);
    }

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


Question: expression : expression NE expression

def p_expression_noteq(self, p):
        ''
        p[0] = NotEq(p[1], p[3], lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))

public QueryExpression lt(String propertyName,String value)
    {
        return new SimpleQueryExpression(propertyName, ComparisonOperator.LESS_THAN,wrap(value));
    }

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


Question:
Gets an input on a configuration file placed in the application assets.

@param context
the Android context to use
@param fileName
the file name
@return the input stream to read the file or null if the
file does not exist.

protected static InputStream getConfigurationFileFromAssets(Context context,
            String fileName) {
        if (context == null) {
            return null;
        }

        AssetManager assets = context.getAssets();
        if (assets == null) {
            return null;
        }

        try {
            return assets.open(fileName);
        } catch (IOException e) {
            return null;
        }

    }

func ReadConfig(configFilePath string) (ConfigSetterWriter, error) {
	var (
		format formatter
		config *configInternal
	)
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot read agent config %q", configFilePath)
	}
	format, config, err = parseConfigData(configData)
	if err != nil {
		return nil, err
	}
	logger.Debugf("read agent config, format %q", format.version())
	config.configFilePath = configFilePath
	return config, nil
}

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


Question: From a set/list of points, this function will try to group points together

def _find_groups(
        self, points: Set[Point2], minimum_points_per_group: int = 8, max_distance_between_points: int = 2
    ) -> List[Set[Point2]]:

        """ Paint clusters of points in rectangular map using flood fill algorithm. """
        NOT_INTERESTED = -2
        NOT_COLORED_YET = -1
        currentColor: int = NOT_COLORED_YET
        picture: List[List[int]] = [
            [NOT_INTERESTED for j in range(self.pathing_grid.width)] for i in range(self.pathing_grid.height)
        ]

        def paint(pt: Point2) -> None:
            picture[pt.y][pt.x] = currentColor

        nearby: Set[Point2] = set()
        for dx in range(-max_distance_between_points, max_distance_between_points + 1):
            for dy in range(-max_distance_between_points, max_distance_between_points + 1):
                if abs(dx) + abs(dy) <= max_distance_between_points:
                    nearby.add(Point2((dx, dy)))

        for point in points:
            paint(point)

        remaining: Set[Point2] = set(points)
        queue: Deque[Point2] = deque()
        foundGroups: List[Set[Point2]] = []
        while remaining:
            currentGroup: Set[Point2] = set()
            if not queue:
                currentColor += 1
                start = remaining.pop()
                paint(start)
                queue.append(start)
                currentGroup.add(start)
            while queue:
                base: Point2 = queue.popleft()
                for offset in nearby:
                    px, py = base.x + offset.x, base.y + offset.y
                    if px < 0 or py < 0 or px >= self.pathing_grid.width or py >= self.pathing_grid.height:
                        continue
                    if picture[py][px] != NOT_COLORED_YET:
                        continue
                    point: Point2 = Point2((px, py))
                    remaining.remove(point)
                    paint(point)
                    queue.append(point)
                    currentGroup.add(point)
            if len(currentGroup) >= minimum_points_per_group:
                foundGroups.append(currentGroup)

        """ Returns groups of points as list
        [{p1, p2, p3}, {p4, p5, p6, p7, p8}]
        """
        return foundGroups

func (c *Cluster) AddNode(node *seesaw.Node) error {
	key := node.Key()
	if _, ok := c.Nodes[key]; ok {
		return fmt.Errorf("Cluster %q already contains Node %q", c.Site, key)
	}
	c.Nodes[key] = node
	return nil
}

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


Question:
Fill.

@throws IOException Signals that an I/O exception has occurred.

private void fill() throws IOException {
    int n;
    previousBufferSize += nChars;
    do {
      n = in.read(cb, 0, cb.length);
    } while (n == 0);
    if (n > 0) {
      nChars = n;
      nextChar = 0;
    }
  }

private void flush(final Collection<Writer> writers) {
		for (Writer writer : writers) {
			try {
				writer.flush();
			} catch (Exception ex) {
				InternalLogger.log(Level.ERROR, ex, "Failed to flush writer");
			}
		}
	}

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


Question:
load file config

@param string
@return array

static function load($name){

		if($name == ''){
			return self::$data;
		}
		$name = Loader::getName($name,'config');
		$key = $name->app.'.'.$name->class;

		if(!isset(static::$data[$key])){
			// file config is exist?
			if(!file_exists($name->path)){
				user_error('Config '.$name->path.' Not Found');
				exit;
			}
			self::$data[$key] = (require_once $name->path);
		}
		return self::$data[$key];
	}

public function getChildren(ConfigurationInterface $configuration)
    {
        $children = [];

        foreach ($this->configurations as $child) {
            if ($child->getParentId() === $configuration->getResourceId()) {
                $children[$child->getResourceName()] = $child;
            }
        }

        return $children;
    }

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


Question: [START delete_and_update_marks]

static SecurityMarks deleteAndUpdateMarks(String assetName) {
    // String assetName = "organizations/123123342/assets/12312321";
    try (SecurityCenterClient client = SecurityCenterClient.create()) {
      // Start setting up a request to clear and update security marks for an asset.
      // Create security mark and field mask for clearing security marks.
      SecurityMarks securityMarks =
          SecurityMarks.newBuilder()
              .setName(assetName + "/securityMarks")
              .putMarks("key_a", "new_value_for_a")
              .build();
      FieldMask updateMask =
          FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build();

      UpdateSecurityMarksRequest request =
          UpdateSecurityMarksRequest.newBuilder()
              .setSecurityMarks(securityMarks)
              .setUpdateMask(updateMask)
              .build();

      // Call the API.
      SecurityMarks response = client.updateSecurityMarks(request);

      System.out.println("Security Marks updated and cleared:");
      System.out.println(response);
      return response;
    } catch (IOException e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }

private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) {

        String controllerId = null;
        LOG.debug("handleAddUpdateActionStatus for action {}", action.getId());

        // information status entry - check for a potential DOS attack
        assertActionStatusQuota(action);
        assertActionStatusMessageQuota(actionStatus);

        switch (actionStatus.getStatus()) {
        case ERROR:
            final JpaTarget target = (JpaTarget) action.getTarget();
            target.setUpdateStatus(TargetUpdateStatus.ERROR);
            handleErrorOnAction(action, target);
            break;
        case FINISHED:
            controllerId = handleFinishedAndStoreInTargetStatus(action);
            break;
        case DOWNLOADED:
            controllerId = handleDownloadedActionStatus(action);
            break;
        default:
            break;
        }

        actionStatus.setAction(action);
        actionStatusRepository.save(actionStatus);
        final Action savedAction = actionRepository.save(action);

        if (controllerId != null) {
            requestControllerAttributes(controllerId);
        }

        return savedAction;
    }

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


Question: // UnmarshalYAML implements the Unmarshaller interface.

func (s *Stringorslice) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var stringType string
	if err := unmarshal(&stringType); err == nil {
		*s = []string{stringType}
		return nil
	}

	var sliceType []interface{}
	if err := unmarshal(&sliceType); err == nil {
		parts, err := toStrings(sliceType)
		if err != nil {
			return err
		}
		*s = parts
		return nil
	}

	return errors.New("Failed to unmarshal Stringorslice")
}

def get_ymal_data(data):

    try:
        format_data = yaml.load(data)
    except yaml.YAMLError, e:
        msg = "Yaml format error: {}".format(
            unicode(str(e), "utf-8")
        )
        logging.error(msg)
        sys.exit(1)

    if not check_config(format_data):
        sys.exit(1)

    return format_data

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


Question:
Removes the given partition from listening to incoming task events, thus forbidding calls to
{@link #subscribeToEvent(ResultPartitionID, EventListener, Class)}.

@param partitionId
the partition ID

public void unregisterPartition(ResultPartitionID partitionId) {
		checkNotNull(partitionId);

		synchronized (registeredHandlers) {
			LOG.debug("unregistering {}", partitionId);
			// NOTE: tolerate un-registration of non-registered task (unregister is always called
			//       in the cleanup phase of a task even if it never came to the registration - see
			//       Task.java)
			registeredHandlers.remove(partitionId);
		}
	}

public void fireTagParseEvent(TagParseEvent tpe)
	{
		for (int i = 0; i < tagParseListeners.size(); i++)
		{
			TagParseListener l = tagParseListeners.get(i);
			l.tagParsed(tpe);
		}
	}

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


Question:
Synchronizes the values for the given element path.<p>

@param cms the cms context
@param elementPath the element path
@param skipPaths the paths to skip
@param sourceLocale the source locale

private void synchronizeElement(
        CmsObject cms,
        String elementPath,
        Collection<String> skipPaths,
        Locale sourceLocale) {

        if (elementPath.contains("/")) {
            String parentPath = CmsXmlUtils.removeLastXpathElement(elementPath);
            List<I_CmsXmlContentValue> parentValues = getValuesByPath(parentPath, sourceLocale);
            String elementName = CmsXmlUtils.getLastXpathElement(elementPath);
            for (I_CmsXmlContentValue parentValue : parentValues) {
                String valuePath = CmsXmlUtils.concatXpath(parentValue.getPath(), elementName);
                boolean skip = false;
                for (String skipPath : skipPaths) {
                    if (valuePath.startsWith(skipPath)) {
                        skip = true;
                        break;
                    }
                }
                if (!skip) {
                    if (hasValue(valuePath, sourceLocale)) {
                        List<I_CmsXmlContentValue> subValues = getValues(valuePath, sourceLocale);
                        removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale);
                        for (I_CmsXmlContentValue value : subValues) {
                            if (value.isSimpleType()) {
                                setValueForOtherLocales(cms, value, CmsXmlUtils.removeLastXpathElement(valuePath));
                            } else {
                                List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value);
                                for (I_CmsXmlContentValue simpleValue : simpleValues) {
                                    setValueForOtherLocales(cms, simpleValue, parentValue.getPath());
                                }
                            }
                        }
                    } else {
                        removeValuesInOtherLocales(valuePath, sourceLocale);
                    }
                }
            }
        } else {
            if (hasValue(elementPath, sourceLocale)) {
                List<I_CmsXmlContentValue> subValues = getValues(elementPath, sourceLocale);
                removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale);
                for (I_CmsXmlContentValue value : subValues) {
                    if (value.isSimpleType()) {
                        setValueForOtherLocales(cms, value, null);
                    } else {
                        List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value);
                        for (I_CmsXmlContentValue simpleValue : simpleValues) {
                            setValueForOtherLocales(cms, simpleValue, null);
                        }
                    }
                }
            } else {
                removeValuesInOtherLocales(elementPath, sourceLocale);
            }
        }
    }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
// GetSharedDomain returns the shared domain associated with the provided
// Domain GUID.

func (actor Actor) GetSharedDomain(domainGUID string) (Domain, Warnings, error) {
	if domain, found := actor.loadDomain(domainGUID); found {
		log.WithFields(log.Fields{
			"domain": domain.Name,
			"GUID":   domain.GUID,
		}).Debug("using domain from cache")
		return domain, nil, nil
	}

	domain, warnings, err := actor.CloudControllerClient.GetSharedDomain(domainGUID)
	if isResourceNotFoundError(err) {
		return Domain{}, Warnings(warnings), actionerror.DomainNotFoundError{GUID: domainGUID}
	}

	actor.saveDomain(domain)
	return Domain(domain), Warnings(warnings), err
}

protected function buildDomainObject(SPIUrl $data)
    {
        return new URL([
            'id' => $data->id,
            'url' => $data->url,
            'isValid' => $data->isValid,
            'lastChecked' => $this->createDateTime($data->lastChecked),
            'created' => $this->createDateTime($data->created),
            'modified' => $this->createDateTime($data->modified),
        ]);
    }

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


Question: // SetVersion sets the Version field's value.

func (s *ContainerInstance) SetVersion(v int64) *ContainerInstance {
	s.Version = &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:
Returns the current token value.

@param  integer     $index Token position, if none given, consider the current iteration position.
@return string|null

protected function _getToken($index, $type)
    {
        if ($index === null) {
            $index = $this->_current;
        }
        return isset($this->_data[$index]) ? $this->_data[$index][$type] : null;
    }

public function InExpression()
    {
        $inExpression = new AST\InExpression($this->ArithmeticExpression());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $inExpression->not = true;
        }

        $this->match(Lexer::T_IN);
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->subselect = $this->Subselect();
        } else {
            $literals   = [];
            $literals[] = $this->InParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
                $literals[] = $this->InParameter();
            }

            $inExpression->literals = $literals;
        }

        $this->match(Lexer::T_CLOSE_PARENTHESIS);

        return $inExpression;
    }

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


Question: // ClearCacheInfo removes any cached info for the the given file.

func (fbo *folderBlockOps) ClearCacheInfo(
	lState *kbfssync.LockState, file data.Path) error {
	fbo.blockLock.Lock(lState)
	defer fbo.blockLock.Unlock(lState)
	return fbo.clearCacheInfoLocked(lState, file)
}

public function deleteMetadata($name = false)
    {
        if ($name === false) {
            $this->metadata = array();
            return true;
        }
        if (!isset($this->metadata[$name])) {
            return false;
        }
        unset($this->metadata[$name]);
        return true;
    }

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


Question: refresh the HTML

function(force)
        {
            if (!this._v && !force) {
                return;
            }
            var opts = this._o,
                minYear = opts.minYear,
                maxYear = opts.maxYear,
                minMonth = opts.minMonth,
                maxMonth = opts.maxMonth;

            if (this._y <= minYear) {
                this._y = minYear;
                if (!isNaN(minMonth) && this._m < minMonth) {
                    this._m = minMonth;
                }
            }
            if (this._y >= maxYear) {
                this._y = maxYear;
                if (!isNaN(maxMonth) && this._m > maxMonth) {
                    this._m = maxMonth;
                }
            }

            this.el.innerHTML = renderTitle(this) + this.render(this._y, this._m);

            if (opts.bound) {
                this.adjustPosition();
                if(opts.field.type !== 'hidden') {
                    sto(function() {
                        opts.trigger.focus();
                    }, 1);
                }
            }

            if (typeof this._o.onDraw === 'function') {
                var self = this;
                sto(function() {
                    self._o.onDraw.call(self);
                }, 0);
            }
        }

function() {
		var me = this;
		helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
			me.getDatasetMeta(datasetIndex).controller.reset();
		}, me);
	}

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


Question:
Add the WComponent to the end of the interceptor chain.

@param ui the WComponent to add.

public void attachUI(final WComponent ui) {
		if (backing == null || backing instanceof WComponent) {
			backing = ui;
		} else if (backing instanceof InterceptorComponent) {
			((InterceptorComponent) backing).attachUI(ui);
		} else {
			throw new IllegalStateException(
					"Unable to attachUI. Unknown type of WebComponent encountered. " + backing.
					getClass().getName());
		}
	}

public function set_model( $model )
    {
        // Check that the required arguments are provided.
        foreach( $this->required_arguments() as $key )
        {
            if ( !isset($model[$key]) )
            {
                throw new \RuntimeException('The required argument "'.$key.'" was not provided for '.get_called_class());
            }
        }

        // Assign the name of the component as the id if no id was specified
        if( !isset($model['id']) && isset($model['name']) )
        {
            $model['id'] = $model['name'];
        }

        // A name must be specified when a component has a visibility condition
        if( isset($model['show']) && !isset($model['name']) )
        {
            throw new \RuntimeException('Components with a visibility condition (a "show" argument) must have a name');
        }

        $this->model = array_merge( $this->default_model(), $model );
    }

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


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

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

func NewSnapFactory(encrypter encryption.Encrypter, decrypter encryption.Decrypter) SnapFactory {
	return snapCryptor{
		encrypter: encrypter,
		decrypter: decrypter,
	}
}

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


Question: // RoundTrip adds the session object to the request.

func (t *CookieAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if t.SessionObject == nil {
		err := t.setSessionObject()
		if err != nil {
			return nil, errors.Wrap(err, "cookieauth: no session object has been set")
		}
	}

	req2 := cloneRequest(req) // per RoundTripper contract
	for _, cookie := range t.SessionObject {
		// Don't add an empty value cookie to the request
		if cookie.Value != "" {
			req2.AddCookie(cookie)
		}
	}

	return t.transport().RoundTrip(req2)
}

def get_xsession(self, item):

        subj_label, sess_label = self._get_item_labels(item)
        with self:
            xproject = self._login.projects[self.project_id]
            try:
                xsubject = xproject.subjects[subj_label]
            except KeyError:
                xsubject = self._login.classes.SubjectData(
                    label=subj_label, parent=xproject)
            try:
                xsession = xsubject.experiments[sess_label]
            except KeyError:
                xsession = self._login.classes.MrSessionData(
                    label=sess_label, parent=xsubject)
                if item.derived:
                    xsession.fields[
                        self.DERIVED_FROM_FIELD] = self._get_item_labels(
                            item, no_from_study=True)[1]
        return xsession

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


Question: Marshall the given parameter object.

public void marshall(ReservedElasticsearchInstanceOffering reservedElasticsearchInstanceOffering, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getReservedElasticsearchInstanceOfferingId(),
                    RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getElasticsearchInstanceType(), ELASTICSEARCHINSTANCETYPE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getDuration(), DURATION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getFixedPrice(), FIXEDPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getUsagePrice(), USAGEPRICE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getCurrencyCode(), CURRENCYCODE_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getPaymentOption(), PAYMENTOPTION_BINDING);
            protocolMarshaller.marshall(reservedElasticsearchInstanceOffering.getRecurringCharges(), RECURRINGCHARGES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Return the URI port

If no port is set, will return the default port according to the scheme

@return integer

public function getPort()
    {
        if (empty($this->port)) {
            if (array_key_exists($this->scheme, static::$defaultPorts)) {
                return static::$defaultPorts[$this->scheme];
            }
        }

        return $this->port;
    }

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question:
Return the results from an external node classifier if one is
        specified

        :param dict load: A payload received from a minion
        :return: The results from an external node classifier

def _master_tops(self, load):
        '''

        '''
        load = self.__verify_load(load, ('id', 'tok'))
        if load is False:
            return {}
        return self.masterapi._master_tops(load, skip_verify=True)

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
Creates a Child Folder

        :param str name: the name of the new child folder
        :param str description: the description of the new child folder
        :return: newly created folder
        :rtype: drive.Folder

def create_child_folder(self, name, description=None):

        if not self.object_id:
            return None

        url = self.build_url(
            self._endpoints.get('list_items').format(id=self.object_id))

        data = {'name': name, 'folder': {}}
        if description:
            data['description'] = description

        response = self.con.post(url, data=data)
        if not response:
            return None

        folder = response.json()

        return self._classifier(folder)(parent=self,
                                        **{self._cloud_data_key: folder})

public static function routes()
    {
        $middleware = [ CreateDefaultFolder::class, MultiUser::class ];
        $as = 'unisharp.lfm.';
        $namespace = '\\UniSharp\\LaravelFilemanager\\Controllers\\';

        Route::group(compact('middleware', 'as', 'namespace'), function () {

            // display main layout
            Route::get('/', [
                'uses' => 'LfmController@show',
                'as' => 'show',
            ]);

            // display integration error messages
            Route::get('/errors', [
                'uses' => 'LfmController@getErrors',
                'as' => 'getErrors',
            ]);

            // upload
            Route::any('/upload', [
                'uses' => 'UploadController@upload',
                'as' => 'upload',
            ]);

            // list images & files
            Route::get('/jsonitems', [
                'uses' => 'ItemsController@getItems',
                'as' => 'getItems',
            ]);

            Route::get('/move', [
                'uses' => 'ItemsController@move',
                'as' => 'move',
            ]);

            Route::get('/domove', [
                'uses' => 'ItemsController@domove',
                'as' => 'domove'
            ]);

            // folders
            Route::get('/newfolder', [
                'uses' => 'FolderController@getAddfolder',
                'as' => 'getAddfolder',
            ]);

            // list folders
            Route::get('/folders', [
                'uses' => 'FolderController@getFolders',
                'as' => 'getFolders',
            ]);

            // crop
            Route::get('/crop', [
                'uses' => 'CropController@getCrop',
                'as' => 'getCrop',
            ]);
            Route::get('/cropimage', [
                'uses' => 'CropController@getCropimage',
                'as' => 'getCropimage',
            ]);
            Route::get('/cropnewimage', [
                'uses' => 'CropController@getNewCropimage',
                'as' => 'getCropimage',
            ]);

            // rename
            Route::get('/rename', [
                'uses' => 'RenameController@getRename',
                'as' => 'getRename',
            ]);

            // scale/resize
            Route::get('/resize', [
                'uses' => 'ResizeController@getResize',
                'as' => 'getResize',
            ]);
            Route::get('/doresize', [
                'uses' => 'ResizeController@performResize',
                'as' => 'performResize',
            ]);

            // download
            Route::get('/download', [
                'uses' => 'DownloadController@getDownload',
                'as' => 'getDownload',
            ]);

            // delete
            Route::get('/delete', [
                'uses' => 'DeleteController@getDelete',
                'as' => 'getDelete',
            ]);

            Route::get('/demo', 'DemoController@index');
        });
    }

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


Question: Format a list of options

def format_lists(lists)
      lists.inject([nil]) do |buf, (_, val)|
        opts = Kat::Search.send(val[:select])
        buf << val[:select].to_s.capitalize
        buf << nil unless opts.values.first.is_a? Array
        width = opts.keys.sort { |a, b| b.size <=> a.size }.first.size
        opts.each do |k, v|
          buf += if v.is_a? Array
                   [nil, "%#{ width }s => #{ v.shift }" % k] +
                     v.map { |e| ' ' * (width + 4) + e }
                 else
                   ["%-#{ width }s => #{ v }" % k]
                 end
        end
        buf << nil
      end
    end

public void setMFAOptions(java.util.Collection<MFAOptionType> mFAOptions) {
        if (mFAOptions == null) {
            this.mFAOptions = null;
            return;
        }

        this.mFAOptions = new java.util.ArrayList<MFAOptionType>(mFAOptions);
    }

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


Question: Verify and decode an encoded string. Return an object or None.

def cookie_decode(data, key, digestmod=None):

    depr(0, 13, "cookie_decode() will be removed soon.",
                "Do not use this API directly.")
    data = tob(data)
    if cookie_is_encoded(data):
        sig, msg = data.split(tob('?'), 1)
        digestmod = digestmod or hashlib.sha256
        hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest()
        if _lscmp(sig[1:], base64.b64encode(hashed)):
            return pickle.loads(base64.b64decode(msg))
    return None

def pattern(self, pattern):

        enc_pattern = _converters[type(pattern)](pattern)
        if (enc_pattern, True) not in self._refs:
            ch = _Sender(self, enc_pattern,
                         is_pattern=True)
            self._refs[(enc_pattern, True)] = ch
        return self._refs[(enc_pattern, True)]

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


Question: Get matched components

function resolveComponents(router) {
  const path = getLocation(router.options.base, router.options.mode)

  return flatMapComponents(router.match(path), async (Component, _, match, key, index) => {
    // If component is not resolved yet, resolve it
    if (typeof Component === 'function' && !Component.options) {
      Component = await Component()
    }
    // Sanitize it and save it
    const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null)
    match.components[key] = _Component
    return _Component
  })
}

public function maybeMatch(string $variable = null, array $labels = []): self
    {
        $query = new self;
        $query->clauses = $this->clauses->add(
            new Clause\OptionalMatchClause(
                Clause\Expression\Path::startWithNode($variable, $labels)
            )
        );

        return $query;
    }

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


Question:
Retrieve an integer attribute or the default value if not exists.
@param attribute the attribute name
@param namespace the attribute namespace URI
@return the value

public int getInt(String attribute, String namespace) {
        return Integer.parseInt(get(attribute, namespace));
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question: load all the monkey patch extension files in the provided folder

def load_extensions
    self.class.validate_path @extensions_path
    Dir[File.join(@extensions_path, '**', '*.rb').to_s].each { |f| load(f) }
  end

private function registerCommands()
    {
        // monashee:backup
        $this->app['command.monashee.backup'] = $this->app->share(function() {
            return $this->app->make('Monashee\Backup\Commands\MonasheeBackup');
        });

        $this->commands('command.monashee.backup');
    }

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


Question:
Compute fourth term of equation (1) on p. 1200:

        ``b5 * S``

def _get_site_amplification(self, sites, coeffs):

        is_rock = self.get_site_type_dummy_variables(sites)
        return coeffs['b5']*is_rock

def add_called_sequence(self, section, name, sequence, qstring):

        event_group = 'BaseCalled_{}'.format(section)
        if not event_group in self.handle.handle['Analyses/{}'.format(self.group_name)]:
            self.handle.add_analysis_subgroup(self.group_name, event_group)
        fastq_text = '@{}\n{}\n+\n{}\n'.format(name, sequence, qstring)
        fastq_arr = np.array(fastq_text, dtype=str)
        self.handle.add_analysis_dataset('{}/{}'.format(self.group_name, event_group), 'Fastq', fastq_arr)

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


Question:
Extract a number of days/weeks/months/years from the age string.

@param string $age
@param string $suffix

@return int

private function extractNumber(string $age, string $suffix): int
    {
        if (preg_match('/(\d+) *' . $suffix . '/', $age, $match)) {
            return (int) $match[1];
        }

        return 0;
    }

public function set_defaults() {
		// General attributes.
		$this->set_tags_to_ignore();
		$this->set_classes_to_ignore();
		$this->set_ids_to_ignore();

		// Smart characters.
		$this->set_smart_quotes();
		$this->set_smart_quotes_primary();
		$this->set_smart_quotes_secondary();
		$this->set_smart_quotes_exceptions();
		$this->set_smart_dashes();
		$this->set_smart_dashes_style();
		$this->set_smart_ellipses();
		$this->set_smart_diacritics();
		$this->set_diacritic_language();
		$this->set_diacritic_custom_replacements();
		$this->set_smart_marks();
		$this->set_smart_ordinal_suffix();
		$this->set_smart_ordinal_suffix_match_roman_numerals();
		$this->set_smart_math();
		$this->set_smart_fractions();
		$this->set_smart_exponents();

		// Smart spacing.
		$this->set_single_character_word_spacing();
		$this->set_fraction_spacing();
		$this->set_unit_spacing();
		$this->set_french_punctuation_spacing();
		$this->set_units();
		$this->set_dash_spacing();
		$this->set_dewidow();
		$this->set_max_dewidow_length();
		$this->set_max_dewidow_pull();
		$this->set_dewidow_word_number();
		$this->set_wrap_hard_hyphens();
		$this->set_url_wrap();
		$this->set_email_wrap();
		$this->set_min_after_url_wrap();
		$this->set_space_collapse();
		$this->set_true_no_break_narrow_space();

		// Character styling.
		$this->set_style_ampersands();
		$this->set_style_caps();
		$this->set_style_initial_quotes();
		$this->set_style_numbers();
		$this->set_style_hanging_punctuation();
		$this->set_initial_quote_tags();

		// Hyphenation.
		$this->set_hyphenation();
		$this->set_hyphenation_language();
		$this->set_min_length_hyphenation();
		$this->set_min_before_hyphenation();
		$this->set_min_after_hyphenation();
		$this->set_hyphenate_headings();
		$this->set_hyphenate_all_caps();
		$this->set_hyphenate_title_case();
		$this->set_hyphenate_compounds();
		$this->set_hyphenation_exceptions();

		// Parser error handling.
		$this->set_ignore_parser_errors();
	}

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


Question: set links for the current HTML page

public static function setLinks(array $links, bool $replace_existing=false) :void {
		// if we want to purge existing links
		!$replace_existing ?: self::$_links = [];
		// href is the key for storing links
		foreach($links as $href_or_index => $attributes_or_href) {
			// if arguments are provided
			if(is_array($attributes_or_href)) {
				// if we have a stylesheet
				if(
					// if a rel is set, and it's not a stylesheet
					!array_key_exists('rel',$attributes_or_href) ||
					// and it's not a stylesheet
					$attributes_or_href['rel'] == 'stylesheet'
				) {
					// also rewrite the path of assets that used relative shortcuts
					$attributes_or_href['href'] 	= self::getPublicAssetPath($href_or_index,'Css');
					// force the type
					$attributes_or_href['type'] 	= 'text/css';
					// force the rel
					$attributes_or_href['rel'] 		= 'stylesheet';
					// if the media key is implicit
					array_key_exists('media', $attributes_or_href) ?: $attributes_or_href['media'] = 'all';
					// push the slightly alternated stylesheet
					self::$_links[$href_or_index] = $attributes_or_href;
				}
				// otherwize we don't know what we're dealing with
				else {
					// just set its href
					$attributes_or_href['href'] = $href_or_index;
					// push that link and its attributes
					self::$_links[$href_or_index] = $attributes_or_href;
				}
			}
			// else only an href is provided, we assume it is a stylesheet
			else {
				// push that link alone
				self::$_links[$attributes_or_href] = [
					// we assume it is a generic all media stylesheet
					'rel'	=>'stylesheet',
					'type'	=>'text/css',
					'media'	=>'all',
					// and we set its href
					'href'	=>self::getPublicAssetPath($attributes_or_href, 'Css')
				];
			}
		}
	}

function (data) {
            var temp = addPath(validUrls, url.parse(data.href), bs.options.get("mode"));
            methods.sendUpdatedIfChanged(validUrls, temp, ui.socket);
        }

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


Question: // GetVSMBUvmPath returns the guest path of a VSMB mount.

func (uvm *UtilityVM) GetVSMBUvmPath(hostPath string) (_ string, err error) {
	op := "uvm::GetVSMBUvmPath"
	log := logrus.WithFields(logrus.Fields{
		logfields.UVMID: uvm.id,
		"host-path":     hostPath,
	})
	log.Debug(op + " - Begin Operation")
	defer func() {
		if err != nil {
			log.Data[logrus.ErrorKey] = err
			log.Error(op + " - End Operation - Error")
		} else {
			log.Debug(op + " - End Operation - Success")
		}
	}()

	if hostPath == "" {
		return "", fmt.Errorf("no hostPath passed to GetVSMBUvmPath")
	}
	uvm.m.Lock()
	defer uvm.m.Unlock()
	share, err := uvm.findVSMBShare(hostPath)
	if err != nil {
		return "", err
	}
	path := share.GuestPath()
	return path, nil
}

func (conn *FakeVTGateConn) AddQuery(
	sql string,
	bindVariables map[string]*querypb.BindVariable,
	session *vtgatepb.Session,
	expectedResult *sqltypes.Result) {
	conn.execMap[sql] = &queryResponse{
		execQuery: &queryExecute{
			SQL:           sql,
			BindVariables: bindVariables,
			Session:       session,
		},
		reply: expectedResult,
	}
}

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


Question:
// Error returns the error if keep aliver
// has been closed

func (k *authKeepAliver) Error() error {
	k.RLock()
	defer k.RUnlock()
	return k.err
}

public function err($text = '', $nl = true)
	{
		fwrite(STDERR, $this->processor->process($text) . ($nl ? "\n" : null));

		return $this;
	}

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


Question:
Init relations and populate pivot map.

@return self|MultipleRelation

protected function initInstances(): MultipleRelation
    {
        if (is_array($this->data) && !empty($this->data)) {
            //Iterates and instantiate records
            $iterator = new RecordIterator($this->data, $this->class, $this->orm);

            foreach ($iterator as $pivotData => $item) {
                if (in_array($item, $this->instances, true)) {
                    //Skip duplicates (if any?)
                    continue;
                }

                $this->pivotData->attach($item, $pivotData);
                $this->instances[] = $item;
            }
        }

        //Memory free
        $this->data = [];

        return $this;
    }

public function normalize(EntityMetadata $metadata, array $record, Store $store)
    {
        // Get the identifier and model type value from the raw record.
        list($identifier, $type) = $this->extractIdAndType($metadata, $record);

        // Reload the metadata in case a polymorphic type was found.
        $metadata = $store->getMetadataForType($type);

        // Convert relationships to the proper format.
        $record = $this->convertRelationships($metadata, $record);

        return [
            'identifier'    => (String) $identifier,
            'type'          => $type,
            'properties'    => $record,
        ];
    }

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


Question:
Remove latex comments from document (modifies document in place).

        Parameters
        ----------
        recursive : bool
            Remove comments from all input LaTeX documents (default ``True``).

def remove_comments(self, recursive=True):

        self.text = texutils.remove_comments(self.text)
        if recursive:
            for path, document in self._children.iteritems():
                document.remove_comments(recursive=True)

public static function getAnnotationParams($controller, $action)
    {
        $result = [];

        $reflection = new \ReflectionClass($controller);
        $res = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
        foreach ($res as $method) {
            if ($method->name == $action) {
                $annotation = $method->getDocComment();
                if (strpos($annotation, '@doc') !== false) {
                    //$result[$version][$model]['all'] = $annotation;
                    //描述
                    preg_match('/@desc([^\n]+)/', $annotation, $desc);
                    $result['desc'] = isset($desc[1]) ? trim($desc[1]) : '';
                    //参数
                    preg_match_all('/@param([^\n]+)/', $annotation, $params);
                    foreach ($params[1] as $key => $val) {
                        $tmp = explode(' ', preg_replace('/\s(\s+)/', ' ', trim($val)));
                        isset($tmp[3]) || $tmp[3] = 'N';
                        substr($tmp[1], 0, 1) == '$' && $tmp[1] = substr($tmp[1], 1);
                        $result['params'][] = $tmp;
                    }

                    //请求示例
                    preg_match('/@req(.+?)(\*\s*?@|\*\/)/s', $annotation, $reqEg);
                    $result['req'] = isset($reqEg[1]) ? self::formatCode($reqEg[1]) : '';

                    //请求成功示例
                    preg_match('/@success(.+?)(\*\s*?@|\*\/)/s', $annotation, $success);
                    $result['success'] = isset($success[1]) ? self::formatCode($success[1]) : '';

                    //请求失败示例
                    preg_match('/@error(.+?)(\*\s*?@|\*\/)/s', $annotation, $error);
                    $result['error'] = isset($error[1]) ? self::formatCode($error[1]) : '';
                }
            }
        }
        return $result;
    }

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


Question:
parse minify : <gc:minify>
@access protected
@return void
@since 3.0
@package Gcs\Framework\Core\Template

protected function _parseMinify() {
        $this->_content = preg_replace_callback('`' . $this->_openTag . $this->_name . preg_quote($this->markup['minify'][0]) . $this->_space . $this->_closeTag . '(.*)' . $this->_openTag . '/' . $this->_name . preg_quote($this->markup['minify'][0]) . $this->_space . $this->_closeTag . '`isU', ['Gcs\Framework\Core\Template\Parser', '_parseMinifyCallback'], $this->_content);
    }

function ( pkg, compiler ) {
			if ( !sys.isEmpty( task.data.depends ) && options.resolveAliases && !sys.isEmpty( pkg.dependAliases ) ) {

				compiler.transform( function ( file ) {
					grunt.verbose.writeln( "Transforming " + file );
					function write( buf ) {
						data += buf;
					}

					var data = '';

					return through( write, function () {
						var __aliases = [];
						sys.each( pkg.dependAliases, function ( al ) {
							if ( data.indexOf( "'" + al + "'" ) !== -1 || data.indexOf( '"' + al + '"' ) !== -1 ) {
								__aliases.push( "'" + al + "' : '" + al + "'" );

								data = data.replace( new RegExp( "'" + al + "'", "g" ), "__aliases['" + al + "']" );
								data = data.replace( new RegExp( '"' + al + '"', "g" ), "__aliases['" + al + "']" );
							}
						} );
						if ( !sys.isEmpty( __aliases ) ) {
							var aliasDefinition = "var __aliases = {" + __aliases.join( ",\n" ) + "};\n";

							data = aliasDefinition + data;

						}
						this.queue( data );
						this.queue( null );
					} );

				} );
			}
		}

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


Question:
Issue a log message with parameters with a level of ERROR.

@param message the message
@param params the message parameters
@deprecated To log a message with parameters, using {@link #errorv(String, Object...)} is recommended.

@Deprecated
    public void error(Object message, Object[] params) {
        doLog(Level.ERROR, FQCN, message, params, null);
    }

def __do_parse(self, pattern_str):

        in_ = antlr4.InputStream(pattern_str)
        lexer = STIXPatternLexer(in_)
        lexer.removeErrorListeners()  # remove the default "console" listener
        token_stream = antlr4.CommonTokenStream(lexer)

        parser = STIXPatternParser(token_stream)
        parser.removeErrorListeners()  # remove the default "console" listener
        error_listener = ParserErrorListener()
        parser.addErrorListener(error_listener)

        # I found no public API for this...
        # The default error handler tries to keep parsing, and I don't
        # think that's appropriate here.  (These error handlers are only for
        # handling the built-in RecognitionException errors.)
        parser._errHandler = antlr4.BailErrorStrategy()

        # To improve error messages, replace "<INVALID>" in the literal
        # names with symbolic names.  This is a hack, but seemed like
        # the simplest workaround.
        for i, lit_name in enumerate(parser.literalNames):
            if lit_name == u"<INVALID>":
                parser.literalNames[i] = parser.symbolicNames[i]

        # parser.setTrace(True)

        try:
            tree = parser.pattern()
            # print(tree.toStringTree(recog=parser))

            return tree
        except antlr4.error.Errors.ParseCancellationException as e:
            # The cancellation exception wraps the real RecognitionException
            # which caused the parser to bail.
            real_exc = e.args[0]

            # I want to bail when the first error is hit.  But I also want
            # a decent error message.  When an error is encountered in
            # Parser.match(), the BailErrorStrategy produces the
            # ParseCancellationException.  It is not a subclass of
            # RecognitionException, so none of the 'except' clauses which would
            # normally report an error are invoked.
            #
            # Error message creation is buried in the ErrorStrategy, and I can
            # (ab)use the API to get a message: register an error listener with
            # the parser, force an error report, then get the message out of the
            # listener.  Error listener registration is above; now we force its
            # invocation.  Wish this could be cleaner...
            parser._errHandler.reportError(parser, real_exc)

            # should probably chain exceptions if we can...
            # Should I report the cancellation or recognition exception as the
            # cause...?
            six.raise_from(ParseException(error_listener.error_message),
                           real_exc)

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


Question: Exit the process with an error message, optionally with a stack trace.

public static void crashLocalVoltDB(String errMsg, boolean stackTrace, Throwable thrown, boolean logFatal) {

        if (exitAfterMessage) {
            System.err.println(errMsg);
            VoltDB.exit(-1);
        }
        try {
            OnDemandBinaryLogger.flush();
        } catch (Throwable e) {}

        /*
         * InvocationTargetException suppresses information about the cause, so unwrap until
         * we get to the root cause
         */
        while (thrown instanceof InvocationTargetException) {
            thrown = ((InvocationTargetException)thrown).getCause();
        }

        // for test code
        wasCrashCalled = true;
        crashMessage = errMsg;
        if (ignoreCrash) {
            throw new AssertionError("Faux crash of VoltDB successful.");
        }
        if (CoreUtils.isJunitTest()) {
            VoltLogger log = new VoltLogger("HOST");
            log.warn("Declining to drop a crash file during a junit test.");
        }
        // end test code
        // send a snmp trap crash notification
        sendCrashSNMPTrap(errMsg);
        // try/finally block does its best to ensure death, no matter what context this
        // is called in
        try {
            // slightly less important than death, this try/finally block protects code that
            // prints a message to stdout
            try {
                // turn off client interface as fast as possible
                // we don't expect this to ever fail, but if it does, skip to dying immediately
                if (!turnOffClientInterface()) {
                    return; // this will jump to the finally block and die faster
                }

                // Flush trace files
                try {
                    VoltTrace.closeAllAndShutdown(new File(instance().getVoltDBRootPath(), "trace_logs").getAbsolutePath(),
                                                  TimeUnit.SECONDS.toMillis(10));
                } catch (IOException e) {}

                // Even if the logger is null, don't stop.  We want to log the stack trace and
                // any other pertinent information to a .dmp file for crash diagnosis
                List<String> currentStacktrace = new ArrayList<>();
                currentStacktrace.add("Stack trace from crashLocalVoltDB() method:");

                // Create a special dump file to hold the stack trace
                try
                {
                    TimestampType ts = new TimestampType(new java.util.Date());
                    CatalogContext catalogContext = VoltDB.instance().getCatalogContext();
                    String root = catalogContext != null ? VoltDB.instance().getVoltDBRootPath() + File.separator : "";
                    PrintWriter writer = new PrintWriter(root + "voltdb_crash" + ts.toString().replace(' ', '-') + ".txt");
                    writer.println("Time: " + ts);
                    writer.println("Message: " + errMsg);

                    writer.println();
                    writer.println("Platform Properties:");
                    PlatformProperties pp = PlatformProperties.getPlatformProperties();
                    String[] lines = pp.toLogLines(instance().getVersionString()).split("\n");
                    for (String line : lines) {
                        writer.println(line.trim());
                    }

                    if (thrown != null) {
                        writer.println();
                        writer.println("****** Exception Thread ****** ");
                        thrown.printStackTrace(writer);
                    }

                    printStackTraces(writer, currentStacktrace);
                    writer.close();
                }
                catch (Throwable err)
                {
                    // shouldn't fail, but..
                    err.printStackTrace();
                }

                VoltLogger log = null;
                try
                {
                    log = new VoltLogger("HOST");
                }
                catch (RuntimeException rt_ex)
                { /* ignore */ }

                if (log != null)
                {
                    if (logFatal) {
                        log.fatal(errMsg);
                    }
                    if (thrown != null) {
                        if (stackTrace) {
                            log.fatal("Fatal exception", thrown);
                        } else {
                            log.fatal(thrown.toString());
                        }
                    } else {
                        if (stackTrace) {
                            for (String currentStackElem : currentStacktrace) {
                                log.fatal(currentStackElem);
                            }
                        }
                    }
                } else {
                    System.err.println(errMsg);
                    if (thrown != null) {
                        if (stackTrace) {
                            thrown.printStackTrace();
                        } else {
                            System.err.println(thrown.toString());
                        }
                    } else {
                        if (stackTrace) {
                            for (String currentStackElem : currentStacktrace) {
                                System.err.println(currentStackElem);
                            }
                        }
                    }
                }
            }
            finally {
                System.err.println("VoltDB has encountered an unrecoverable error and is exiting.");
                System.err.println("The log may contain additional information.");
            }
        }
        finally {
            ShutdownHooks.useOnlyCrashHooks();
            System.exit(-1);
        }
    }

public void printToStandardStream() throws FileNotFoundException {
        System.out.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams
        System.err.println("I'm gonna print to the command line"); // Violates rule not to write to standard streams
        new SomeCustomException().printStackTrace(); // Violates rule not to write to standard streams

        new SomeCustomException().printStackTrace(new PrintStream("/some/file")); // this is okay, since it's a custom PrintStream
        new SomeCustomException().printStackTrace(new PrintWriter("/some/file")); // this is okay, since it's a custom PrintWriter
    }

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


Question:
Validate the Contact record according to what will be valid by the gateway.

 Usage:
  contact.valid?     # Returns true/false

  Additionally sets contact.errors array to an array of field/error.

def valid?
      @errors = []

      if !contact_id.nil? && contact_id !~ GUID_REGEX
        @errors << ['contact_id', 'must be blank or a valid Xero GUID']
      end

      if status && !CONTACT_STATUS[status]
        @errors << ['status', "must be one of #{CONTACT_STATUS.keys.join('/')}"]
      end

      unless name
        @errors << ['name', "can't be blank"]
      end

      # Make sure all addresses are correct.
      unless addresses.all? { | address | address.valid? }
        @errors << ['addresses', 'at least one address is invalid']
      end

      # Make sure all phone numbers are correct.
      unless phones.all? { | phone | phone.valid? }
        @errors << ['phones', 'at least one phone is invalid']
      end

      @errors.size == 0
    end

def errors
      errors_hash = { fields: [] }
      parse_fields.map do |resource, fields|
        resource_class = resource_class(resource)
        dev_errors = handle_development_errors(resource, resource_class, fields)
        return dev_errors if dev_errors.present?
        generate_errors_hash(resource, resource_class, fields, errors_hash)
      end
      errors_hash[:count] = total_errors_count(errors_hash)
      errors_hash
    end

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


Question:
Verifies the signature of signed content based on a public key.

@param signatureAlgorithm signature algorithm
@param publicKey public key
@param signatureBytes signature bytes
@param contentBytes content bytes
@return whether the signature was verified

public static boolean verify(
      Signature signatureAlgorithm, PublicKey publicKey, byte[] signatureBytes, byte[] contentBytes)
      throws InvalidKeyException, SignatureException {
    signatureAlgorithm.initVerify(publicKey);
    signatureAlgorithm.update(contentBytes);
    // SignatureException may be thrown if we are tring the wrong key.
    try {
      return signatureAlgorithm.verify(signatureBytes);
    } catch (SignatureException e) {
      return false;
    }
  }

func (def *Synthdef) writeParams(w io.Writer) error {
	// write number of params
	if err := binary.Write(w, byteOrder, int32(len(def.ParamNames))); err != nil {
		return err
	}
	// write initial param values
	for _, val := range def.InitialParamValues {
		if err := binary.Write(w, byteOrder, val); err != nil {
			return err
		}
	}
	// write number of param names
	if err := binary.Write(w, byteOrder, int32(len(def.ParamNames))); err != nil {
		return err
	}
	// write param names
	for _, p := range def.ParamNames {
		if err := p.Write(w); err != nil {
			return err
		}
	}
	return nil
}

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


Question:
Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate.

def getmembers(object, predicate=None):
    """"""
    results = []
    for key in dir(object):
        value = getattr(object, key)
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort()
    return results

def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))

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


Question:
A decorator that raises an exception if the specified target is busy.

    Expects the target ID to be either the 'target_id' param in kwargs,
    or the first positional parameter.

    Raises a TargetBusyException if the target does not exist.

def validate_busy(func, *args, **kwargs):

    def inner(self, *args, **kwargs):
        # find the target param
        target_id = None
        if 'target_id' in kwargs and kwargs['target_id'] != None:
            target_id = kwargs['target_id']
        else:
            target_id = 0

        # if there was a target specified, ensure it's not busy
        if self.target_is_busy(target_id):
            raise TargetBusyException()

        # call the function
        return func(self, *args, **kwargs)
    return inner

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question:
Create PUT method with list of parameters
@param path Resource path, relative to repository baseURL
@param params Query parameters
@return PUT method

public HttpPut createPutMethod(final String path, final Map<String, List<String>> params) {
        return new HttpPut(repositoryURL + path + queryString(params));
    }

private static HttpResponse sendRequest(org.dasein.cloud.digitalocean.DigitalOcean provider, RESTMethod method, String token, String strUrl, DigitalOceanAction action) throws CloudException, InternalException {
        HttpRequestBase req = null;
        if (method == RESTMethod.GET) {
            req = new HttpGet(strUrl);
        } else if (method == RESTMethod.POST) {
            req = new HttpPost(strUrl);
        } else if (method == RESTMethod.PUT) {
            req = new HttpPut(strUrl);
        } else if (method == RESTMethod.DELETE) {
            req = new HttpDelete(strUrl);
        } else if (method == RESTMethod.HEAD) {
            req = new HttpHead(strUrl);
        }

        try {
            req.setHeader("Authorization", "Bearer " + token);
            req.setHeader("Accept", "application/json");
            req.setHeader("Content-Type", "application/json;charset=UTF-8");

            StringEntity requestEntity = null;
            if (req instanceof HttpEntityEnclosingRequestBase && action != null) {
                JSONObject jsonToPost = action.getParameters();
                if (jsonToPost != null) {
                    requestEntity = new StringEntity(
                            jsonToPost.toString(),
                            ContentType.APPLICATION_JSON);
                    ((HttpEntityEnclosingRequestBase) req).setEntity(requestEntity);
                }
            }

            HttpClient httpClient = provider.getClient();

            if (wire.isDebugEnabled()) {
                wire.debug("");
                wire.debug("--------------------------------------------------------------------------------------");
            }

            if (wire.isDebugEnabled()) {
                wire.debug(req.getRequestLine().toString());
                for (Header header : req.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");

                if (requestEntity != null) {
                    try {
                        wire.debug(EntityUtils.toString(requestEntity));
                        wire.debug("");
                    } catch (IOException ignore) {
                    }
                }
            }

            HttpResponse response = null;
            int retryCount = 0;

            while (retryCount < 6) {
                response = httpClient.execute(req);

                if (wire.isDebugEnabled()) {
                    wire.debug(response.getStatusLine().toString());
                }

                if (method == RESTMethod.DELETE) {
                    if ((response.getStatusLine().getStatusCode() == 204)) {
                        break;
                    } else {
                        retryCount++;
                        Thread.sleep(5000);
                    }
                } else {
                    break;
                }
            }
            if (method == RESTMethod.DELETE && (response.getStatusLine().getStatusCode() != 204)) {
                //Error occurred
                throw new CloudException("Delete method returned unexpected code, despite retrying.");
            }
            return response;
        } catch (JSONException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (InterruptedException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (ClientProtocolException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (IOException e) {
            throw new CloudException("Problem sending request.", e);
        } finally {
            try {
//                req.releaseConnection();
            } catch (Exception e) {
            }

        }
    }

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


Question:
Inserts a new, blank record somewhere in the file beginning at the
current record. If the new record does not fit into an existing block,
then a new block is appended to the file.

public void insert() {
		// Block read-only transaction
		if (tx.isReadOnly() && !isTempTable())
			throw new UnsupportedOperationException();

		// Insertion may change the properties of this file,
		// so that we need to lock the file.
		if (!isTempTable())
			tx.concurrencyMgr().modifyFile(fileName);

		// Modify the free chain which is start from a pointer in
		// the header of the file.
		if (fhp == null)
			fhp = openHeaderForModification();

		// Log that this logical operation starts
		tx.recoveryMgr().logLogicalStart();

		if (fhp.hasDeletedSlots()) {
			// Insert into a deleted slot
			moveToRecordId(fhp.getLastDeletedSlot());
			RecordId lds = rp.insertIntoDeletedSlot();
			fhp.setLastDeletedSlot(lds);
		} else {
			// Insert into a empty slot
			if (!fhp.hasDataRecords()) { // no record inserted before
				// Create the first data block
				appendBlock();
				moveTo(1);
				rp.insertIntoNextEmptySlot();
			} else {
				// Find the tail page
				RecordId tailSlot = fhp.getTailSolt();
				moveToRecordId(tailSlot);
				while (!rp.insertIntoNextEmptySlot()) {
					if (atLastBlock())
						appendBlock();
					moveTo(currentBlkNum + 1);
				}
			}
			fhp.setTailSolt(currentRecordId());
		}

		// Log that this logical operation ends
		RecordId insertedRid = currentRecordId();
		tx.recoveryMgr().logRecordFileInsertionEnd(ti.tableName(), insertedRid.block().number(), insertedRid.id());

		// Close the header (release the header lock)
		closeHeader();
	}

def process(self, txt, mode):

        result = ''
        if mode == 'ADD':  # already in add mode, so add data
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Adding Text : ', txt)
                result = self.cmd_add(txt)
        elif mode == 'QUERY':
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Query : ', txt)
                result = self.cmd_query(txt)
        else:
            if txt in self.all_commands['exit'][0]:
                self.cmd_exit()

            elif txt in self.all_commands['help'][0]:
                self.cmd_help()

            elif txt in self.all_commands['cmd'][0]:
                result = 'Returning to Command mode'
                mode = 'COMMAND'
                self.prompt = '> '

            elif txt in self.all_commands['add'][0]:
                result = 'Entering Add mode'
                mode = 'ADD'
                self.prompt = 'ADD > '

            elif txt in self.all_commands['query'][0]:
                result = 'Entering Query mode'
                mode = 'QUERY'
                self.prompt = '?? > '
            else:
                result = 'Unknown command - type help for list of commands'

        return result, mode

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


Question: Download `blob` as file with `fileName`. Does not work in IE9.

function(blob, fileName) {

            if (window.navigator.msSaveBlob) { // requires IE 10+
                // pulls up a save dialog
                window.navigator.msSaveBlob(blob, fileName);

            } else { // other browsers
                // downloads directly in Chrome and Safari

                // presents a save/open dialog in Firefox
                // Firefox bug: `from` field in save dialog always shows `from:blob:`
                // https://bugzilla.mozilla.org/show_bug.cgi?id=1053327

                var url = window.URL.createObjectURL(blob);
                var link = document.createElement('a');

                link.href = url;
                link.download = fileName;
                document.body.appendChild(link);

                link.click();

                document.body.removeChild(link);
                window.URL.revokeObjectURL(url); // mark the url for garbage collection
            }
        }

public function getFileAction(Request $request)
    {
        $customerClient = $this->getFactory()->createCustomerClient();
        $customerTransfer = $customerClient->getCustomer();

        if (!$customerTransfer) {
            return $this->redirectResponseInternal(PayoneControllerProvider::ROUTE_LOGIN);
        }

        $getFileTransfer = new PayoneGetFileTransfer();
        $getFileTransfer->setReference($request->query->get('id'));
        $getFileTransfer->setCustomerId($customerTransfer->getIdCustomer());

        $response = $this->getClient()->getFile($getFileTransfer);

        if ($response->getStatus() === 'ERROR') {
            return $this->viewResponse(['errormessage' => $response->getCustomerErrorMessage()]);
        }

        $callback = function () use ($response) {
            echo base64_decode($response->getRawResponse());
        };

        return $this->streamedResponse($callback, 200, ["Content-type" => "application/pdf"]);
    }

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


Question: TODO(binfan): check the logic is correct or not when commitBlock is a retry

@Override
  public void commitBlock(long workerId, long usedBytesOnTier, String tierAlias, long blockId,
      long length) throws NotFoundException, UnavailableException {
    LOG.debug("Commit block from workerId: {}, usedBytesOnTier: {}, blockId: {}, length: {}",
        workerId, usedBytesOnTier, blockId, length);

    MasterWorkerInfo worker = mWorkers.getFirstByField(ID_INDEX, workerId);
    // TODO(peis): Check lost workers as well.
    if (worker == null) {
      throw new NotFoundException(ExceptionMessage.NO_WORKER_FOUND.getMessage(workerId));
    }

    // Lock the worker metadata first.
    try (JournalContext journalContext = createJournalContext()) {
      synchronized (worker) {
        try (LockResource lr = lockBlock(blockId)) {
          Optional<BlockMeta> block = mBlockStore.getBlock(blockId);
          if (!block.isPresent() || block.get().getLength() != length) {
            if (block.isPresent() && block.get().getLength() != Constants.UNKNOWN_SIZE) {
              LOG.warn("Rejecting attempt to change block length from {} to {}",
                  block.get().getLength(), length);
            } else {
              mBlockStore.putBlock(blockId, BlockMeta.newBuilder().setLength(length).build());
              BlockInfoEntry blockInfo =
                  BlockInfoEntry.newBuilder().setBlockId(blockId).setLength(length).build();
              journalContext.append(JournalEntry.newBuilder().setBlockInfo(blockInfo).build());
            }
          }

          // Update the block metadata with the new worker location.
          mBlockStore.addLocation(blockId, BlockLocation.newBuilder()
              .setWorkerId(workerId)
              .setTier(tierAlias)
              .build());
          // This worker has this block, so it is no longer lost.
          mLostBlocks.remove(blockId);

          // Update the worker information for this new block.
          // TODO(binfan): when retry commitBlock on master is expected, make sure metrics are not
          // double counted.
          worker.addBlock(blockId);
          worker.updateUsedBytes(tierAlias, usedBytesOnTier);
          worker.updateLastUpdatedTimeMs();
        }
      }
    }
  }

def has_unsent(self):
        """"""
        for tp in list(self._batches.keys()):
            with self._tp_locks[tp]:
                dq = self._batches[tp]
                if len(dq):
                    return True
        return False

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


Question: // NewDNSProviderConfig return a DNSProvider instance configured for Linode.

func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("linodev4: the configuration of the DNS provider is nil")
	}

	if len(config.Token) == 0 {
		return nil, errors.New("linodev4: Linode Access Token missing")
	}

	if config.TTL < minTTL {
		return nil, fmt.Errorf("linodev4: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
	}

	tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: config.Token})
	oauth2Client := &http.Client{
		Timeout: config.HTTPTimeout,
		Transport: &oauth2.Transport{
			Source: tokenSource,
		},
	}

	client := linodego.NewClient(oauth2Client)
	client.SetUserAgent(fmt.Sprintf("lego-dns linodego/%s", linodego.Version))

	return &DNSProvider{
		config: config,
		client: &client,
	}, nil
}

def configure_nodes(self):
        """"""
        # Since load balancing runs after server provisioning,
        # the servers should already be created regardless of
        # whether this was a preexisting load balancer or not.
        # We also have the existing nodes, because add_to_inventory
        # has been called already
        required_nodes = self._get_required_nodes()

        log.debug(
                "Matching existing lb nodes to required %s (port %s)"
                % (", ".join(required_nodes), self.backend_port)
                )

        self.consul.match_lb_nodes(
            self.lb_attrs[A.loadbalancer.ID],
            self.lb_attrs[A.loadbalancer.NODES_KEY],
            required_nodes,
            self.backend_port)

        self.lb_attrs = self.consul.lb_details(
                self.lb_attrs[A.loadbalancer.ID]
                )

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


Question:
Get current usage memory
@return int

protected static function _getMemory()
    {
        if (function_exists('memory_get_usage')) {
            return memory_get_usage();
        } else {
            $output = array();
            $pid    = getmypid();

            if (substr(PHP_OS, 0, 3) == 'WIN') {
                @exec('tasklist /FI "PID eq ' . $pid . '" /FO LIST', $output);
                if (!isset($output[5])) {
                    $output[5] = null;
                }
                return (int)substr($output[5], strpos($output[5], ':') + 1);
            } else {
                @exec("ps -o rss -p $pid", $output);
                return $output[1] * 1024;
            }
        }
    }

public function imagecolorallocate($imageResource)
	{

		return imagecolorallocate(
			$imageResource,
			$this->_r,
			$this->_g,
			$this->_b
		);

	}

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


Question:
Returns the js code needed to initialize the debug bar

@return string

protected function getJsInitializationCode()
    {
        $js = '';

        if (($this->initialization & self::INITIALIZE_CONSTRUCTOR) === self::INITIALIZE_CONSTRUCTOR) {
            $js .= sprintf("var %s = new %s();\n", $this->variableName, $this->javascriptClass);
        }

        if (($this->initialization & self::INITIALIZE_CONTROLS) === self::INITIALIZE_CONTROLS) {
            $js .= $this->getJsControlsDefinitionCode($this->variableName);
        }

        if ($this->ajaxHandlerClass) {
            $js .= sprintf("%s.ajaxHandler = new %s(%s);\n", $this->variableName, $this->ajaxHandlerClass, $this->variableName);
            if ($this->ajaxHandlerBindToXHR) {
                $js .= sprintf("%s.ajaxHandler.bindToXHR();\n", $this->variableName);
            } elseif ($this->ajaxHandlerBindToJquery) {
                $js .= sprintf("if (jQuery) %s.ajaxHandler.bindToJquery(jQuery);\n", $this->variableName);
            }
        }

        if ($this->openHandlerUrl !== null) {
            $js .= sprintf("%s.setOpenHandler(new %s(%s));\n", $this->variableName,
                $this->openHandlerClass,
                json_encode(array("url" => $this->openHandlerUrl)));
        }

        return $js;
    }

function _printItem (item) {
  switch(item.type) {
    case 'option':
      console.log(item.index + ': ' + item.label);
      break;
    case 'break':
      for (var breakString = ''; breakString.length < item.charCount;) {
        breakString += item.character;
      }

      console.log(breakString);
      break;
    case 'text':
      console.log(item.text);
      break;
    default:
      console.error('Invalid item type: ' + item.type);
      process.exit();
  }
}

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


Question:
Print representation of :class:`~ctfile.ctfile.CTfile`.

        :param str file_format: Format to use: ``ctfile`` or ``json``.
        :param f: Print to file or stdout.
        :type f: File-like
        :return: None.
        :rtype: :py:obj:`None`.

def print_file(self, file_format='ctfile', f=sys.stdout):

        print(self.writestr(file_format=file_format), file=f)

def write_oplog_progress(self):

        if self.oplog_checkpoint is None:
            return None

        with self.oplog_progress as oplog_prog:
            oplog_dict = oplog_prog.get_dict()
        items = [[name, util.bson_ts_to_long(oplog_dict[name])] for name in oplog_dict]
        if not items:
            return

        # write to temp file
        backup_file = self.oplog_checkpoint + ".backup"
        os.rename(self.oplog_checkpoint, backup_file)

        # for each of the threads write to file
        with open(self.oplog_checkpoint, "w") as dest:
            if len(items) == 1:
                # Write 1-dimensional array, as in previous versions.
                json_str = json.dumps(items[0])
            else:
                # Write a 2d array to support sharded clusters.
                json_str = json.dumps(items)
            try:
                dest.write(json_str)
            except IOError:
                # Basically wipe the file, copy from backup
                dest.truncate()
                with open(backup_file, "r") as backup:
                    shutil.copyfile(backup, dest)

        os.remove(backup_file)

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


Question: Compile given regular expression for current sanitize words

def _compile_re(self, expression):

        meta_words = "|".join(self.sanitize_words)
        expression = expression.replace("META_WORDS_HERE", meta_words)
        return re.compile(expression, re.IGNORECASE)

protected function _isSafeEchos($value)
    {
        return preg_match('#^([a-z\d_]+)\\(#', $value, $match) === 1 && in_array($match[1], $this->_safe_functions, true);
    }

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


Question: // SeriesKeys returns a list of series keys from a list of ids.

func (f *SeriesFile) SeriesKeys(ids []SeriesID) [][]byte {
	keys := make([][]byte, len(ids))
	for i := range ids {
		keys[i] = f.SeriesKey(ids[i])
	}
	return keys
}

public function getShowByTvdbId($tvdbId)
  {
    $response = $this->request('/GetShowByTVDBID/' . $tvdbId);
    if ( $response->response->status == 'false' )
      return null;
    $show     = $this->formatShow($response->response);

    return $show;
  }

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


Question:
@VirtualProperty
@SerializedName("variantAttributes")

@return Attribute[]

public function getVariantAttributes()
    {
        $variantAttributes = [];
        foreach ($this->entity->getVariantAttributes() as $attribute) {
            $variantAttributes[] = new Attribute(
                $attribute,
                $this->locale,
                $this->productLocaleManager->getFallbackLocale()
            );
        }

        return $variantAttributes;
    }

public void initDataGroup(ParamType paramType, List<ValidationData> lists) {
        this.paramType = paramType;

        lists.forEach(vd -> {
            this.addRule(vd);
        });

    }

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