Question:
Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the
    files under the paths they ultimately point to) according to the markup
    format provided by :param:`template`.

def _render_filenames(filenames, zip_file, saltenv, template):
    '''

    '''
    if not template:
        return (filenames, zip_file)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        '''
        Render :param:`contents` into a literal pathname by writing it to a
        temp file, rendering that file, and returning the result.
        '''
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to render file path with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    filenames = _render(filenames)
    zip_file = _render(zip_file)
    return (filenames, zip_file)

def fromsra(args):

    p = OptionParser(fromsra.__doc__)
    p.add_option("--paired", default=False, action="store_true",
            help="Specify if library layout is paired-end " + \
                 "[default: %default]")
    p.add_option("--compress", default=None, choices=["gzip", "bzip2"],
            help="Compress output fastq files [default: %default]")
    p.set_outdir()
    p.set_grid()
    opts, args = p.parse_args(args)

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

    srafile, = args
    paired = opts.paired
    compress = opts.compress
    outdir = opts.outdir

    script_path = which("fastq-dump")
    if not script_path:
        logging.error("Cannot find `fastq-dump` in the PATH")
        sys.exit()

    cmd = [script_path]
    if compress:
        cmd.append("--{0}".format(compress))
    if paired:
        cmd.append("--split-files")
    if outdir:
        cmd.append("--outdir {0}".format(outdir))
    cmd.append(srafile)

    outcmd = " ".join(cmd)
    sh(outcmd, grid=opts.grid)

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


Question:
// Ping the remote server to make sure it's alive.  Non-nil return value means
// that there is no active connection.

func (l *Listener) Ping() error {
	l.lock.Lock()
	defer l.lock.Unlock()

	if l.isClosed {
		return errListenerClosed
	}
	if l.cn == nil {
		return errors.New("no connection")
	}

	return l.cn.Ping()
}

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

        if path is None:
            path = self.atlasdb_path

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

        peer_hostport = self.canonical_peer( peer_hostport )

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

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

        return neighbors

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


Question: Get all records identified by package.

def get_records_for_package(self, package_name):

        result = []
        result.extend(self.package_module_map.get(package_name))
        return result

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.GCLINERG__XPOS:
				setXPOS((Integer)newValue);
				return;
			case AfplibPackage.GCLINERG__YPOS:
				setYPOS((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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


Question:
Set LinearGradient type

@param string $type

@throws \InvalidArgumentException

public function setType($type)
    {
        if (!in_array($type, self::$supported)) {
            throw new \InvalidArgumentException(sprintf(
                    'Invalid LinearGradient Gradient Type ""', (string) $type
            ));
        }
        $this->type = $type;
    }

def cli():

    import argparse

    parser = argparse.ArgumentParser(description='Send data to graphite')

    # Core of the application is to accept a metric and a value.
    parser.add_argument('metric', metavar='metric', type=str,
                        help='name.of.metric')
    parser.add_argument('value', metavar='value', type=int,
                        help='value of metric as int')

    args = parser.parse_args()
    metric = args.metric
    value = args.value

    graphitesend_instance = init()
    graphitesend_instance.send(metric, value)

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


Question: // SetPatchOperations sets the PatchOperations field's value.

func (s *UpdateGatewayResponseInput) SetPatchOperations(v []*PatchOperation) *UpdateGatewayResponseInput {
	s.PatchOperations = v
	return s
}

def update(self, **kwargs):

        ret_val = super(ManagerUtilsQuerySet, self).update(**kwargs)
        post_bulk_operation.send(sender=self.model, model=self.model)
        return ret_val

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


Question:
Returns special price querybuilder.

@return \Doctrine\ORM\QueryBuilder

protected function getValidSpecialPriceQuery()
    {
        $qb = $this->createQueryBuilder('specialPrice')
            ->leftJoin('specialPrice.product', 'product')
            ->leftJoin('product.status', 'productStatus')
            ->where(':now BETWEEN specialPrice.startDate AND specialPrice.endDate')
            ->andWhere('productStatus.id = :productStatus')
            ->setParameter('productStatus', Status::ACTIVE)
            ->setParameter('now', new \DateTime());

        return $qb;
    }

protected static function boot()
    {
        parent::boot();

        self::$buildQueryScopeDefaults['columns'] = [
            'id',
            'user_id',
            'option_id',
        ];

        self::$buildQueryScopeDefaults['relations'] = [
            'option' => function (BelongsTo $optionQuery) {
                $optionQuery->select(['id', 'poll_id', 'answer']);
            },
        ];
    }

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


Question:
Add copy bridge methods for all classes/interfaces between the leaf
(genericised class) and the root (genericised baseclass).

@param cf file to which to add the copy bridge
@param leaf leaf class

public static void defineCopyBridges(ClassFile cf, Class leaf) {
        for (Class c : gatherAllBridgeTypes(new HashSet<Class>(), leaf)) {
            if (c != Object.class) {
                defineCopyBridge(cf, leaf, c);
            }
        }
    }

public function path($name, array $parameters = [], $relative = false)
    {
        if ($name instanceof TreeNodeInterface) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ContentTreeContext) {
            return $this->router->generate($name->getNode(), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ElementStructureValue) {
            if ($name->getType() === 'link') {
                $link = $name->getValue();
                if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                    $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                    if ($tree) {
                        $node = $tree->get($link['tid']);

                        return $this->router->generate(
                            $node,
                            $parameters,
                            $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                        );
                    }
                } elseif ($link['type'] === 'external') {
                    return $link['url'];
                } elseif ($link['type'] === 'mailto') {
                    return 'mailto:'.$link['recipient'];
                }
            }
        } elseif (is_array($name) && isset($name['type']) && in_array($name['type'], array('internal', 'intrasiteroot', 'external', 'mailto'))) {
            $link = $name;
            if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                if ($tree) {
                    $node = $tree->get($link['tid']);

                    return $this->router->generate(
                        $node,
                        $parameters,
                        $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                    );
                }
            } elseif ($link['type'] === 'external') {
                return $link['url'];
            } elseif ($link['type'] === 'mailto') {
                return 'mailto:'.$link['recipient'];
            }
        } elseif (strlen($name) && (is_int($name) || (int) $name)) {
            $tree = $this->contentTreeManager->findByTreeId((int) $name);
            if ($tree) {
                $node = $tree->get((int) $name);

                return $this->router->generate($node, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
            }
        } elseif (is_string($name)) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        }

        return '';
    }

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


Question:
Retrieves information about a specified search index within the design
        document, returns dictionary

        GET databasename/_design/{ddoc}/_search_info/{search_index}

def search_info(self, search_index):

        ddoc_search_info = self.r_session.get(
            '/'.join([self.document_url, '_search_info', search_index]))
        ddoc_search_info.raise_for_status()
        return response_to_json_dict(ddoc_search_info)

public function whereSearch($filters)
    {
        $data = $this->request->get();

        foreach ($filters as $k => $v) {
            preg_match('#^(\w+)(.*)$#', is_string($k) ? $k : $v, $match);
            $field = $match[1];

            if (is_int($k)) {
                if (!isset($data[$field])) {
                    continue;
                }
                $value = $data[$field];
                if (is_string($value)) {
                    $value = trim($value);
                    if ($value === '') {
                        continue;
                    }
                }
                $this->where($v, $value);
            } else {
                $this->where($k, $v);
            }
        }

        return $this;
    }

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


Question:
Like newstr.find() but raise ValueError when the substring is not
        found.

def index(self, sub, *args):

        pos = self.find(sub, *args)
        if pos == -1:
            raise ValueError('substring not found')
        return pos

def get_series_by_name(self, series_name):

        try:
            return self.api.search_series(name=series_name), None
        except exceptions.TVDBRequestException as err:
            LOG.exception('search for series %s failed', series_name)
            return None, _as_str(err)

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


Question:
Wraps a try-catch handler around the handler.

@param {function} handler
@param {*} args

function tryWrapper(handler) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
    }

    try {
        handler.apply(undefined, args);
    } catch (err) {
        console.error("handler received an error: " + err.message + ", " + JSON.stringify(err));
    }
}

protected String argumentTypeString(final Type type) {
        if (type instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final List<String> subs = new ArrayList<>();
            for (final Type actualType : parameterizedType.getActualTypeArguments())
                subs.add(argumentTypeString(actualType));
            return argumentTypeString(((ParameterizedType) type).getRawType()) + "[" + String.join(",", subs) + "]";
        } else if (type instanceof GenericArrayType) {
            return argumentTypeString(((GenericArrayType) type).getGenericComponentType()) + "[]";
        } else if (type instanceof WildcardType) {
            throw new RuntimeException("We don't support wildcards in arguments: " + type);
        } else if (type instanceof Class<?>) {
            return ((Class) type).getSimpleName();
        } else {
            throw new DocException("Unknown type: " + type);
        }
    }

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


Question:
Operation getFile

get a file

@param  string $fax_id fax_id (required)
@param  string $format can be 'pdf' or 'tiff' (optional)

@throws \faxplus\ApiException on non-2xx response
@throws \InvalidArgumentException
@return \SplFileObject

public function getFile($fax_id, $format = null)
    {
        list($response) = $this->getFileWithHttpInfo($fax_id, $format);
        return $response;
    }

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

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


Question:
// AttachContainer returns a channel that monitors the run state of a given
// container.

func (a *HostAgent) AttachContainer(state *zkservice.ServiceState, serviceID string, instanceID int) (<-chan time.Time, error) {
	logger := plog.WithFields(log.Fields{
		"serviceid":   serviceID,
		"instanceid":  instanceID,
		"containerid": state.ContainerID,
	})

	// find the container by name
	ctrName := fmt.Sprintf("%s-%d", serviceID, instanceID)
	ctr, err := docker.FindContainer(ctrName)
	if err == docker.ErrNoSuchContainer {
		return nil, nil
	} else if err != nil {
		logger.WithError(err).Debug("Could not look up container")
		return nil, err
	}

	// verify that the container ids match, otherwise delete
	// the container.
	if ctr.ID != state.ContainerID {
		ctr.Kill()
		if err := ctr.Delete(true); err != nil {
			logger.WithError(err).Debug("Could not delete orphaned container")
			return nil, err
		}
		logger.WithField("currentcontainerid", ctr.ID).Warn("Removed orphaned container")
		return nil, nil
	}

	// monitor the container
	ev := a.monitorContainer(logger, ctr)

	// make sure the container is running at the time this event is set
	if !ctr.IsRunning() {
		logger.Debug("Could not capture event, container not running")
		ctr.CancelOnEvent(docker.Die)
		return nil, nil
	}
	go a.exposeAssignedIPs(state, ctr)
	a.setInstanceState(serviceID, instanceID, service.StateRunning)
	return ev, nil
}

<L, E extends Input.Impl> void dispatch(
      Class<L> listenerType, E event, Interaction<L, E> interaction, Interaction<L, E> onCancel) {
    dispatch(event.captureState.layer, listenerType, event, interaction, onCancel);
  }

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


Question: // Workflows returns an object that can list and get Workflows.

func (s *workflowLister) Workflows(namespace string) WorkflowNamespaceLister {
	return workflowNamespaceLister{indexer: s.indexer, namespace: namespace}
}

public void addRewardProducer(IRewardProducer producer) {
        if (this.producers == null) {
            this.producers = new ArrayList<IRewardProducer>();
        }
        this.producers.add(producer);
    }

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


Question:
Edit the wiki page.

        Convenience function that utilizes
        :meth:`.AuthenticatedReddit.edit_wiki_page` populating both the
        ``subreddit`` and ``page`` parameters.

def edit(self, *args, **kwargs):

        return self.subreddit.edit_wiki_page(self.page, *args, **kwargs)

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Creates a by $type parameter specified message

@param string $type
@param string $message

@return Notification

private function createMessageObject(string $type, string $message): Notification
    {
        $msg = new Notification();

        $msg->setType($type);
        $msg->setMessage($message);

        $this->handler->add($msg);

        return $msg;
    }

def _sendMsg(self, type, msg):

        if self.ALERT_STATUS and type in self.ALERT_TYPES:
            self._configMailer()
            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)

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


Question:
Initializes the connected icons.<br>
Fills up the {@link #icons} array.

protected void initializeIcons()
	{
		float f = 1F / 3F;

		icons[LEFT | TOP] = part1.copy().clip(0, 0, f, f);
		icons[TOP] = part1.copy().clip(f, 0, f, f);
		icons[RIGHT | TOP] = part1.copy().clip(2 * f, 0, f, f);

		icons[LEFT] = part1.copy().clip(0, f, f, f);
		icons[NONE] = part1.copy().clip(f, f, f, f);
		icons[RIGHT] = part1.copy().clip(2 * f, f, f, f);

		icons[LEFT | BOTTOM] = part1.copy().clip(0, 2 * f, f, f);
		icons[BOTTOM] = part1.copy().clip(f, 2 * f, f, f);
		icons[RIGHT | BOTTOM] = part1.copy().clip(2 * f, 2 * f, f, f);

		icons[LEFT | TOP | BOTTOM] = part2.copy().clip(0, 0, f, f);
		icons[TOP | BOTTOM] = part2.copy().clip(f, 0, f, f);
		icons[LEFT | RIGHT | TOP] = part2.copy().clip(2 * f, 0, f, f);

		icons[LEFT | RIGHT] = part2.copy().clip(0, f, f, f);
		icons[FULL] = part2.copy().clip(f, f, f, f);
		//icons[LEFT | RIGHT] = icon.copy().clip(2 * f, f, f, f);

		icons[LEFT | RIGHT | BOTTOM] = part2.copy().clip(0, 2 * f, f, f);
		//icons[TOP | BOTTOM] = icon.copy().clip(f, 2 * f, f, f);
		icons[RIGHT | TOP | BOTTOM] = part2.copy().clip(2 * f, 2 * f, f, f);

		initialized = true;
	}

function(data) {
      var segment;
      log('json loaded');

      if (!data.files[0].length) {
        data.files = [data.files];
      }

      for (var i = 0, l = data.files.length; i < l; i++) {
        _files.push([]);
        segment = data.files[i];

        for (var m = 0, n = segment.length; m < n; m++) {
          arrangeData(i, m, segment[m]);
        }
      }
    }

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


Question:
The distance between two ranges.

    :param rng: another range
    :type rng: GenomicRange
    :returns: bases separting, 0 if overlapped or adjacent, -1 if on different chromsomes
    :rtype: int

def distance(self,rng):

    if self.chr != rng.chr: return -1
    c = self.cmp(rng)
    if c == 0: return 0
    if c < 0:
      return rng.start - self.end-1
    return self.start - rng.end-1

private function setValues($values)
    {

        $numbers = Array();
        foreach ($values as $key => $val) {

            $value = new \stdClass();
            $value->label = trim($key);

            if (!is_numeric($val)) {
                $val = null;
            }

            $value->value = $val;
            $this->values[] = $value;
            $numbers[] = $val;
        }
        $min_max = Array();
        foreach ($numbers as $number) {
            if (!is_null($number)) {
                array_push($min_max, $number);
            }
        }
        $this->min = min($min_max);
        $this->max = max($min_max);

        $this->total_values = count($numbers);

        $separation_dist = (($this->graph_width - 40) / $this->total_values);
        $i = 0;

        $this->points = Array();

        foreach ($this->values as $value) {
            $point = new \stdClass();
            $point->x = ($i * $separation_dist) + $this->axis_offset + 40;
            $point->y = $this->plotValue($value->value);
            $point->label = $value->label;
            $point->value = $value->value;
            $this->points[] = $point;
            $i++;
        }

        return $this->points;
    }

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


Question:
TODO: maybe should return null for history request?
@return array

public function getLayoutPlaceHolderNames()
	{
		$layout = $this->getLayout();

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

		return $this->getLayoutProcessor()
				->getPlaces($layout->getFileName());
	}

public function getBuilds($repository, $options = [])
    {
        $paramsUrl = $this->prepareParametersUrl($options, ['number', 'after_number', 'event_type']);
        $response = $this->sendRequest(sprintf('repos/%s/builds%s', $repository, $paramsUrl));

        $result = [];

        if ($response->getStatusCode() == 200) {
            $responseJson = $response->json();
            $commits = [];

            foreach ($responseJson['commits'] as $item) {
                $commit = new Commit();
                Commit::hydrate($item, $commit);

                $commits[$commit->getId()] = $commit;
            }

            foreach ($responseJson['builds'] as $item) {
                $build = new Build();
                $item['commit'] = $commits[$item['commit_id']];
                Build::hydrate($item, $build);

                $result[] = $build;
            }
        }

        return $result;
    }

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


Question: Loads in an application saved in JSON format.

def loadJSON(self, json_string):

        g = get_root(self).globals
        data = json.loads(json_string)['appdata']
        # first set the parameters which change regardless of mode
        # number of exposures
        numexp = data.get('numexp', 0)
        if numexp == -1:
            numexp = 0
        self.number.set(numexp)
        # Overscan (x, y)
        if 'oscan' in data:
            self.oscan.set(data['oscan'])
        if 'oscany' in data:
            self.oscan.set(data['oscany'])
        # LED setting
        self.led.set(data.get('led_flsh', 0))
        # Dummy output enabled
        self.dummy.set(data.get('dummy_out', 0))
        # Fast clocking option?
        self.fastClk.set(data.get('fast_clks', 0))
        # readout speed
        self.readSpeed.set(data.get('readout', 'Slow'))
        # dwell
        dwell = data.get('dwell', 0)
        self.expose.set(str(float(dwell)))

        # multipliers
        mult_values = data.get('multipliers',
                               (1, 1, 1, 1, 1))
        self.nmult.setall(mult_values)

        # look for nodpattern in data
        nodPattern = data.get('nodpattern', {})
        if nodPattern and g.cpars['telins_name'] == 'GTC':
            self.nodPattern = nodPattern
            self.nod.set(True)
            self.clear.set(True)
        else:
            self.nodPattern = {}
            self.nod.set(False)

        # binning
        self.quad_frame.xbin.set(data.get('xbin', 1))
        self.quad_frame.ybin.set(data.get('ybin', 1))
        self.drift_frame.xbin.set(data.get('xbin', 1))
        self.drift_frame.ybin.set(data.get('ybin', 1))

        # now for the behaviour which depends on mode
        if 'app' in data:
            self.app.set(data['app'])
            app = data['app']

            if app == 'Drift':
                # disable clear mode in drift
                self.clear.set(0)
                # only one pair allowed
                self.wframe.npair.set(1)

                # set the window pair values
                labels = ('x1start_left', 'y1start',
                          'x1start_right', 'x1size',
                          'y1size')
                if not all(label in data for label in labels):
                    raise DriverError('Drift mode application missing window params')
                # now actually set them
                self.wframe.xsl[0].set(data['x1start_left'])
                self.wframe.xsr[0].set(data['x1start_right'])
                self.wframe.ys[0].set(data['y1start'])
                self.wframe.nx[0].set(data['x1size'])
                self.wframe.ny[0].set(data['y1size'])
                self.wframe.check()

            elif app == 'FullFrame':
                # enable clear mode if set
                self.clear.set(data.get('clear', 0))

            elif app == 'Windows':
                # enable clear mode if set
                self.clear.set(data.get('clear', 0))
                nquad = 0
                for nw in range(2):
                    labels = ('x{0}start_lowerleft y{0}start x{0}start_upperleft x{0}start_upperright ' +
                              'x{0}start_lowerright x{0}size y{0}size').format(nw+1).split()
                    if all(label in data for label in labels):
                        xsll = data[labels[0]]
                        xslr = data[labels[4]]
                        xsul = data[labels[2]]
                        xsur = data[labels[3]]
                        ys = data[labels[1]]
                        nx = data[labels[5]]
                        ny = data[labels[6]]
                        self.wframe.xsll[nw].set(xsll)
                        self.wframe.xslr[nw].set(xslr)
                        self.wframe.xsul[nw].set(xsul)
                        self.wframe.xsur[nw].set(xsur)
                        self.wframe.ys[nw].set(ys)
                        self.wframe.nx[nw].set(nx)
                        self.wframe.ny[nw].set(ny)
                        nquad += 1
                    else:
                        break
                self.wframe.nquad.set(nquad)
                self.wframe.check()

def ToJson(self):

        type = ''
        if self.Type == StateType.Validator:
            type = 'Validator'
        elif self.Type == StateType.Account:
            type = 'Account'

        return {
            'type': type,
            'key': self.Key.hex(),
            'field': self.Field,
            'value': self.Value.hex()
        }

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


public static void main(String[] args)
    {
        System.out.println("FitLayout interactive console");
        Console con = new Console();
        try
        {
            con.interactiveSession(System.in, System.out, System.err);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

		if ($this->multiPage)
		{
			$strPreview .= '
 Articletitle1

 Articletitle2

 Articletitle3
';
		}
		else
		{
			$strPreview .= '
 Articletitle
';
		}

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

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


Question: // SetZipFile sets the ZipFile field's value.

func (s *UpdateFunctionCodeInput) SetZipFile(v []byte) *UpdateFunctionCodeInput {
	s.ZipFile = v
	return s
}

public function save($file)
	{
		$handle = strcasecmp(substr($file, -3), '.gz') ? fopen($file, 'wb') : gzopen($file, 'wb');
		if (!$handle) {
			throw new Exception("ERROR: Cannot write file '$file'.");
		}
		$this->write($handle);
	}

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


Question:
// StatusCodeWriter returns an http.ResponseWriter that always
// writes the status code stored in rb from when a response
// was buffered to it.

func (rb *ResponseBuffer) StatusCodeWriter(w http.ResponseWriter) http.ResponseWriter {
	return forcedStatusCodeWriter{w, rb}
}

def precise_matcher(text_log_error):
    """"""
    failure_line = text_log_error.metadata.failure_line
    logger.debug("Looking for test match in failure %d", failure_line.id)

    if failure_line.action != "test_result" or failure_line.message is None:
        return

    f = {
        'text_log_error___metadata__failure_line__action': 'test_result',
        'text_log_error___metadata__failure_line__test': failure_line.test,
        'text_log_error___metadata__failure_line__subtest': failure_line.subtest,
        'text_log_error___metadata__failure_line__status': failure_line.status,
        'text_log_error___metadata__failure_line__expected': failure_line.expected,
        'text_log_error___metadata__failure_line__message': failure_line.message
    }
    qwargs = (
        Q(text_log_error___metadata__best_classification=None)
        & (Q(text_log_error___metadata__best_is_verified=True)
           | Q(text_log_error__step__job=text_log_error.step.job))
    )
    qs = (TextLogErrorMatch.objects.filter(**f)
                                   .exclude(qwargs)
                                   .order_by('-score', '-classified_failure'))

    if not qs:
        return

    # chunk through the QuerySet because it could potentially be very large
    # time bound each call to the scoring function to avoid job timeouts
    # returns an iterable of (score, classified_failure_id) tuples
    chunks = chunked_qs_reverse(qs, chunk_size=20000)
    return chain.from_iterable(time_boxed(score_matches, chunks, time_budget=500))

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


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

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.IOB__OBJ_NAME:
				return OBJ_NAME_EDEFAULT == null ? objName != null : !OBJ_NAME_EDEFAULT.equals(objName);
			case AfplibPackage.IOB__OBJ_TYPE:
				return OBJ_TYPE_EDEFAULT == null ? objType != null : !OBJ_TYPE_EDEFAULT.equals(objType);
			case AfplibPackage.IOB__XOA_OSET:
				return XOA_OSET_EDEFAULT == null ? xoaOset != null : !XOA_OSET_EDEFAULT.equals(xoaOset);
			case AfplibPackage.IOB__YOA_OSET:
				return YOA_OSET_EDEFAULT == null ? yoaOset != null : !YOA_OSET_EDEFAULT.equals(yoaOset);
			case AfplibPackage.IOB__XOA_ORENT:
				return XOA_ORENT_EDEFAULT == null ? xoaOrent != null : !XOA_ORENT_EDEFAULT.equals(xoaOrent);
			case AfplibPackage.IOB__YOA_ORENT:
				return YOA_ORENT_EDEFAULT == null ? yoaOrent != null : !YOA_ORENT_EDEFAULT.equals(yoaOrent);
			case AfplibPackage.IOB__XOCA_OSET:
				return XOCA_OSET_EDEFAULT == null ? xocaOset != null : !XOCA_OSET_EDEFAULT.equals(xocaOset);
			case AfplibPackage.IOB__YOCA_OSET:
				return YOCA_OSET_EDEFAULT == null ? yocaOset != null : !YOCA_OSET_EDEFAULT.equals(yocaOset);
			case AfplibPackage.IOB__REF_CSYS:
				return REF_CSYS_EDEFAULT == null ? refCSys != null : !REF_CSYS_EDEFAULT.equals(refCSys);
			case AfplibPackage.IOB__TRIPLETS:
				return triplets != null && !triplets.isEmpty();
		}
		return super.eIsSet(featureID);
	}

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:
Resend Auth Code To Medium By Identifier Type

[code:]
$federation->resendAuthCode('c312cd59f57b964c79f7b71a25c8f6', 'mobile')
[/code]

@param string $validationHash
@param string $identifierType Identifier type. exp. "email" | "mobile"

@return array

function resendAuthCode($validationHash, $identifierType)
    {
        $response = $this->call( new Command\Recover\ResendCode($validationHash, $identifierType) );
        if ( $ex = $response->hasException() )
            throw $ex;

        $r = $response->expected();
        $r = ($r instanceof iDataEntity) ? $r->get('result') : $r;
        return $r;
    }

protected function curl($url  , $data = array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $reponse = curl_exec($ch);
        curl_close($ch);
        $result =  json_decode($reponse , true);

        //因access_token失效导致访问失败，重新access_token再试一次
        /*if($result['errcode'] == 40001 || $result['errcode'] == 40014 ||$result['errcode'] == 42001){

        }*/
        return $result;
    }

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


Question: Get an ASCII string from within the data.

def get_string_from_data(self, offset, data):
        """"""

        # OC Patch
        b = None

        try:
            b = data[offset]
        except IndexError:
            return ''

        s = ''
        while ord(b):
            s += b
            offset += 1
            try:
                b = data[offset]
            except IndexError:
                break

        return s

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:
// newAdvsiroyLock returns a new AdvisoryLock suitable for obtaining a lock to
// perform the stack update.

func newAdvisoryLock(db *sql.DB, stackName string) (*pglock.AdvisoryLock, error) {
	l, err := pglock.NewAdvisoryLock(db, stackLockKey(stackName))
	if err != nil {
		return l, err
	}
	l.LockTimeout = lockTimeout
	l.Context = fmt.Sprintf("stack %s", stackName)
	return l, nil
}

def _notify_listeners(self, sender, message):

        uid = message['uid']
        msg_topic = message['topic']

        self._ack(sender, uid, 'fire')

        all_listeners = set()
        for lst_topic, listeners in self.__listeners.items():
            if fnmatch.fnmatch(msg_topic, lst_topic):
                all_listeners.update(listeners)

        self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none')

        try:
            results = []
            for listener in all_listeners:
                result = listener.handle_message(sender,
                                                 message['topic'],
                                                 message['content'])
                if result:
                    results.append(result)

            self._ack(sender, uid, 'send', json.dumps(results))
        except:
            self._ack(sender, uid, 'send', "Error")

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


Question: // ReadResponse reads a server response into the recieved o.

func (o *DeleteFilesFileidentifierReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 204:
		result := NewDeleteFilesFileidentifierNoContent()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 404:
		result := NewDeleteFilesFileidentifierNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewDeleteFilesFileidentifierInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		result := NewDeleteFilesFileidentifierDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	}
}

func (p DebugPrinter) WebsocketRead(typ int, content []byte, closeCode int) {
	b := &bytes.Buffer{}
	fmt.Fprintf(b, "<- Received: %s", wsMessageTypeName(typ))
	if typ == websocket.CloseMessage {
		fmt.Fprintf(b, " (%d)", closeCode)
	}
	fmt.Fprint(b, "\n")
	if len(content) > 0 {
		if typ == websocket.BinaryMessage {
			fmt.Fprintf(b, "%v\n", content)
		} else {
			fmt.Fprintf(b, "%s\n", content)
		}
	}
	fmt.Fprintf(b, "\n")
	p.logger.Logf(b.String())
}

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


Question: (for multiline edit). Move cursor to the previous line.

def cursor_up(self, count=1):

        original_column = self.preferred_column or self.document.cursor_position_col
        self.cursor_position += self.document.get_cursor_up_position(
            count=count, preferred_column=original_column)

        # Remember the original column for the next up/down movement.
        self.preferred_column = original_column

function() {
      var that = this,
          oldHtml,
          cleanHtml;

      if (wysihtml5.browser.supportsModenPaste()) {
        this.on("paste:composer", function(event) {
          event.preventDefault();
          oldHtml = wysihtml5.dom.getPastedHtml(event);
          if (oldHtml) {
            that._cleanAndPaste(oldHtml);
          }
        });

      } else {
        this.on("beforepaste:composer", function(event) {
          event.preventDefault();
          wysihtml5.dom.getPastedHtmlWithDiv(that.composer, function(pastedHTML) {
            if (pastedHTML) {
              that._cleanAndPaste(pastedHTML);
            }
          });
        });

      }
    }

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


Question:
Returns information about which entities exist and possibly if their
mapping information contains errors or not.

@return array
@throws \Doctrine\ORM\ORMException

public function getEntityStatus()
    {
        $info = [];
        $entityClassNames = $this->entityManager->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
        foreach ($entityClassNames as $entityClassName) {
            try {
                $info[$entityClassName] = $this->entityManager->getClassMetadata($entityClassName);
            } catch (MappingException $e) {
                $info[$entityClassName] = $e->getMessage();
            }
        }

        return $info;
    }

public function newAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $template = new Template();
        $form = $this->container->get('form.factory')->create(TemplateType::class, $template);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em->persist($template);
            $em->flush();

            return new JsonResponse([
                'success' => true,
                'url'     => $this->generateUrl('victoire_template_show', ['id' => $template->getId()]),
            ]);
        }

        return new JsonResponse(
            [
                'success' => true,
                'html'    => $this->container->get('templating')->render(
                    'VictoireTemplateBundle:Template:new.html.twig',
                    ['form' => $form->createView()]
                ),
            ]
        );
    }

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


Question:
Default implementation of UnicodeMatcher::matches() for Unicode
filters.  Matches a single 16-bit code unit at offset.

@Override
    public int matches(Replaceable text,
                       int[] offset,
                       int limit,
                       boolean incremental) {
        int c;
        if (offset[0] < limit &&
            contains(c = text.char32At(offset[0]))) {
            offset[0] += UTF16.getCharCount(c);
            return U_MATCH;
        }
        if (offset[0] > limit && contains(text.char32At(offset[0]))) {
            // Backup offset by 1, unless the preceding character is a
            // surrogate pair -- then backup by 2 (keep offset pointing at
            // the lead surrogate).
            --offset[0];
            if (offset[0] >= 0) {
                offset[0] -= UTF16.getCharCount(text.char32At(offset[0])) - 1;
            }
            return U_MATCH;
        }
        if (incremental && offset[0] == limit) {
            return U_PARTIAL_MATCH;
        }
        return U_MISMATCH;
    }

def set_encoding (parsobj, attrs):

    charset = attrs.get_true('charset', u'')
    if charset:
        # <meta charset="utf-8">
        # eg. in http://cn.dolphin-browser.com/activity/Dolphinjump
        charset = charset.encode('ascii', 'ignore').lower()
    elif attrs.get_true('http-equiv', u'').lower() == u"content-type":
        # <meta http-equiv="content-type" content="text/html;charset="utf-8">
        charset = attrs.get_true('content', u'')
        charset = charset.encode('ascii', 'ignore').lower()
        charset = get_ctype_charset(charset)
    if charset and charset in SUPPORTED_CHARSETS:
        parsobj.encoding = charset

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


Question:
Release the lock.

        This method should only be called in the locked state;
        it changes the state to unlocked and returns immediately.
        If an attempt is made to release an unlocked lock,
        a RuntimeError will be raised.

def release(self):

        if self._local.locked:
            while self._queue:
                future = self._queue.popleft()
                if not future.done():
                    return future.set_result(None)
            self._local.locked = None
        else:
            raise RuntimeError('release unlocked lock')

def send_frame(self, frame):
        '''

        '''
        if self.closed:
            if self.close_info and len(self.close_info['reply_text']) > 0:
                raise ChannelClosed(
                    "channel %d is closed: %s : %s",
                    self.channel_id,
                    self.close_info['reply_code'],
                    self.close_info['reply_text'])
            raise ChannelClosed()

        # If there's any pending event at all, then it means that when the
        # current dispatch loop started, all possible frames were flushed
        # and the remaining item(s) starts with a sync callback. After careful
        # consideration, it seems that it's safe to assume the len>0 means to
        # buffer the frame. The other advantage here is
        if not len(self._pending_events):
            if not self._active and \
                    isinstance(frame, (ContentFrame, HeaderFrame)):
                raise Channel.Inactive(
                    "Channel %d flow control activated", self.channel_id)
            self._connection.send_frame(frame)
        else:
            self._pending_events.append(frame)

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


Question:
Convert object members to a dictionary that can be parsed as JSON.

        Returns:
             dict:

def ToJson(self):

        type = ''
        if self.Type == StateType.Validator:
            type = 'Validator'
        elif self.Type == StateType.Account:
            type = 'Account'

        return {
            'type': type,
            'key': self.Key.hex(),
            'field': self.Field,
            'value': self.Value.hex()
        }

func decodeStructObjectMethods(mrb *Mrb, v *MrbValue) decodeStructGetter {
	return func(key string) (*MrbValue, error) {
		return v.Call(key)
	}
}

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


Question:
Returns domain component id for current component

@return string

public function getDomainComponentId()
    {
        if (!isset($this->_domainComponentIdCache)) { //cache ist vorallem für bei kwfUnserialize nützlich
            $this->_domainComponentIdCache = $this->getDomainComponent()->componentId;
        }
        return $this->_domainComponentIdCache;
    }

def get_nameserver_detail_output_show_nameserver_nameserver_scr(self, **kwargs):

        config = ET.Element("config")
        get_nameserver_detail = ET.Element("get_nameserver_detail")
        config = get_nameserver_detail
        output = ET.SubElement(get_nameserver_detail, "output")
        show_nameserver = ET.SubElement(output, "show-nameserver")
        nameserver_portid_key = ET.SubElement(show_nameserver, "nameserver-portid")
        nameserver_portid_key.text = kwargs.pop('nameserver_portid')
        nameserver_scr = ET.SubElement(show_nameserver, "nameserver-scr")
        nameserver_scr.text = kwargs.pop('nameserver_scr')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question: Performs enrichment.

protected function performEnrichment()
    {
        if ( ! count($this->info->list->filters)) {
            $this->fillDataForEmpty();
        } else {
            $this->enrichCustomData();
        }
    }

func (l *ReaderLexer) Emit(t ItemType) {
	Trace("Emit %s", t)
	l.items <- l.Grab(t)
}

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


Question: // updateNFSClientRPCStats collects statistics for kernel server RPCs.

func (c *nfsCollector) updateNFSClientRPCStats(ch chan<- prometheus.Metric, s *nfs.ClientRPC) {
	ch <- prometheus.MustNewConstMetric(c.nfsRPCOperationsDesc, prometheus.CounterValue,
		float64(s.RPCCount))
	ch <- prometheus.MustNewConstMetric(c.nfsRPCRetransmissionsDesc, prometheus.CounterValue,
		float64(s.Retransmissions))
	ch <- prometheus.MustNewConstMetric(c.nfsRPCAuthenticationRefreshesDesc, prometheus.CounterValue,
		float64(s.AuthRefreshes))
}

func (vrsConnection *VRSConnection) RegisterForPortUpdates(brport string, pnc chan *PortIPv4Info) error {
	vrsConnection.registrationChannel <- &Registration{Brport: brport, Channel: pnc, Register: true}
	return nil
}

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


Question:
Find conditions by column.

@param column column
@return conditions

public List<Condition> findConditions(final Column column) {
        List<Condition> result = new LinkedList<>();
        for (AndCondition each : andConditions) {
            result.addAll(Collections2.filter(each.getConditions(), new Predicate<Condition>() {

                @Override
                public boolean apply(final Condition input) {
                    return input.getColumn().equals(column);
                }
            }));
        }
        return result;
    }

public function _addIdColumnConditions(&$query)
        {
            $query[] = "WHERE";
            $keys = Arrays::is($this->_getIdColumnName()) ? $this->_getIdColumnName() : array( $this->_getIdColumnName() );
            $first = true;

            foreach($keys as $key) {
                if ($first) {
                    $first = false;
                } else {
                    $query[] = "AND";
                }

                $query[] = $this->_quoteIdentifier($key);
                $query[] = "= ?";
            }
        }

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


Question:
In-situ converts the white on black images of a directory to black on white images

        :param image_directory: The directory, that contains the images
        :param image_file_ending: The pattern for finding files in the image_directory

def invert_images(self, image_directory: str, image_file_ending: str = "*.bmp"):

        image_paths = [y for x in os.walk(image_directory) for y in glob(os.path.join(x[0], image_file_ending))]
        for image_path in tqdm(image_paths, desc="Inverting all images in directory {0}".format(image_directory)):
            white_on_black_image = Image.open(image_path).convert("L")
            black_on_white_image = ImageOps.invert(white_on_black_image)
            black_on_white_image.save(os.path.splitext(image_path)[0] + ".png")

def scan_django_settings(values, imports):
    '''
    '''
    if isinstance(values, (str, bytes)):
        if utils.is_import_str(values):
            imports.add(values)
    elif isinstance(values, dict):
        for k, v in values.items():
            scan_django_settings(k, imports)
            scan_django_settings(v, imports)
    elif hasattr(values, '__file__') and getattr(values, '__file__'):
        imp, _ = utils.import_path_from_file(getattr(values, '__file__'))
        imports.add(imp)
    elif hasattr(values, '__iter__'):
        for item in values:
            scan_django_settings(item, imports)

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


Question: // Copy returns a copy of this RawConfig, uninterpolated.

func (r *RawConfig) Copy() *RawConfig {
	if r == nil {
		return nil
	}

	r.lock.Lock()
	defer r.lock.Unlock()

	if r.Body != nil {
		return NewRawConfigHCL2(r.Body)
	}

	newRaw := make(map[string]interface{})
	for k, v := range r.Raw {
		newRaw[k] = v
	}

	result, err := NewRawConfig(newRaw)
	if err != nil {
		panic("copy failed: " + err.Error())
	}

	result.Key = r.Key
	return result
}

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

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


Question: Public: Convert video URL to a valid video URL

public function getVideo()
    {
        // This function is based on code by Wouter Sioen released under the MIT license
        // see woutersioen/sir-trevor-php
        // Regexps from http://stackoverflow.com/questions/10488943/easy-way-to-get-vimeo-id-from-a-vimeo-url
        // and http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url
        if (preg_match('/.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/', $this->getVideoUrl(), $matches)) {
            $data = array(
                'source' => 'youtube',
                'remote_id' => $matches[1]
            );
        } elseif (preg_match('/(?:https?:\/\/)?(?:www\.)?(?:player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/', $this->getVideoUrl(), $matches)) {
            $data = array(
                'source' => 'vimeo',
                'remote_id' => $matches[2]
            );
        } else {
            throw new \FelixOnline\Exceptions\InternalException('The specified video URL is not valid');
        }

        if ($data['source'] == 'youtube') {
            $html = '' . "\n";
        } else {
            $html = '' . "\n";
        }

        return $html;
    }

protected function buildUrl($path)
    {
        $path = str_replace('%2F', '/', $path);
        $path = str_replace(' ', '%20', $path);

        return rtrim($this->base, '/') . '/' . $path;
    }

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


Question:
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.

func (_PublicResolver *PublicResolverRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
	return _PublicResolver.Contract.PublicResolverCaller.contract.Call(opts, result, method, params...)
}

func (at AnyType) GoType(pkg string, d Domain) string {
	switch at.getType() {
	case "any":
		return "json.RawMessage"
	case "boolean":
		return "bool"
	case "string":
		return "string"
	case "number":
		return "float64"
	case "integer":
		return "int"
	case "object":
		return "struct"
	case "array":
		return "[]" + at.Items.GoType(pkg, d)
	case "reference":
		return at.refType(d)
	case "time":
		return "time.Time"
	case "enum":
		// Enums are handled specially.
		return "enum"
	case "base64":
		// By using a []byte here, Base64-encoded images are
		// automatically decoded by json.Unmarshal.
		return "[]byte"
	case "raw":
		// Special []byte, without bas64 decoding.
		return "RawMessage"
	default:
		log.Panicf("unhandled type: %#v", at)
	}

	panic("unreachable")
}

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


Question: // SetName sets the Name field's value.

func (s *CreateFunctionDefinitionOutput) SetName(v string) *CreateFunctionDefinitionOutput {
	s.Name = &v
	return s
}

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

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

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


Question: Marshall the given parameter object.

public void marshall(StartGatewayRequest startGatewayRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(startGatewayRequest.getGatewayARN(), GATEWAYARN_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: Provides appropiate parameters to the intent functions.

def _map_intent_to_view_func(self, intent):
        """"""
        if intent.label in self._intent_view_funcs:
            view_func = self._intent_view_funcs[intent.label]
        elif self._default_intent_view_func is not None:
            view_func = self._default_intent_view_func
        else:
            raise NotImplementedError(
                'Intent "{}" not found and no default intent specified.'.format(intent.name))

        argspec = inspect.getargspec(view_func)
        arg_names = argspec.args
        arg_values = self._map_params_to_view_args(intent.label, arg_names)

        return partial(view_func, *arg_values)

func NewPlainDialer(host string, port int, username, password string) *Dialer {
	return NewDialer(host, port, username, password)
}

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


Question: Read frames with Scapy.

def _scapy_read_frame(self):
        """"""
        from pcapkit.toolkit.scapy import (ipv4_reassembly, ipv6_reassembly,
                                           packet2chain, packet2dict, tcp_reassembly,
                                           tcp_traceflow)

        # fetch Scapy packet
        packet = next(self._extmp)

        # verbose output
        self._frnum += 1
        self._proto = packet2chain(packet)
        if self._flag_v:
            print(f' - Frame {self._frnum:>3d}: {self._proto}')

        # write plist
        frnum = f'Frame {self._frnum}'
        if not self._flag_q:
            info = packet2dict(packet)
            if self._flag_f:
                ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
                ofile(info, name=frnum)
            else:
                self._ofile(info, name=frnum)

        # record frames
        if self._flag_d:
            # setattr(packet, 'packet2dict', packet2dict)
            # setattr(packet, 'packet2chain', packet2chain)
            self._frame.append(packet)

        # record fragments
        if self._ipv4:
            flag, data = ipv4_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[0](data)  # pylint: disable=E1102
        if self._ipv6:
            flag, data = ipv6_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[1](data)  # pylint: disable=E1102
        if self._tcp:
            flag, data = tcp_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[2](data)  # pylint: disable=E1102

        # trace flows
        if self._flag_t:
            flag, data = tcp_traceflow(packet, count=self._frnum)
            if flag:
                self._trace(data)

        return packet

def __initialize_snapshot(self):

        if not self.__processDict:
            try:
                self.scan_processes()       # remote desktop api (relative fn)
            except Exception:
                self.scan_processes_fast()  # psapi (no filenames)
            self.scan_process_filenames()

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


Question:
Should a page be included in the sitemap?

@param Page $page

@return bool

public function canIncludePageInSitemap(Page $page)
    {
        $result = false;
        if ($this->isPageStandard($page)) {
            if ($this->isPagePublished($page)) {
                if (!$this->isPageExcludedFromSitemap($page)) {
                    if ($this->isPageAccessible($page)) {
                        $result = true;
                    }
                }
            }
        }

        return $result;
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question: // close logger, flush all chan data and destroy all adapters in BeeLogger.

func (bl *BeeLogger) Close() {
	bl.lock.Lock()
	bl.status = CLOSE
	close(bl.steal)
	bl.lock.Unlock()

	bl.lock.RLock()
	defer bl.lock.RUnlock()
	for {
		if len(bl.msg) > 0 {
			bm := <-bl.msg
			for _, l := range bl.outputs {
				err := l.WriteMsg(bm.msg, bm.level)
				if err != nil {
					fmt.Println("ERROR, unable to WriteMsg (while closing logger):", err)
				}
			}
			continue
		}
		break
	}

	for _, l := range bl.outputs {
		l.Flush()
		l.Destroy()
	}
}

private function beforeClose()
    {
        if ($this->isWritable() && $this->remainder !== '') {
            $this->stream->write(base64_encode($this->remainder));
            $this->remainder = '';
        }
    }

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


Question:
Plug an Phug extension to Pug.

@param ExtensionInterface $extension

public function addExtension(ExtensionInterface $extension)
    {
        if (!in_array($extension, $this->extensions)) {
            $this->extensions[] = $extension;
            $options = Phug::getExtensionsOptions([$extension]);
            foreach ([$this, $this->getCompiler()] as $instance) {
                $instance->setOptionsRecursive($options);
            }

            $this->initCompiler();
        }
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question:
Render the exception to a response.

@param  \Illuminate\Http\Request  $request
@param  \Exception  $e
@return \Symfony\Component\HttpFoundation\Response

protected function renderException($request, Exception $e)
    {
        return $this->app[ExceptionHandler::class]->render($request, $e);
    }

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

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

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

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

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

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

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

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

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

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

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

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


Question:
Set a cookie.

@param string $key Canonical name of the cookie.
@param string $val Value to be set.
@param int $lifetime Lifetime in seconds from now (defaults to 30 days).
@param bool $track Whether to set a expiry-tracking cookie.
@return bool

public function setCookie( $key, $val, $lifetime = 2592000, $track = TSINT_COOKIE_TRACK ) {
		// Validate cookie name
		$name = $this->getCookieName( $key );
		if ( !$name ) {
			return false;
		}

		$val = strval( $val );
		$lifetime = intval( $lifetime );
		$expire = time() + $lifetime;

		// Set a 30-day domain-wide cookie
		setcookie( $name, $val, $expire, '/' );

		// In order to keep track of the expiration date, we set another cookie
		if ( $track === TSINT_COOKIE_TRACK ) {
			$this->setExpiryTrackerCookie( $lifetime );
		}

		return true;
	}

def __add_default_values(self):

        self.__sp.setdefault('assertionConsumerService', {})
        self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)

        self.__sp.setdefault('attributeConsumingService', {})

        self.__sp.setdefault('singleLogoutService', {})
        self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)

        # Related to nameID
        self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
        self.__security.setdefault('nameIdEncrypted', False)

        # Metadata format
        self.__security.setdefault('metadataValidUntil', None)  # None means use default
        self.__security.setdefault('metadataCacheDuration', None)  # None means use default

        # Sign provided
        self.__security.setdefault('authnRequestsSigned', False)
        self.__security.setdefault('logoutRequestSigned', False)
        self.__security.setdefault('logoutResponseSigned', False)
        self.__security.setdefault('signMetadata', False)

        # Sign expected
        self.__security.setdefault('wantMessagesSigned', False)
        self.__security.setdefault('wantAssertionsSigned', False)

        # NameID element expected
        self.__security.setdefault('wantNameId', True)

        # SAML responses with a InResponseTo attribute not rejected when requestId not passed
        self.__security.setdefault('rejectUnsolicitedResponsesWithInResponseTo', False)

        # Encrypt expected
        self.__security.setdefault('wantAssertionsEncrypted', False)
        self.__security.setdefault('wantNameIdEncrypted', False)

        # Signature Algorithm
        self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)

        # Digest Algorithm
        self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)

        # AttributeStatement required by default
        self.__security.setdefault('wantAttributeStatement', True)

        self.__idp.setdefault('x509cert', '')
        self.__idp.setdefault('certFingerprint', '')
        self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')

        self.__sp.setdefault('x509cert', '')
        self.__sp.setdefault('privateKey', '')

        self.__security.setdefault('requestedAuthnContext', True)
        self.__security.setdefault('failOnAuthnContextMismatch', False)

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


@Override
    protected List<TokenParser> createAllTokenParsers() {
        List<TokenParser> parsers = new ArrayList<>();
        modules.forEach(m -> parsers.addAll(m.getTokenParsers()));

        return parsers;
    }

def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)

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


Question:
Almacena los errores
@param string $error

protected function catchError($error){
        if($this->connection->inTransaction()){
            $this->errorTran[]= $error;
            $this->stateTran= FALSE;
        }
        $this->lastError= $error;

    }

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:
Retrieve (in string format) from this field.
@return The display field of the grid record.

public String getString()
    {
        FieldInfo field = this.getField();
        if (field instanceof StringField)
            return field.toString();
        if (displayFieldName != null)
            return m_record.getField(displayFieldName).getString();  // Return the desc string
        else
            return m_record.getField(m_iFieldSeq).getString();  // Return the desc string
    }

def _serialized(self):
        """"""
        return {'title': self.title,
                'summary': self.summary,
                'areadesc': self.areadesc,
                'event': self.event,
                'samecodes': self.samecodes,
                'zonecodes': self.zonecodes,
                'expiration': self.expiration,
                'updated': self.updated,
                'effective': self.effective,
                'published': self.published,
                'severity': self.severity,
                'category': self.category,
                'urgency': self.urgency,
                'msgtype': self.msgtype,
                'link': self.link,
                }

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


Question:
签名.

@param string $url
@param string $nonce
@param int $timestamp
@param bool $isAdminGroup

@return array

public function getSignaturePackage($url = null, $nonce = null, $timestamp = null, $isAdminGroup = false)
    {
        $url = $url ? $url : $this->getUrl();
        $nonce = $nonce ? $nonce : $this->getNonce();
        $timestamp = $timestamp ? $timestamp : time();
        $ticket = $isAdminGroup ? $this->getGroupTicket() : $this->getTicket();

        $sign = $isAdminGroup ? array(
            'groupId' => $ticket['group_id'],
            'timestamp' => $timestamp,
            'nonceStr' => $nonce,
            'signature' => $this->getSignature($ticket['ticket'], $nonce, $timestamp, $url, true),
        ) : array(
            'appId' => $this->appId,
            'nonceStr' => $nonce,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $this->getSignature($ticket, $nonce, $timestamp, $url),
        );

        return $sign;
    }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question: Default Implementation of TasksSource for AMQP(usually RabbitMQ). Events: - ack: ACK signal was sent to Rabbit.mq through the call of .shift();

function AmqpTasksSource(amqpOptions) {
  TasksSource.apply(this, arguments);
  assert.ok(amqpOptions, "amqpOptions are required in order to create a AmqpTasksSource");
  Object.defineProperty(this, 'amqpOptions', {
    value: amqpOptions,
    enumerable: false,
    configurable: false
  });
  this.connection = null;
  this._amqpExchange = null;
  this.exchangeName = 'orch';
  this._queues = {};
}

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question:
Get a strategy instance.

@param string|null $strategy
@return StrategyInterface
@throws InvalidArgumentException

public function strategy($strategy = null)
    {
        if (is_null($strategy)) {
            $strategy = $this->defaultStrategy ?: OrderStrategy::class;
        }

        if (!class_exists($strategy)) {
            $strategy = __NAMESPACE__ . '\strategies\\' . ucfirst($strategy);
        }

        if (!class_exists($strategy)) {
            throw new InvalidArgumentException("Unsupported strategy \"{$strategy}\"");
        }

        if (empty($this->strategies[$strategy]) || !($this->strategies[$strategy] instanceof StrategyInterface)) {
            $this->strategies[$strategy] = new $strategy($this);
        }

        return $this->strategies[$strategy];
    }

protected Route getRouteStrategy(ControllerMethod controllerMethod, Parameter[] parameterNames) {
		return new FixedMethodStrategy(originalUri, controllerMethod, this.supportedMethods, builder.build(), priority, parameterNames);
	}

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


Question:
Saves a Counter to a text file. Counter written as one key/count pair per
line, separated by whitespace.

public static <E> void saveCounter(Counter<E> c, String filename) throws IOException {
    FileOutputStream fos = new FileOutputStream(filename);
    saveCounter(c, fos);
    fos.close();
  }

def _output_results(
            self):

        self.log.info('starting the ``_output_results`` method')

        content = ""
        maxNameLen = 0

        for r in self.results:
            if maxNameLen < len(r["ned_name"]):
                maxNameLen = len(r["ned_name"])

        if len(self.results) == 0:
            content += "No resuls found"
        else:
            thisHeader = "| "
            thisLine = "| "
            for head in self.headers:
                if head == "ned_name":
                    s = maxNameLen
                else:
                    s = self.resultSpacing
                thisHeader += str(head).ljust(s,
                                              ' ') + " | "
                thisLine += ":".ljust(s,
                                      '-') + " | "
            content += thisHeader
            content += "\n" + thisLine
            for r in self.results:
                thisRow = "| "
                for head in self.headers:
                    if head == "ned_name":
                        s = maxNameLen
                    else:
                        s = self.resultSpacing
                    thisRow += str(r[head]).ljust(s,
                                                  ' ') + " | "
                content += "\n" + thisRow

        if self.quiet == False:
            print content
        if self.outputFilePath:
            import codecs
            writeFile = codecs.open(
                self.outputFilePath, encoding='utf-8', mode='w')
            writeFile.write(content)
            writeFile.close()

        self.log.info('completed the ``_output_results`` method')
        return None

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


Question:
Get the list of parameter fillers from the given parameters.

@param parameters the given parameters
@return the parameter fillers, or empty if none of the parameters is recognizable

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question: Flush pending items to Dynamo

def flush(self):

        items = []

        for data in self._to_put:
            items.append(encode_put(self.connection.dynamizer, data))

        for data in self._to_delete:
            items.append(encode_delete(self.connection.dynamizer, data))
        self._write(items)
        self._to_put = []
        self._to_delete = []

@Override
    @Transactional(value = MillJpaRepoConfig.TRANSACTION_MANAGER_BEAN, propagation = Propagation.REQUIRES_NEW)
    public int purgeDeletedItemsBefore(Date expiration) {
        return this.manifestItemRepo.deleteFirst50000ByDeletedTrueAndModifiedBefore(expiration);
    }

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


Question:
Set the validator

@throws Exception
@return void

protected function setValidator()
    {
        // Get query data
        if (!isset($_SERVER['REQUEST_METHOD'])) {
            throw new Exception('Error: The server request method is not set.');
        }
        $queryData = [];
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                $queryData = $_GET;
                break;
            case 'POST':
                $queryData = $_POST;
                break;
            default:
                $input = fopen('php://input', 'r');
                $qData = null;
                while ($data = fread($input, 1024)) {
                    $qData .= $data;
                }
                parse_str($qData, $queryData);
        }
        // If there is query data, set validator to check against the token value
        if (count($queryData) > 0) {
            $val = (isset($queryData[$this->name])) ? $queryData[$this->name] : '';
            $this->addValidator(new \Pop\Validator\Equal($val, 'The security token does not match.'));
        }
    }

public static function createBoundValidator($methodName, ...$boundArgs)
    {
        return function (...$args) use ($methodName, $boundArgs) {
            return call_user_func_array("self::$methodName", array_merge($boundArgs, $args));
        };
    }

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


Question: Returns an array of schema file names defined as entry points

public function getSchemaEntryPoints()
	{
		return array_reduce( $this->entryPoints, function( $carry, $entryPoint ) {
			$schemaFiles = array_filter( $entryPoint['entryPointDocument'], function( $entryPointDocument ) {
				return XBRL::endsWith( $entryPointDocument, ".xsd" );
			} );
			return array_merge( $carry, $schemaFiles );
		}, array() );
	}

private static function input()
    {
        $files = ['Input'];
        $folder = static::$root.'Http'.'/';

        self::call($files, $folder);

        Input::register();
    }

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


Question:
Acknowledge that the message(s) were been processed by the consumer
        associated with the parent :py:class:`ConsumerGroup`.

        :param id_list: one or more message ids to acknowledge
        :returns: number of messages marked acknowledged

def ack(self, *id_list):

        return self.database.xack(self.key, self.group, *id_list)

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question: internal helpers

private GenericConverter.ConvertiblePair getRequiredTypeInfo(Object converter, Class<?> genericIfc) {
		Class<?>[] args = GenericTypeResolver.resolveTypeArguments(converter.getClass(), genericIfc);
		return (args != null ? new GenericConverter.ConvertiblePair(args[0], args[1]) : null);
	}

protected function updateInternalState()
    {
        if (!$this->hasFilter(static::END_DATE_FILTER)) {
            $this->endDate = null;
        }

        if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
            $this->recurrences = null;
        }
    }

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


Question:
Finds the index in 'a' with the largest value.
@param a Input array
@return Index of largest value

public static int findMaxIndex( int[] a ) {
		int max = a[0];
		int index = 0;

		for( int i = 1; i< a.length; i++ ) {
			int val = a[i];

			if( val > max ) {
				max = val;
				index = i;
			}
		}

		return index;
	}

public void rmLittlePathByScore() {
        int maxTo = -1;
        Term temp = null;
        for (int i = 0; i < terms.length; i++) {
            if (terms[i] == null) {
                continue;
            }
            Term maxTerm = null;
            double maxScore = 0;
            Term term = terms[i];
            // 找到自身分数对大最长的

            do {
                if (maxTerm == null || maxScore > term.score()) {
                    maxTerm = term;
                } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) {
                    maxTerm = term;
                }

            } while ((term = term.next()) != null);
            term = maxTerm;
            do {
                maxTo = term.toValue();
                maxScore = term.score();
                if (maxTo - i == 1 || i + 1 == terms.length)
                    continue;
                boolean flag = true;// 可以删除
                out: for (int j = i; j < maxTo; j++) {
                    temp = terms[j];
                    if (temp == null) {
                        continue;
                    }
                    do {
                        if (temp.toValue() > maxTo || temp.score() < maxScore) {
                            flag = false;
                            break out;
                        }
                    } while ((temp = temp.next()) != null);
                }
                // 验证通过可以删除了
                if (flag) {
                    for (int j = i + 1; j < maxTo; j++) {
                        terms[j] = null;
                    }
                }
            } while ((term = term.next()) != null);
        }
    }

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