Question:
//-------------------------------------------------------------------------------
// gc_parser.declarations
//-------------------------------------------------------------------------------
// ImportDecl = "import" identifier string_lit .

func (p *gc_parser) parse_import_decl() {
	p.expect_keyword("import")
	alias := p.expect(scanner.Ident)
	path := p.parse_package()
	fullName := "!" + path.Name + "!" + alias
	p.path_to_name[path.Name] = fullName
	p.pfc.add_package_to_scope(fullName, path.Name)
}

private boolean parseLine() {
    cureid = null;
    curpoly = null;
    curlbl = null;
    polys.clear();
    coords.clear();
    labels.clear();

    Matcher m = COORD.matcher(reader.getBuffer());
    for(/* initialized by nextLineExceptComments */; tokenizer.valid(); tokenizer.advance()) {
      m.region(tokenizer.getStart(), tokenizer.getEnd());
      if(m.find()) {
        try {
          double c1 = ParseUtil.parseDouble(m.group(1));
          double c2 = ParseUtil.parseDouble(m.group(2));
          if(m.group(3) != null) {
            double c3 = ParseUtil.parseDouble(m.group(3));
            coords.add(new double[] { c1, c2, c3 });
          }
          else {
            coords.add(new double[] { c1, c2 });
          }
          continue;
        }
        catch(NumberFormatException e) {
          LOG.warning("Looked like a coordinate pair but didn't parse: " + tokenizer.getSubstring());
        }
      }
      // Match polygon separator:
      // FIXME: Avoid unnecessary subSequence call.
      final int len = tokenizer.getEnd() - tokenizer.getStart();
      if(POLYGON_SEPARATOR.length() == len && //
          reader.getBuffer().subSequence(tokenizer.getStart(), tokenizer.getEnd()).equals(POLYGON_SEPARATOR)) {
        if(!coords.isEmpty()) {
          polys.add(new Polygon(new ArrayList<>(coords)));
        }
        continue;
      }
      String cur = tokenizer.getSubstring();
      // First label will become the External ID
      if(cureid == null) {
        cureid = new ExternalID(cur);
      }
      else {
        labels.add(cur);
      }
    }
    // Complete polygon
    if(!coords.isEmpty()) {
      polys.add(new Polygon(coords));
    }
    curpoly = new PolygonsObject(polys);
    curlbl = (haslabels || !labels.isEmpty()) ? LabelList.make(labels) : null;
    return true;
  }

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


Question:
@param float $south
@param float $west
@param float $north

@return Bounds|null

private static function createBounds($south, $west, $north, $east)
    {
        if (null === $south || null === $west || null === $north || null === $east) {
            return null;
        }

        return new Bounds($south, $west, $north, $east);
    }

def create_node(**kwargs):
    '''

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

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

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

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

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

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

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

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

    return {}

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


Question:
This causes OpenALPR to attempt to recognize an image by opening a file on
        disk.

        :param file_path: The path to the image that will be analyzed
        :return: An OpenALPR analysis in the form of a response dictionary

def recognize_file(self, file_path):

        file_path = _convert_to_charp(file_path)
        ptr = self._recognize_file_func(self.alpr_pointer, file_path)
        json_data = ctypes.cast(ptr, ctypes.c_char_p).value
        json_data = _convert_from_charp(json_data)
        response_obj = json.loads(json_data)
        self._free_json_mem_func(ctypes.c_void_p(ptr))
        return response_obj

def pairs(args):

    p = OptionParser(pairs.__doc__)
    p.set_firstN()
    p.set_mates()
    p.set_aligner()
    opts, args = p.parse_args(args)

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

    cwd = os.getcwd()
    aligner = opts.aligner
    work = "-".join(("pairs", aligner))
    mkdir(work)

    from jcvi.formats.sam import pairs as ps
    if aligner == "bowtie":
        from jcvi.apps.bowtie import align
    elif aligner == "bwa":
        from jcvi.apps.bwa import align

    folder, ref = args
    ref = get_abs_path(ref)
    messages = []
    for p, prefix in iter_project(folder):
        samplefq = []
        for i in range(2):
            samplefq.append(op.join(work, prefix + "_{0}.first.fastq".format(i+1)))
            first([str(opts.firstN)] + [p[i]] + ["-o", samplefq[i]])

        os.chdir(work)
        align_args = [ref] + [op.basename(fq) for fq in samplefq]
        outfile, logfile = align(align_args)
        bedfile, stats = ps([outfile, "--rclip={0}".format(opts.rclip)])
        os.chdir(cwd)

        median = stats.median
        tag = "MP" if median > 1000 else "PE"
        median = str(median)
        pf, sf = median[:2], median[2:]
        if sf and int(sf) != 0:
            pf = str(int(pf) + 1)  # Get the first two effective digits
        lib = "{0}-{1}".format(tag, pf + '0' * len(sf))
        for i, xp in enumerate(p):
            suffix = "fastq.gz" if xp.endswith(".gz") else "fastq"
            link = "{0}-{1}.{2}.{3}".format(lib, prefix.replace("-", ""),
                                            i + 1, suffix)
            m = "\t".join(str(x) for x in (xp, link))
            messages.append(m)

    messages = "\n".join(messages)
    write_file("f.meta", messages, tee=True)

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


Question:
Get User's data by key

@param string $key key to get value
@param int    $id  user id to get value from

@return string

public function getUserData($key, $id = 0)
    {
        // Current User id
        if (!$id) {
            if (defined('USER_ID')) {
                $id = USER_ID;
            } else {
                return NULL;
            }
        } else {
            $id = abs((int)$id);
        }

        // Check or init cache
        if (!isset(self::$cached_user_data[$id])) {
            $user = AdminUserRepository::findOneEntityById($id);
            if (!$user) {
                return NULL;
            }
            self::$cached_user_data[$id] = $user->getAsArray();

            // Unset critical data
            unset(self::$cached_user_data[$id]['password']);
        }

        return isset(self::$cached_user_data[$id][$key]) ? self::$cached_user_data[$id][$key] : NULL;
    }

public static String getParameter(final Request request, final String parameterName)
	{
		String parameterValue = request.getRequestParameters().getParameterValue(parameterName)
			.toString();
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getPostParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getQueryParameters().getParameterValue(parameterName)
				.toString();
		}
		if ((parameterValue == null) || parameterValue.isEmpty())
		{
			parameterValue = request.getRequestParameters().getParameterValue(parameterName)
				.toString();
		}
		return parameterValue;
	}

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


Question:
/* (non-Javadoc)
@see org.jboss.as.cli.operation.OperationRequestHeader#toModelNode()

@Override
    public void addTo(CommandContext ctx, ModelNode headers) throws CommandFormatException {
        if(name == null) {
            throw new CommandFormatException("Header name is null.");
        }
        if(value == null) {
            throw new CommandFormatException("Value for header '" + name + "' is null.");
        }
        headers.get(name).set(value);
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question:
Asserts that the requested sub list is available in the virtual list. Otherwise it throws
an IndexOutOfBoundsException.

@param from the from index (inclusive)
@param to   the to index (inclusive)

private void assertSubRange(long from, long to) {
        if (!checkSubRange(from) || !checkSubRange(to)) {
            throw new IndexOutOfBoundsException("Required data for the sub list [" + from + "," + (to + 1) + "[ have "
                    + "not been loaded in the virtual list.");
        }
    }

public <E extends Exception> boolean allMatch(Try.ShortPredicate<E> filter) throws E {
        return allMatch(0, size(), filter);
    }

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


Question:
// TagValueIn will retrieve the tagged value from the error that's associated
// with this key, and a boolean indicating if the tag was present or not.

func TagValueIn(t TagKey, err error) (value interface{}, ok bool) {
	Walk(err, func(err error) bool {
		if sc, isSC := err.(stackContexter); isSC {
			if value, ok = sc.stackContext().tags[t]; ok {
				return false
			}
		}
		return true
	})
	return
}

protected void transportTrailersReceived(Metadata trailers) {
    Preconditions.checkNotNull(trailers, "trailers");
    if (transportError == null && !headersReceived) {
      transportError = validateInitialMetadata(trailers);
      if (transportError != null) {
        transportErrorMetadata = trailers;
      }
    }
    if (transportError != null) {
      transportError = transportError.augmentDescription("trailers: " + trailers);
      http2ProcessingFailed(transportError, false, transportErrorMetadata);
    } else {
      Status status = statusFromTrailers(trailers);
      stripTransportDetails(trailers);
      inboundTrailersReceived(trailers, status);
    }
  }

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


Question:
@param string         $action
@param ResourceNode[] $nodes
@param TokenInterface $token

@return array

@throws \Exception

protected function checkAction($action, array $nodes, TokenInterface $token)
    {
        $haveSameWorkspace = true;
        $ws = $nodes[0]->getWorkspace();

        foreach ($nodes as $node) {
            if ($node->getWorkspace() !== $ws) {
                $haveSameWorkspace = false;
                break;
            }
        }

        //the workspace manager he can do w/e he wants
        if ($haveSameWorkspace && $ws && $this->isWorkspaceManager($ws, $token)) {
            return [];
        }

        //the resource creator can do w/e he wants
        $timesCreator = 0;

        foreach ($nodes as $node) {
            if ($node->getCreator() === $token->getUser()) {
                ++$timesCreator;
            }
        }

        //but it only work if he's not usurping a workspace role to see if everything is good
        if ($timesCreator === count($nodes) && !$this->isUsurpatingWorkspaceRole($token)) {
            return [];
        }

        //check if the action is possible on the node
        $errors = [];
        $action = strtolower($action);

        foreach ($nodes as $node) {
            if ($node->isActive()) {
                $mask = $this->repository->findMaximumRights($this->ut->getRoles($token), $node);
                $type = $node->getResourceType();
                $decoder = $this->maskManager->getDecoder($type, $action);
                // Test if user can administrate
                $adminDecoder = $this->maskManager->getDecoder($type, 'administrate');
                $canAdministrate = $adminDecoder ? (0 !== ($mask & $adminDecoder->getValue())) : false;
                // If user can administrate OR resource is open then check action
                if ($canAdministrate ||
                    ($this->restrictionsManager->isStarted($node) &&
                     !$this->restrictionsManager->isEnded($node) &&
                    $node->isPublished())) {
                    //gotta check
                    if (!$decoder) {
                        return ['The permission '.$action.' does not exists for the type '.$type->getName()];
                    }

                    $grant = $decoder ? $mask & $decoder->getValue() : 0;

                    if ($decoder && 0 === $grant) {
                        $errors[] = $this->getRoleActionDeniedMessage($action, $node->getPathForDisplay());
                    }
                } else {
                    $errors[] = $this->getRoleActionDeniedMessage($action, $node->getPathForDisplay());
                }
            } else {
                $errors[] = $this->getRoleActionDeniedMessage($action, $node->getPathForDisplay());
            }
        }

        return $errors;
    }

public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) {

        if (operation == null)
            throw new IllegalArgumentException(
                    "The operation parameter must be specified!");

        ShapeMarshaller marshaller = new ShapeMarshaller()
                .withAction(operation.getName())
                .withVerb(operation.getHttp().getMethod())
                .withRequestUri(operation.getHttp().getRequestUri());
        Input input = operation.getInput();
        if (input != null) {
            marshaller.setLocationName(input.getLocationName());
            // Pass the xmlNamespace trait from the input reference
            XmlNamespace xmlNamespace = input.getXmlNamespace();
            if (xmlNamespace != null) {
                marshaller.setXmlNameSpaceUri(xmlNamespace.getUri());
            }
        }
        if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) {
            marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName());
        }
        return marshaller;

    }

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


Question:
This function creates and returns a new HTTP method.

@param   url
The target URL
@param   httpMethod
The HTTP method to use
@return  The new HTTP method

protected HttpMethodBase createMethod(String url,HTTPMethod httpMethod)
    {
        if(httpMethod==null)
        {
            throw new FaxException("HTTP method not provided.");
        }
        if((url==null)||(url.length()==0))
        {
            throw new FaxException("HTTP URL not provided.");
        }

        //create method
        HttpMethodBase httpMethodClient=null;
        switch(httpMethod)
        {
            case POST:
                httpMethodClient=new PostMethod(url);
                break;
            case GET:
                httpMethodClient=new GetMethod(url);
                break;
            case PUT:
                httpMethodClient=new PutMethod(url);
                break;
        }

        return httpMethodClient;
    }

func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string,
	routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool,
	args map[string]interface{}, data interface{}) (BaseResponse, error) {
	var url string
	var retval BaseResponse
	url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh)
	if err != nil {
		return retval, err
	}
	var method string
	if len(id) == 0 {
		method = "POST"
	} else {
		method = "PUT"
	}
	body, err := c.DoCommand(method, url, args, data)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}

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


Question: // Names returns the names of the attributes

func (a *Attributes) Names() []string {
	i := 0
	names := make([]string, len(a.Attrs))
	for name := range a.Attrs {
		names[i] = name
		i++
	}
	return names
}

public void attributeDecl(
        String arg0,
        String arg1,
        String arg2,
        String arg3,
        String arg4)
        throws SAXException
    {
        m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4);
    }

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


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

public EClass getIfcTextStyle() {
		if (ifcTextStyleEClass == null) {
			ifcTextStyleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(603);
		}
		return ifcTextStyleEClass;
	}

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:
@param Merchant $merchant
@param array    $data

@return Merchant

public static function ChangeMerchant(Merchant $merchant, $data)
	{
		$merchant->username = $data['username'];
		$merchant->callback_url = $data['callback'];
		$merchant->email = $data['email'];
		$merchant->key = $data['key'];

		if (null != $data['password']) {
			$merchant->password = $data['password'];
		}
		$merchant->save();

		return $merchant;
	}

public function getStatusesHuman()
    {
        return [
            self::STATUS_PENDING          => 'Pending',
            self::STATUS_PROCESSING       => 'Processing',
            self::STATUS_COMPLETE         => 'Complete',
            self::STATUS_FAILED           => 'Failed',
            self::STATUS_REFUNDED         => 'Refunded',
            self::STATUS_REFUNDED_PARTIAL => 'Partially Refunded',
        ];
    }

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


Question:
/*
(non-Javadoc)

@see com.googlecode.openbeans.beancontext.BeanContext#getResource(java.lang.String, com.googlecode.openbeans.beancontext.BeanContextChild)

public URL getResource(String resourceName, BeanContextChild child)
	{
		if (resourceName == null || child == null)
		{
			throw new NullPointerException();
		}
		if (!contains(child))
		{
			throw new IllegalArgumentException(Messages.getString("beans.6D"));
		}

		return ClassLoader.getSystemResource(resourceName);
	}

public String getMessage(String id, String defaultMsg) {
    return getMessage(id, lang, defaultMsg);
  }

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


Question:
Removes a scan engine from the list of available engines.

 @param [Fixnum] engine_id Unique ID of an existing engine to remove.
 @param [String] scope Whether the engine is global or silo scoped.
 @return [Boolean] true if engine successfully deleted.

def delete_engine(engine_id, scope = 'silo')
      xml = make_xml('EngineDeleteRequest', { 'engine-id' => engine_id, 'scope' => scope })
      response = execute(xml, '1.2')
      response.success
    end

def delete(name, wait=False, region=None, key=None, keyid=None, profile=None):
    '''

    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        conn.delete_cache_cluster(name)
        if not wait:
            log.info('Deleted cache cluster %s.', name)
            return True
        while True:
            config = get_config(name, region, key, keyid, profile)
            if not config:
                return True
            if config['cache_cluster_status'] == 'deleting':
                return True
            time.sleep(2)
        log.info('Deleted cache cluster %s.', name)
        return True
    except boto.exception.BotoServerError as e:
        msg = 'Failed to delete cache cluster {0}.'.format(name)
        log.error(msg)
        log.debug(e)
        return False

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


Question:
Create a prepared statement an store it in self::stmnt
@param  string $sql_string SQL string
@return \SQLAnywherePrepared

public function prepare($sql_string, $array=array())
	{
		$this->sql_string = $sql_string;
		return new SQLAnywherePrepared( $this->sql_string, $this->connection, $this->dbinfo );
	}

@Override
    public void setString(String parameterName, String x) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }

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


Question:
Set the view data for the message.

@param  string|array  $key
@param  mixed   $value
@return $this

public function with($key, $value = null)
    {
        if (is_array($key)) {
            $this->viewData = array_merge($this->viewData, $key);
        } else {
            $this->viewData[$key] = $value;
        }

        return $this;
    }

def new
      @parameter = Parameter.new

      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @parameter }
      end
    end

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


Question:
***************************************
Messenger Initialization
***************************************

function (messageEvent) {
		var messageObject = JSON.parse(messageEvent.data || '{}');
		if ((messageObject || {})
			.action && messageObject.action === MESSENGER_CONST.ACTION.CONNECT) {
			appWindow = messageEvent.source;
			appOrigin = messageEvent.origin;
			connectionRequestID = messageObject.id;
			status.initialized = true;
			if (status.enabled) {
				connect();
			}
		}
	}

def _connect(self):

        self.kik_connection_thread = Thread(target=self._kik_connection_thread_function, name="Kik Connection")
        self.kik_connection_thread.start()

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


Question: Fill L submatrix ( see more here)

private void fillPsubMatrix( Coordinate[] controlPoints, GeneralMatrix L ) {
        int controlPointsNum = controlPoints.length;
        for( int i = 0; i < controlPointsNum; i++ ) {
            L.setElement(i, i, 0);

            L.setElement(i, controlPointsNum + 0, 1);
            L.setElement(i, controlPointsNum + 1, controlPoints[i].x);
            L.setElement(i, controlPointsNum + 2, controlPoints[i].y);

            L.setElement(controlPointsNum + 0, i, 1);
            L.setElement(controlPointsNum + 1, i, controlPoints[i].x);
            L.setElement(controlPointsNum + 2, i, controlPoints[i].y);
        }
    }

def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"):

        return self.__do_menu("as_p", show_leaf, current_linkable, class_current)

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


Question: Generates a random integer in the available range.

def simulate(self):
        """"""
        min_ = (-sys.maxsize - 1) if self._min is None else self._min
        max_ = sys.maxsize if self._max is None else self._max
        return random.randint(min_, max_)

func getBin(xr *XorRand) *as.Bin {
	var bin *as.Bin
	switch binDataType {
	case "B":
		bin = &as.Bin{Name: "B", Value: getRandValue(xr)}
	case "S":
		bin = &as.Bin{Name: "S", Value: getRandValue(xr)}
	default:
		bin = &as.Bin{Name: "I", Value: getRandValue(xr)}
	}

	return bin
}

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


Question:
Get the contact url (with the given id)
@param int $ContactUrlId
@return models\Call\ContactUrl

public function getFromId( $ContactUrlId){
        $rest = $this->getService( self::API_URL . $ContactUrlId);
        $rest->GET();

        return $rest->getResult( models\Call\ContactUrl::class);
    }

public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setId($value);
                break;
            case 1:
                $this->setDtCall($value);
                break;
            case 2:
                $this->setRemoteAppId($value);
                break;
            case 3:
                $this->setStatuscode($value);
                break;
            case 4:
                $this->setLastResponse($value);
                break;
        } // switch()
    }

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


Question:
Flushes the stream if it's not closed and checks its error state.

@return true if the print stream has encountered an error,
either on the underlying output stream or during a format
conversion.

public boolean checkError() {
        if (out != null) {
            flush();
        }
        if (out instanceof java.io.PrintWriter) {
            PrintWriter pw = (PrintWriter) out;
            return pw.checkError();
        } else if (psOut != null) {
            return psOut.checkError();
        }
        return trouble;
    }

public static Boolean coerceToBoolean(Object pValue,
                                          Logger pLogger)
            throws ELException {
        if (pValue == null ||
                "".equals(pValue)) {
            return Boolean.FALSE;
        } else if (pValue instanceof Boolean) {
            return (Boolean) pValue;
        } else if (pValue instanceof String) {
            String str = (String) pValue;
            try {
                return Boolean.valueOf(str);
            }
            catch (Exception exc) {
                if (pLogger.isLoggingError()) {
                    pLogger.logError
                            (Constants.STRING_TO_BOOLEAN,
                                    exc,
                                    (String) pValue);
                }
                return Boolean.FALSE;
            }
        } else {
            if (pLogger.isLoggingError()) {
                pLogger.logError
                        (Constants.COERCE_TO_BOOLEAN,
                                pValue.getClass().getName());
            }
            return Boolean.TRUE;
        }
    }

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


Question:
Deletes the user from the disk

@param userName
@return True if successful.

public boolean deleteUser(String userName) {
		// load user info from file
		if (resourcePath != null) {

			lock.writeLock().lock();
			try {
				File userDir = new File(resourcePath, "users");
				if (userDir.isDirectory()) {
					// get the file which corresponds to the user
					File userFile = new File(userDir.getAbsolutePath(), userName);
					return userFile.delete();
				}
			} finally {
				lock.writeLock().unlock();
			}
		} // end if resourcePath not null
		return false;
	}

protected function buildDeleteQuery(SQLDelete $query, array &$parameters)
    {
        $sql  = $this->buildDeleteFragment($query, $parameters);
        $sql .= $this->buildFromFragment($query, $parameters);
        $sql .= $this->buildWhereFragment($query, $parameters);
        return $sql;
    }

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


Question: // MonthWide returns the locales wide month given the 'month' provided

func (ksh *ksh) MonthWide(month time.Month) string {
	return ksh.monthsWide[month]
}

static public function create($params, LocatorInterface $locator = null) {
		if (! is_array($params) && ! $params instanceof Traversable) {
			throw new InvalidOptions('Options must be an array or a Traversable implementation');
		}

		if ($params instanceof Traversable) {
			$params = Std::iteratorToArray($params);
		}

		$translator = new Translator();

		foreach ($params as $param => $value) {
			if ($param === 'cacheStrategy') {
				$class = self::NAMESPACE_CACHE . '\Strategy' . ucfirst($value);

				$translator->setCache(new $class($locator));
				unset($params[$param]);
				continue;
			}

			if ($param === 'resources') {
				if (! is_array($value) && ! $value instanceof Traversable) {
					throw new InvalidOptions('Resources definition must be an array or a Traversable implementation');
				}

				$translator->setResources(self::createResources($value));
				unset($params[$param]);
				continue;
			}

			if ($param === 'bbcodes') {
				if ($value) {
					$bbcodes = new BBCodes();

					if (isset($params['paramsPattern'])) {
						$bbcodes->setParamsPattern($params['paramsPattern']);
					}

					$translator->addPlugin($bbcodes, 'bbcodes');
				}

				unset($params[$param]);
			}
		}

		$translator->setOptions($params, false, false);

		return $translator;
	}

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


Question: // Run all mandatory Amazon security checks on the request.

func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	devFlag := r.URL.Query().Get("_dev")
	isDev := devFlag != ""
	if !isDev && !IsValidAlexaRequest(w, r) {
		log.Println("Request invalid")
		return
	}
	next(w, r)
}

public static String orderQuery(boolean isSandbox, Map<String, String> params) {
		if (isSandbox)
			return doPost(ORDERQUERY_SANDBOXNEW_URL, params);
		return doPost(ORDERQUERY_URL, params);
	}

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


Question:
Gets the events that occurred during the call.

@return events the events list
@throws IOException unexpected error.

public List<EventBase> getEventsList() throws Exception {
        final String eventsPath = StringUtils.join(new String[]{
                getUri(),
                "events"
        }, '/');
        final JSONArray array = toJSONArray(client.get(eventsPath, null));

        final List<EventBase> list = new ArrayList<EventBase>();
        for (final Object object : array) {
            list.add(new EventBase((JSONObject) object));
        }
        return list;
    }

public void get_asynch_replies(final DeviceProxy dev) {
        final Enumeration _enum = async_request_table.keys();
        while (_enum.hasMoreElements()) {
            int n = (Integer)_enum.nextElement();
                final AsyncCallObject aco = async_request_table.get(n);
                if (aco.dev == dev) {
                    aco.manage_reply(ApiDefs.NO_TIMEOUT);
            }
        }
    }

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


Question:
selector
: (IDENT | ASTERISK)  selpart* S*
| selpart+ S*
;

public Selector visitSelector(CSSParser.SelectorContext ctx) {
        if (ctxHasErrorNode(ctx)) {
            statement_stack.peek().invalid = true;
            return null;
        }
        selector_stack.push(new selector_scope());
        cz.vutbr.web.css.Selector sel;
        logEnter("selector");
        selector_stack.peek().s = sel = (cz.vutbr.web.css.Selector) rf.createSelector().unlock();
        if (ctx.IDENT() != null || ctx.ASTERISK() != null) {
            cz.vutbr.web.css.Selector.ElementName en = rf.createElement(cz.vutbr.web.css.Selector.ElementName.WILDCARD);
            if (ctx.IDENT() != null) {
                en.setName(extractTextUnescaped(ctx.IDENT().getText()));
            }
            //log.debug("Adding element name: {}.", en.getName());
            selector_stack.peek().s.add(en);
        }
        for (CSSParser.SelpartContext selpartctx : ctx.selpart()) {
            visitSelpart(selpartctx);
        }

        logLeave("selector");
        selector_stack.pop();
        return sel;
    }

def predicates(predicate, collection, klass, column_name, value)
      case predicate
      when :between
        klass.arel_table[column_name].between(value.first..value.last)
      when :does_not_match
        klass.arel_table[column_name].does_not_match("%#{value}%")
      when :does_not_match_all
        klass.arel_table[column_name].does_not_match_all(value)
      when :does_not_match_any
        klass.arel_table[column_name].does_not_match_any(value)
      when :eq
        klass.arel_table[column_name].eq(value)
      when :eq_all
        klass.arel_table[column_name].eq_all(value)
      when :eq_any
        klass.arel_table[column_name].eq_any(value)
      when :gt
        klass.arel_table[column_name].gt(value)
      when :gt_all
        klass.arel_table[column_name].gt_all(value)
      when :gt_any
        klass.arel_table[column_name].gt_any(value)
      when :gteq
        klass.arel_table[column_name].gteq(value)
      when :gteq_all
        klass.arel_table[column_name].gteq_all(value)
      when :gteq_any
        klass.arel_table[column_name].gteq_any(value)
      when :in
        klass.arel_table[column_name].in(value)
      when :in_all
        klass.arel_table[column_name].in_all(value)
      when :in_any
        klass.arel_table[column_name].in_any(value)
      when :lt
        klass.arel_table[column_name].lt(value)
      when :lt_all
        klass.arel_table[column_name].lt_all(value)
      when :lt_any
        klass.arel_table[column_name].lt_any(value)
      when :lteq
        klass.arel_table[column_name].lteq(value)
      when :lteq_all
        klass.arel_table[column_name].lteq_all(value)
      when :lteq_any
        klass.arel_table[column_name].lteq_any(value)
      when :ilike
        klass.arel_table[column_name].matches("%#{value}%")
      when :matches
        klass.arel_table[column_name].matches(value)
      when :matches_all
        klass.arel_table[column_name].matches_all(value)
      when :matches_any
        klass.arel_table[column_name].matches_any(value)
      when :not_between
        klass.arel_table[column_name].not_between(value.first..value.last)
      when :not_eq
        klass.arel_table[column_name].not_eq(value)
      when :not_eq_all
        klass.arel_table[column_name].not_eq_all(value)
      when :not_eq_any
        klass.arel_table[column_name].not_eq_any(value)
      when :not_in
        klass.arel_table[column_name].not_in(value)
      when :not_in_all
        klass.arel_table[column_name].not_in_all(value)
      when :not_in_any
        klass.arel_table[column_name].not_in_any(value)
      else
        unless predicate.respond_to?(:call)
          raise ArgumentError,
                "unsupported predicate `#{predicate}`"
        end

        predicate.call(collection, value)
      end
    end

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


Question: Choose color scheme

def _choose_scheme(self):
        """"""
        if self.style_cols[self.color] in ('string', 'boolean', ):
            self.scheme = antique(10)
        elif self.style_cols[self.color] in ('number', ):
            self.scheme = mint(5)
        elif self.style_cols[self.color] in ('date', 'geometry', ):
            raise ValueError(
                'Cannot style column `{col}` of type `{type}`. It must be '
                'numeric, text, or boolean.'.format(
                    col=self.color, type=self.style_cols[self.color]))

public function formatScheme($secure)
    {
        if (!is_null($secure)) {
            return $secure ? 'https://' : 'http://';
        }
        if (is_null($this->cachedSchema)) {
            $this->cachedSchema = $this->forceScheme ?: $this->getContext()->getScheme() . '://';
        }
        return $this->cachedSchema;
    }

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


Question:
Join the specified group, per:

http://developer.linkedin.com/documents/groups-api

@param str $gid
The group id.

@return arr
Array containing retrieval success, LinkedIn response.

public function joinGroup($gid) {
		if(!is_string($gid)) {
			throw new LinkedInException('LinkedIn->joinGroup(): bad data passed, $gid must be of type string.');
		}

		// constructing the XML
		$data = '<?xml version="1.0" encoding="UTF-8"?>
  				   <group-membership>
  				   	 <membership-state>
  				  	 	 member
  				  	 </membership-state>
  				   </group-membership>';

		// construct and send the request
		$query    = self::_URL_API . '/v1/people/~/group-memberships/' . trim($gid);
		$response = $this->fetch('PUT', $query, $data);

		/**
	   * Check for successful request (a 200 or 201 response from LinkedIn server)
	   * per the documentation linked in method comments above.
	   */
		return $this->checkResponse(array(200, 201), $response);
	}

func (s *AcceptPortfolioShareInput) SetPortfolioId(v string) *AcceptPortfolioShareInput {
	s.PortfolioId = &v
	return s
}

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


Question:
Iterates through and gathers the projects to validate along with scanning all the other
projects to gather their information for validating the projects.

@throws IOException
@throws JAXBException

private void gatherMetatypeFilesAndStats() throws IOException, JAXBException {
        for (File bundle : directory.listFiles()) {
            if (bundle.isFile()) {
                analyzeBundle(bundle);
            }
        }
    }

public void updateIndex(ChangesHolder changes, ChangesHolder parentChanges)
   {
      // pass lists to search manager
      if (searchManager != null && changes != null)
      {
         try
         {
            searchManager.apply(changes);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               handler.logErrorChanges(new HashSet<String>(changes.getRemove()), new HashSet<String>(changes
                  .getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
      // pass lists to parent search manager
      if (parentSearchManager != null && parentChanges != null)
      {
         try
         {
            parentSearchManager.apply(parentChanges);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               parentHandler.logErrorChanges(new HashSet<String>(parentChanges.getRemove()), new HashSet<String>(
                  parentChanges.getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
   }

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


Question: Deserialize a base-58-encoded HD Key with no parent

public static DeterministicKey deserializeB58(String base58, NetworkParameters params) {
        return deserializeB58(null, base58, params);
    }

func (d *decodeState) unmarshalValue(data Slice, v reflect.Value) {
	if !v.IsValid() {
		return
	}

	switch data.Type() {
	case Array:
		d.unmarshalArray(data, v)
	case Object:
		d.unmarshalObject(data, v)
	case Bool, Int, SmallInt, UInt, Double, Binary, BCD, String:
		d.unmarshalLiteral(data, v)
	}
}

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


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

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.TBM__DIRCTION:
				setDIRCTION((Integer)newValue);
				return;
			case AfplibPackage.TBM__PRECSION:
				setPRECSION((Integer)newValue);
				return;
			case AfplibPackage.TBM__INCRMENT:
				setINCRMENT((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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:
Check the given plain value against a hash.

@param  string  $value
@param  string  $hashedValue
@param  array   $options
@return bool

public function check($value, $hashedValue, array $options = array()) {

        return strtoupper($this->make($value)) === strtoupper($hashedValue);
    }

public function getParameterValue($name)
    {
        return (isset($this->attributes[$name])) ? $this->attributes[$name] : null;
    }

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


Question: Make all lines 80 chars and ending with CRLF (except the last)

public static function normalize(PyStringNode $node): string
    {
        return rtrim(
            array_reduce($node->getStrings(), function ($carry, $string) {
                return $carry . str_pad(rtrim($string), 80) . "\r\n";
            }),
            "\r\n"
        );
    }

@Override
    public int doEndTag() throws JspException {

        if (m_firstOnPage || m_manualPlacement) {
            // only execute action for the first "editable" tag on the page (include file), or in manual mode
            editableTagAction(pageContext, m_provider, m_mode, m_file);
        }
        if (OpenCms.getSystemInfo().getServletContainerSettings().isReleaseTagsAfterEnd()) {
            // need to release manually, JSP container may not call release as required (happens with Tomcat)
            release();
        }

        return EVAL_PAGE;
    }

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


Question:
Call after headers or columns with no attributes (table.headers)
 Create all the cells based on each column in the model's database table
 Create cell's actions based on option default_actions or on actions given (:actions => [:edit])

def create_cells
      @attributes.each { |ask| add_cell(@object, format_options_to_cell(ask)) }
      if @args.empty?
        TableBuilder.default_actions.each { |action| add_cell(@object, action, :action) }
      else
        get_column_actions.each { |action| add_cell(@object, action, :action) }
      end
    end

public function create()
	{
		$view = $this->addViewData( $this->getView() );
		$siteid = $this->getContext()->getLocale()->getSiteId();
		$data = $view->param( 'stock', [] );

		foreach( $view->value( $data, 'stock.id', [] ) as $idx => $value ) {
			$data['stock.siteid'][$idx] = $siteid;
		}

		$view->stockData = $data;
		$view->stockBody = '';

		foreach( $this->getSubClients() as $client ) {
			$view->stockBody .= $client->create();
		}

		return $this->render( $view );
	}

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


Question:
Generate an Excel BIFF XF record (style or cell).

@return string The XF record

function writeXf()
	{
		// Set the type of the XF record and some of the attributes.
		if ($this->_isStyleXf) {
			$style = 0xFFF5;
		} else {
			$style   = self::_mapLocked($this->_style->getProtection()->getLocked());
			$style  |= self::_mapHidden($this->_style->getProtection()->getHidden()) << 1;
		}

		// Flags to indicate if attributes have been set.
		$atr_num     = ($this->_numberFormatIndex != 0)?1:0;
		$atr_fnt     = ($this->_fontIndex != 0)?1:0;
		$atr_alc     = ((int) $this->_style->getAlignment()->getWrapText())?1:0;
		$atr_bdr     = (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle())   ||
						self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle())      ||
						self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle())     ||
						self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0;
		$atr_pat     = (($this->_fg_color != 0x40) ||
						($this->_bg_color != 0x41) ||
						self::_mapFillType($this->_style->getFill()->getFillType()))?1:0;
		$atr_prot    = self::_mapLocked($this->_style->getProtection()->getLocked())
						| self::_mapHidden($this->_style->getProtection()->getHidden());

		// Zero the default border colour if the border has not been set.
		if (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
			$this->_bottom_color = 0;
		}
		if (self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle())  == 0) {
			$this->_top_color = 0;
		}
		if (self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
			$this->_right_color = 0;
		}
		if (self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
			$this->_left_color = 0;
		}
		if (self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
			$this->_diag_color = 0;
		}

		$record         = 0x00E0;              // Record identifier
		$length         = 0x0014;              // Number of bytes to follow

		$ifnt           = $this->_fontIndex;   // Index to FONT record
		$ifmt           = $this->_numberFormatIndex;  // Index to FORMAT record

		$align          = $this->_mapHAlign($this->_style->getAlignment()->getHorizontal());       // Alignment
		$align         |= (int) $this->_style->getAlignment()->getWrapText()     << 3;
		$align         |= self::_mapVAlign($this->_style->getAlignment()->getVertical())  << 4;
		$align         |= $this->_text_justlast << 7;

		$used_attrib    = $atr_num              << 2;
		$used_attrib   |= $atr_fnt              << 3;
		$used_attrib   |= $atr_alc              << 4;
		$used_attrib   |= $atr_bdr              << 5;
		$used_attrib   |= $atr_pat              << 6;
		$used_attrib   |= $atr_prot             << 7;

		$icv            = $this->_fg_color;      // fg and bg pattern colors
		$icv           |= $this->_bg_color      << 7;

		$border1        = self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle());          // Border line style and color
		$border1       |= self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle())         << 4;
		$border1       |= self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle())           << 8;
		$border1       |= self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle())        << 12;
		$border1       |= $this->_left_color    << 16;
		$border1       |= $this->_right_color   << 23;

		$diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
		$diag_tl_to_rb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
							|| $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_DOWN;
		$diag_tr_to_lb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH
							|| $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_UP;
		$border1       |= $diag_tl_to_rb        << 30;
		$border1       |= $diag_tr_to_lb        << 31;

		$border2        = $this->_top_color;    // Border color
		$border2       |= $this->_bottom_color   << 7;
		$border2       |= $this->_diag_color     << 14;
		$border2       |= self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle())           << 21;
		$border2       |= self::_mapFillType($this->_style->getFill()->getFillType())        << 26;

		$header      = pack("vv",       $record, $length);

		//BIFF8 options: identation, shrinkToFit and  text direction
		$biff8_options  = $this->_style->getAlignment()->getIndent();
		$biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;

		$data  = pack("vvvC", $ifnt, $ifmt, $style, $align);
		$data .= pack("CCC"
			, self::_mapTextRotation($this->_style->getAlignment()->getTextRotation())
			, $biff8_options
			, $used_attrib
			);
		$data .= pack("VVv", $border1, $border2, $icv);

		return($header . $data);
	}

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:
Constructs an API URL.

@param string $domain_key
@param string $path

@return string

final protected function generateUrl($domain_key, $path = '/')
    {
        $base_domain = self::$URL_MAP[$domain_key];
        $base_domain = str_replace('{domain}', $this->domain, $base_domain);

        if ($path[0] === '/') {
            $path = substr($path, 1);
        }

        return $base_domain.$path;
    }

func NewProductPrivateHostAPI(client *Client) *ProductPrivateHostAPI {
	return &ProductPrivateHostAPI{
		&baseAPI{
			client: client,
			// FuncGetResourceURL
			FuncGetResourceURL: func() string {
				return "product/privatehost"
			},
		},
	}
}

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


Question:
start auto cycle.
@param delay delay time
@param duration animation duration time.
@param autoRecover if recover after user touches the slider.

public void startAutoCycle(long delay,long duration,boolean autoRecover){
        if(mCycleTimer != null) mCycleTimer.cancel();
        if(mCycleTask != null) mCycleTask.cancel();
        if(mResumingTask != null) mResumingTask.cancel();
        if(mResumingTimer != null) mResumingTimer.cancel();
        mSliderDuration = duration;
        mCycleTimer = new Timer();
        mAutoRecover = autoRecover;
        mCycleTask = new TimerTask() {
            @Override
            public void run() {
                mh.sendEmptyMessage(0);
            }
        };
        mCycleTimer.schedule(mCycleTask,delay,mSliderDuration);
        mCycling = true;
        mAutoCycle = true;
    }

function (curve, options, redraw) {
            if (typeof options === "undefined") { options = {}; }
            if (typeof redraw === "undefined") { redraw = false; }
            var screen = this.screen, ctx = this.ctx, prop, opts, path, paths = [], x, y, i, fx, fxold, step = 2 / (screen.scale.x - screen.scale.y), from, to;

            ctx.save();
            ctx.lineWidth = (options.lineWidth || 4) / (screen.scale.x - screen.scale.y);

            // Set the drawing options
            if (options) {
                opts = MathLib.Canvas.convertOptions(options);
                for (prop in opts) {
                    if (opts.hasOwnProperty(prop)) {
                        ctx[prop] = opts[prop];
                    }
                }

                if ('setLineDash' in ctx) {
                    ctx.setLineDash(('dash' in options ? options.dash : []));
                }
                if ('lineDashOffset' in ctx) {
                    ctx.lineDashOffset = ('dashOffset' in options ? options.dashOffset : 0);
                }
            }

            // If curve is a function f, the path will be (x, f(x))
            if (typeof curve === 'function') {
                path = [];
                from = ('from' in options ? (options).from : (-screen.translation.x) / screen.scale.x) - step;
                to = ('to' in options ? (options).to : (screen.width - screen.translation.x) / screen.scale.x) + step;

                for (i = from; i <= to; i += step) {
                    fx = curve(i);

                    // Inline NaN test and disontinuity test
                    // Check if we are drawing a (nearly) vertical line, which should not be there.
                    // i.e the vertical lines at π/2 for the tangent function
                    // TODO: Find a better check if there is a discontinuity.
                    if (fx !== fx || (MathLib.abs((fxold - fx) / step) >= 1e2 && (fx - curve(i - step / 2)) * (fxold - curve(i - step / 2)) >= 0)) {
                        // Don't add empty subpaths
                        if (path.length) {
                            paths.push(path);
                            path = [];
                        }
                    } else {
                        path.push([i, fx]);
                    }

                    fxold = fx;
                }
                if (path.length) {
                    paths.push(path);
                }
            } else if (typeof curve[0] === 'function') {
                path = [];
                x = curve[0];
                y = curve[1];
                from = ('from' in options ? (options).from : 0) - step;
                to = ('to' in options ? (options).to : 2 * Math.PI) + step;
                for (i = from; i <= to; i += step) {
                    path.push([x(i), y(i)]);
                }
                paths.push(path);
            } else {
                path = curve;
            }

            // Draw the path
            // Till now I haven't found a way to stroke and fill the path in one go.
            // The problem is basically, that moveTo creates a new subpath
            // and every subpath is filled on its own.
            if (options.fillColor || options.fillColor !== 'transparent') {
                ctx.beginPath();
                ctx.lineTo(from, 0);
                paths.forEach(function (path) {
                    // The following line (and the line four lines afterwards) fixes the fill at holes in the path.
                    ctx.lineTo(path[0][0], 0);
                    path.forEach(function (x) {
                        ctx.lineTo(x[0], x[1]);
                    });
                    ctx.lineTo(path[path.length - 1][0], 0);
                });
                ctx.fill();
                // ctx.closePath();
            }

            if (options.lineColor || options.lineColor !== 'transparent') {
                ctx.beginPath();
                paths.forEach(function (path) {
                    ctx.moveTo(path[0][0], path[0][1]);
                    path.forEach(function (x) {
                        ctx.lineTo(x[0], x[1]);
                    });
                });
                ctx.stroke();
                // ctx.closePath();
            }

            ctx.restore();

            if (!redraw) {
                if (options.conic) {
                    this.stack.push({
                        type: 'conic',
                        object: options.conic,
                        options: options
                    });
                } else {
                    this.stack.push({
                        type: 'path',
                        object: curve,
                        options: options
                    });
                }
            }

            return this;
        }

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


Question:
Send 401 headers to the browser
@param string message to output as "Basic realm" text/message (default "Login Required")
@param bool true to terminate php after outputting headers (default true)

static function OutputHeaders($realm = "Login Required", $terminate = true)
	{
		header("WWW-Authenticate: Basic realm=\"".$realm."\"");
		header("Status: 401 Unauthorized");
		header("HTTP-Status: 401 Unauthorized");
		if ($terminate) die();
	}

static public function httpPost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, self::_buildPost($data));
        list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl));
        return (intval($status["http_code"]) === 200) ? $content : false;
    }

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


Question:
Delete an object

@param string $bucket Bucket name
@param string $uri Object URI
@return boolean

public static function deleteObject($bucket, $uri)
	{
		$rest = new S3Request('DELETE', $bucket, $uri, self::$endpoint);
		$rest = $rest->getResponse();
		if ($rest->error === false && $rest->code !== 204)
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		if ($rest->error !== false)
		{
			self::__triggerError(sprintf("S3::deleteObject(): [%s] %s",
			$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
			return false;
		}
		return true;
	}

func (s *Service) ListBucketsRequest(input *ListBucketsInput) (*request.Request, *ListBucketsOutput, error) {

	if input == nil {
		input = &ListBucketsInput{}
	}

	o := &data.Operation{
		Config:        s.Config,
		APIName:       "Get Service",
		RequestMethod: "GET",
		RequestURI:    "/",
		StatusCodes: []int{
			200, // OK
		},
	}

	x := &ListBucketsOutput{}
	r, err := request.New(o, input, x)
	if err != nil {
		return nil, nil, err
	}

	return r, x, nil
}

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


Question:
Binds parameters to a PDO statement.

@param \PDOStatement $statement PDO statement
@param array $values Parameters. The indexes are the names or numbers of the values.
@throws InvalidArgumentException
@throws BasePDOException

protected function bindValues(\PDOStatement $statement, array $values)
    {
        $number = 1;

        foreach ($values as $name => $value) {
            $this->bindValue($statement, is_string($name) ? $name : $number, $value);
            $number += 1;
        }
    }

protected function buildSql()
    {
        $query = $this->getQuery();
        if (
            !isset($query['table']) || empty($query['table'])
            || !isset($query['columns']) || empty($query['columns'])
        ) {
            throw new Exception(str_cover('"{type}"查询参数不完整', [
                '{type}' => 'insert'
            ]), 101300301);
        }
        $KS = $VS = [];
        foreach ($query['columns'] as $k => $v) {
            if ($v instanceof Expression) {
                $KS[] = $this->quoteColumnName($k);
                $VS[] = $v->expression;
                continue;
            }
            $KS[] = $this->quoteColumnName($k);
            $VS[] = $bk = $this->getBindKey();
            $this->addParam($bk, $v);
        }
        $sql = 'INSERT INTO '
            . $this->quoteTableName($query['table'])
            . ' (' . implode(',', $KS) . ') VALUES (' . implode(',', $VS) . ')';
        return $sql;
    }

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


Question: write map with simple keys

private Object writeMapSimple(SerIterator itemIterator) {
        Map<String, Object> result = new LinkedHashMap<>();
        StringConverter<Object> keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
        while (itemIterator.hasNext()) {
            itemIterator.next();
            Object key = itemIterator.key();
            if (key == null) {
                throw new IllegalArgumentException("Unable to write map key as it cannot be null");
            }
            String str = keyConverter.convertToString(itemIterator.key());
            if (str == null) {
                throw new IllegalArgumentException("Unable to write map key as it cannot be a null string");
            }
            result.put(str, writeObject(itemIterator.valueType(), itemIterator.value(), itemIterator));
        }
        return result;
    }

private HashMap<String, DBIDs> multipleAssignment(Relation<?> data) {
    HashMap<String, DBIDs> labelMap = new HashMap<>();

    for(DBIDIter iditer = data.iterDBIDs(); iditer.valid(); iditer.advance()) {
      String[] labels = data.get(iditer).toString().split(" ");
      for(String label : labels) {
        assign(labelMap, label, iditer);
      }
    }
    return labelMap;
  }

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


Question: // SetKmsKeyId sets the KmsKeyId field's value.

func (s *EncryptionAtRestOptions) SetKmsKeyId(v string) *EncryptionAtRestOptions {
	s.KmsKeyId = &v
	return s
}

func (c *ClientsetSecretStore) createSecret(s *fi.Secret, name string, replace bool) (*kops.Keyset, error) {
	keyset := &kops.Keyset{}
	keyset.Name = NamePrefix + name
	keyset.Spec.Type = kops.SecretTypeSecret

	t := time.Now().UnixNano()
	id := pki.BuildPKISerial(t)

	keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
		Id:              id.String(),
		PrivateMaterial: s.Data,
	})

	if replace {
		return c.clientset.Keysets(c.namespace).Update(keyset)
	}
	return c.clientset.Keysets(c.namespace).Create(keyset)
}

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


Question: Executes the specified namespace aware XPath query as a multiple node query, returning the resulting list of nodes.

@SuppressWarnings("unchecked")
    public static List<Node> selectNodes(Node node, String xpathQuery, Map<String, String> namespaceUris) {
        XPath xpath = DocumentHelper.createXPath(xpathQuery);
        xpath.setNamespaceURIs(namespaceUris);

        return xpath.selectNodes(node);
    }

protected static function createReplacementNode(DOMDocument $dom, array $replacement)
	{
		if ($replacement[0] === 'expression')
		{
			$newNode = $dom->createElementNS(self::XMLNS_XSL, 'xsl:value-of');
			$newNode->setAttribute('select', $replacement[1]);
		}
		elseif ($replacement[0] === 'passthrough')
		{
			$newNode = $dom->createElementNS(self::XMLNS_XSL, 'xsl:apply-templates');
			if (isset($replacement[1]))
			{
				$newNode->setAttribute('select', $replacement[1]);
			}
		}
		else
		{
			$newNode = $dom->createTextNode($replacement[1]);
		}

		return $newNode;
	}

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


Question:
Sets up service providers for the given component

        :param component_context: The ComponentContext bean
        :param instance: The component instance
        :return: The list of handlers associated to the given component

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


Question:
Delete all films from specified sender.

@param sender Sender which films are to be deleted.

public synchronized void deleteAllFilms(String sender) {
        removeIf(film -> film.arr[DatenFilm.FILM_SENDER].equalsIgnoreCase(sender));
    }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
Shortcut for creating a new resource
        :return: The newly created resource as a Resource object

def create_resource(self, url, data):

        status_code, json_data = self.send_request(url, data, method='POST')

        if status_code != 201:
            msg = 'Expected 201 status code, got %s. Failed to create resource.'
            raise TagCubeAPIException(msg % status_code)

        try:
            return Resource(json_data)
        except KeyError:
            # Parse the error and raise an exception, errors look like:
            # {u'error': [u'The domain foo.com already exists.']}
            error_string = u' '.join(json_data['error'])
            raise TagCubeAPIException(error_string)

private void registerChildInternal(IgnoreDomainResourceTypeResource child) {
        child.setParent(this);
        children.put(child.getName(), child);
    }

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


Question:
@abstract   Create a new block with default parameters

@param      string      $blockType       Standard Widget Block Type
@param      array       $blockOptions    Block Options

@return     $this

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
Gets the table column with the supplied key.

@param mixed $columnKey

@return TableDataColumn
@throws InvalidArgumentException
@throws TypeMismatchException

public function getColumn($columnKey) : TableDataColumn
    {
        $this->validateColumnKey(__METHOD__, $columnKey);
        $this->loadColumns();

        $columnHash = ValueHasher::hash($columnKey);

        if (!isset($this->columns[$columnHash])) {
            throw InvalidArgumentException::format(
                'Invalid column key supplied to %s: expecting one of hashes (%s), value with \'%s\' hash given',
                __METHOD__, Debug::formatValues(array_keys($this->columns)), $columnHash
            );
        }

        return $this->columns[$columnHash];
    }

public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }

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


Question:
Convert type if possible
@param old The old type
@return The new type; otherwise null

private Class<?> convertType(Class<?> old)
   {
      if (Boolean.class.equals(old))
      {
         return boolean.class;
      }
      else if (boolean.class.equals(old))
      {
         return Boolean.class;
      }
      else if (Byte.class.equals(old))
      {
         return byte.class;
      }
      else if (byte.class.equals(old))
      {
         return Byte.class;
      }
      else if (Short.class.equals(old))
      {
         return short.class;
      }
      else if (short.class.equals(old))
      {
         return Short.class;
      }
      else if (Integer.class.equals(old))
      {
         return int.class;
      }
      else if (int.class.equals(old))
      {
         return Integer.class;
      }
      else if (Long.class.equals(old))
      {
         return long.class;
      }
      else if (long.class.equals(old))
      {
         return Long.class;
      }
      else if (Float.class.equals(old))
      {
         return float.class;
      }
      else if (float.class.equals(old))
      {
         return Float.class;
      }
      else if (Double.class.equals(old))
      {
         return double.class;
      }
      else if (double.class.equals(old))
      {
         return Double.class;
      }
      else if (Character.class.equals(old))
      {
         return char.class;
      }
      else if (char.class.equals(old))
      {
         return Character.class;
      }

      return null;
   }

public static Short checkNull(Short value, short elseValue) {
        return checkNull(value, Short.valueOf(elseValue));
    }

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


Question:
// sendKeepAliveWithTimeout sends a keepalive@openssh.com message to the remote
// client. A manual timeout is needed here because SendRequest will wait for a
// response forever.

func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool {
	errorCh := make(chan error, 1)

	go func() {
		// SendRequest will unblock when connection or channel is closed.
		_, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil)
		errorCh <- err
	}()

	select {
	case err := <-errorCh:
		if err != nil {
			return false
		}
		return true
	case <-time.After(timeout):
		return false
	case <-closeContext.Done():
		return false
	}
}

def execute(self, command):

        try:
            if self.ssh.get_transport() is not None:
                logger.debug('{0}: executing "{1}"'.format(self.target_address,
                                                           command))
                stdin, stdout, stderr = self.ssh.exec_command(command)
                return dict(zip(['stdin', 'stdout', 'stderr'],
                                [stdin, stdout, stderr]))
            else:
                raise SSHConnectionError(self.target_address,
                                         "ssh transport is closed")
        except (AuthenticationException, SSHException,
                ChannelException, SocketError) as ex:
            logger.critical(("{0} execution failed on {1} with exception:"
                             "{2}".format(command, self.target_address,
                                               ex)))
            raise SSHCommandError(self.target_address, command, ex)

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


Question:
Check if a given request has access to delete a post.

@param  WP_REST_Request $request Full details about the request.
@return bool|WP_Error

public function delete_item_permissions_check( $request ) {

		$post = $this->get_post( $request['id'] );

		if ( $post && ! $this->check_delete_permission( $post ) ) {
			return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete posts.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		return true;
	}

def get(args):

    html = args.H
    lang = args.l
    nowrap = args.n
    query = args.q
    silent = args.s
    title = args.t
    verbose = args.v
    wiki = args.w

    if query:
        qobj = WPToolsQuery(lang=lang, wiki=wiki)
        if title:
            return qobj.query(title)
        return qobj.random()

    page = wptools.page(title, lang=lang, silent=silent,
                        verbose=verbose, wiki=wiki)

    try:
        page.get_query()
    except (StandardError, ValueError, LookupError):
        return "NOT_FOUND"

    if not page.data.get('extext'):
        out = page.cache['query']['query']

    out = _page_text(page, nowrap)
    if html:
        out = _page_html(page)

    try:
        return out.encode('utf-8')
    except KeyError:
        return out

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


Question: Set system attribute and do some initialization. Used by System.

def setup_system(self, system, name_from_system='', **kwargs):

        if not self.system:
            self.system = system
        name, traits = self._passed_arguments
        new_name = self.system.get_unique_name(self, name, name_from_system)
        if not self in self.system.reverse:
            self.name = new_name
        self.logger = self.system.logger.getChild('%s.%s' % (self.__class__.__name__, self.name))
        self.logger.setLevel(self.log_level)
        if name is None and 'name' in traits:  # Only __setstate__ sets name to None. Default is ''.
            del traits['name']

        for cname in self.callables:
            if cname in traits:
                c = self._postponed_callables[cname] = traits.pop(cname)
                c.setup_callable_system(self.system)
            getattr(self, cname).setup_callable_system(self.system)

        if not self.traits_inited():
            super().__init__(**traits)
        self.name_changed_event = True
        self.setup()

def _init_metadata(self, **kwargs):
        """"""
        osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
        self._rubric_default = self._mdata['rubric']['default_id_values'][0]
        self._level_default = self._mdata['level']['default_id_values'][0]

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


Question:
Method to update a comment on a gist.

@param   integer  $commentId  The id of the comment to update.
@param   string   $body       The new body text for the comment.

@throws \DomainException
@since  1.0

@return  object

public function edit($commentId, $body)
	{
		// Build the request path.
		$path = '/gists/comments/' . (int) $commentId;

		// Build the request data.
		$data = json_encode(
			array(
				'body' => $body
			)
		);

		// Send the request.
		$response = $this->client->patch($this->fetchUrl($path), $data);

		// Validate the response code.
		if ($response->code != 200)
		{
			// Decode the error response and throw an exception.
			$error = json_decode($response->body);
			throw new \DomainException($error->message, $response->code);
		}

		return json_decode($response->body);
	}

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup

        data = {}
        data['game_short_name'] = u(array.get('game_short_name'))
        if array.get('chat_id') is None:
            data['receiver'] = None
        elif isinstance(array.get('chat_id'), None):
            data['receiver'] = None(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), str):
            data['receiver'] = u(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), int):
            data['receiver'] = int(array.get('chat_id'))
        else:
            raise TypeError('Unknown type, must be one of None, str, int or None.')
        # end if
        if array.get('reply_to_message_id') is None:
            data['reply_id'] = None
        elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID):
            data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id'))
        elif isinstance(array.get('reply_to_message_id'), int):
            data['reply_id'] = int(array.get('reply_to_message_id'))
        else:
            raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.')
        # end if
        data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None
        data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None
        return GameMessage(**data)

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


Question:
// storageHealthCheck returns a channel that will close when the distributed
// storage is no longer accessible (i.e., stale NFS mount)

func (c *Controller) storageHealthCheck() (chan struct{}, error) {
	gone := make(chan struct{})
	mounts, err := mount.GetMounts()
	if err != nil {
		return nil, err
	}
	nfsMountPoints := []string{}
	for _, minfo := range mounts {
		if strings.HasPrefix(minfo.Fstype, "nfs") {
			nfsMountPoints = append(nfsMountPoints, minfo.Mountpoint)
		}
	}
	if len(nfsMountPoints) > 0 {
		// Start polling
		go func() {
			for {
				for _, mp := range nfsMountPoints {
					if utils.IsNFSMountStale(mp) {
						close(gone)
						return
					}
				}
				<-time.After(5 * time.Second)
			}
		}()
	}
	return gone, nil
}

def _maybe_connect(self, node_id):
        """"""
        with self._lock:
            conn = self._conns.get(node_id)

            if conn is None:
                broker = self.cluster.broker_metadata(node_id)
                assert broker, 'Broker id %s not in current metadata' % (node_id,)

                log.debug("Initiating connection to node %s at %s:%s",
                          node_id, broker.host, broker.port)
                host, port, afi = get_ip_port_afi(broker.host)
                cb = WeakMethod(self._conn_state_change)
                conn = BrokerConnection(host, broker.port, afi,
                                        state_change_callback=cb,
                                        node_id=node_id,
                                        **self.config)
                self._conns[node_id] = conn

            # Check if existing connection should be recreated because host/port changed
            elif self._should_recycle_connection(conn):
                self._conns.pop(node_id)
                return False

            elif conn.connected():
                return True

            conn.connect()
            return conn.connected()

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


Question: Returns with a view of all scopes known by this manager.

public List<List<String>> getAllScopes() {
    this.checkInitialized();
    final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();
    final Consumer<Integer> _function = (Integer it) -> {
      List<String> _get = this.scopes.get(it);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("No scopes are available for index: ");
      _builder.append(it);
      builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));
    };
    this.scopes.keySet().forEach(_function);
    return builder.build();
  }

private function sitemapRecords(Tree $tree, string $type, int $limit, int $offset): Collection
    {
        switch ($type) {
            case 'i':
                $records = $this->sitemapIndividuals($tree, $limit, $offset);
                break;

            case 'm':
                $records = $this->sitemapMedia($tree, $limit, $offset);
                break;

            case 'n':
                $records = $this->sitemapNotes($tree, $limit, $offset);
                break;

            case 'r':
                $records = $this->sitemapRepositories($tree, $limit, $offset);
                break;

            case 's':
                $records = $this->sitemapSources($tree, $limit, $offset);
                break;

            default:
                throw new NotFoundHttpException('Invalid record type: ' . $type);
        }

        // Skip private records.
        $records = $records->filter(GedcomRecord::accessFilter());

        return $records;
    }

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


Question:
Build the diagnostic message.

Examples:

Non-exhaustive switch, expected cases for: FOO

Non-exhaustive switch, expected cases for: FOO, BAR, BAZ, and 42 others.

private String buildMessage(Set<String> unhandled) {
    StringBuilder message =
        new StringBuilder(
            "Non-exhaustive switch; either add a default or handle the remaining cases: ");
    int numberToShow =
        unhandled.size() > MAX_CASES_TO_PRINT
            ? 3 // if there are too many to print, only show three examples.
            : unhandled.size();
    message.append(unhandled.stream().limit(numberToShow).collect(Collectors.joining(", ")));
    if (numberToShow < unhandled.size()) {
      message.append(String.format(", and %d others", unhandled.size() - numberToShow));
    }
    return message.toString();
  }

@Nonnull
  public BootstrapSpacingBuilder side (@Nonnull final EBootstrapSpacingSideType eSide)
  {
    ValueEnforcer.notNull (eSide, "Side");
    m_eSide = eSide;
    return this;
  }

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


Question:
@param        $rsp
@param        $txnType
@param string $returnType

@return \HpsGiftCardAlias

public static function fromDict($rsp, $txnType, $returnType = 'HpsGiftCardAlias')
    {
        $item = $rsp->Transaction->$txnType;

        $alias = new HpsGiftCardAlias();
        $alias->transactionId = (string)$rsp->Header->GatewayTxnId;
        $alias->giftCard = new HpsGiftCard($item->CardData);
        $alias->responseCode = (isset($item->RspCode) ? (string)$item->RspCode : null);
        $alias->responseText = (isset($item->RspText) ? (string)$item->RspText : null);

        return $alias;
    }

def role_create(role, principal, endpoint_id):

    principal_type, principal_val = principal

    client = get_client()

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

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

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

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


Question:
Arg section or key is allowed to be empty.

@see SectionedConfigInterface::set()

@inheritdoc

public function set(string $section, string $key, $value) : bool
    {
        return $this->config->set($this->concat($section, $key), $value);
    }

protected function loadSettings() {
		$folder = realpath(__DIR__);
		$segments = explode('/', $folder);
		$file = NULL;
		while (NULL === $file && 0 < count($segments) && ($segment = array_pop($segments))) {
			$base = '/' . implode('/', $segments) . '/' . $segment . '/';
			$expectedFile = $base . $this->settingsFile;
			$expectedFile = FALSE === file_exists($expectedFile) ? $base . 'Settings.yml' : $expectedFile;
			$file = TRUE === file_exists($expectedFile) ? $expectedFile : NULL;
		}
		return (array) (TRUE === file_exists($file) ? Yaml::parse(file_get_contents($file)) : array());
	}

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


Question: Extracts the first value.

protected final Object getValueFromResultSet( ResultSet pResultSet ) throws SQLException
  {
    if( !pResultSet.next() )
    {
      if( _returnNullInsteadOfNoDataFoundException )
      {
        return null;
      }

      throw new NoDataFoundException();
    }

    return pResultSet.getObject( getObjectIndex() );
  }

def get_first_model_with_rest_name(cls, rest_name):

        models = cls.get_models_with_rest_name(rest_name)

        if len(models) > 0:
            return models[0]

        return None

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


Question:
Exports a [SurfaceEllipse]{@link SurfaceEllipse} in GeoJSON format of type Polygon.
@param {SurfaceEllipse} renderable The SurfaceEllipse object.
@throws {ArgumentError} If the specified argument is null or undefined.
@returns {String} GeoJSON format.

function (renderable) {
                if (!(renderable instanceof WorldWind.SurfaceEllipse)) {
                    throw new ArgumentError(
                        Logger.logMessage(Logger.LEVEL_SEVERE, "GeoJSONExporter", "exportSurfaceEllipse",
                            "invalidTypeOfRenderable"));
                }

                var sb = '{';
                sb = sb + '"' + GeoJSONConstants.FIELD_TYPE + '":"' + GeoJSONConstants.TYPE_POLYGON + '",';
                sb = sb + '"' + GeoJSONConstants.FIELD_COORDINATES + '":[';
                sb = sb + '[';
                for (var i = 0; i < renderable._boundaries.length; i++) {
                    sb = sb + '[' + renderable._boundaries[i].longitude + ',' +
                        renderable._boundaries[i].latitude + ']';
                    sb = sb + ',';

                    if (i === renderable._boundaries.length - 1) {
                        sb = sb + '[' + renderable._boundaries[0].longitude + ',' +
                            renderable._boundaries[0].latitude + ']';
                    }
                }
                sb = sb + ']';
                sb = sb + ']';
                sb = sb + '}';
                return sb;
            }

public function mapToGoogle(Entity $obj_gds_entity, \google\appengine\datastore\v4\Entity $obj_entity)
    {
        // Key
        $this->configureGoogleKey($obj_entity->mutableKey(), $obj_gds_entity);

        // Properties
        $arr_field_defs = $this->obj_schema->getProperties();
        foreach($obj_gds_entity->getData() as $str_field_name => $mix_value) {
            $obj_prop = $obj_entity->addProperty();
            $obj_prop->setName($str_field_name);
            $obj_val = $obj_prop->mutableValue();
            if(isset($arr_field_defs[$str_field_name])) {
                $this->configureGooglePropertyValue($obj_val, $arr_field_defs[$str_field_name], $mix_value);
            } else {
                $arr_dynamic_data = $this->determineDynamicType($mix_value);
                $this->configureGooglePropertyValue($obj_val, ['type' => $arr_dynamic_data['type'], 'index' => TRUE], $arr_dynamic_data['value']);
            }
        }
    }

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


Question:
add a value to the aggregator

@param val
an object.

public void addNextValue(Object val) {
    if (this.numItems <= this.maxNumItems) {
      uniqItems.put(val.toString(), "1");
      this.numItems = this.uniqItems.size();
    }
  }

protected Parameter[] createDefaultParameters(Class[] parameters) {
		Parameter[] componentParameters = new Parameter[parameters.length];
		for (int i = 0; i < parameters.length; i++) {
			componentParameters[i] = ComponentParameter.DEFAULT;
		}
		return componentParameters;
	}

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


Question:
Convenience method equivalent to
        ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])``

def getattr(self, name, default: Any = _missing):

        return deep_getattr(self.clsdict, self.bases, name, default)

func (s *DB) Attrs(attrs ...interface{}) *DB {
	return s.clone().search.Attrs(attrs...).db
}

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


Question: // MonthWide returns the locales wide month given the 'month' provided

func (is *is) MonthWide(month time.Month) string {
	return is.monthsWide[month]
}

static public function create($params, LocatorInterface $locator = null) {
		if (! is_array($params) && ! $params instanceof Traversable) {
			throw new InvalidOptions('Options must be an array or a Traversable implementation');
		}

		if ($params instanceof Traversable) {
			$params = Std::iteratorToArray($params);
		}

		$translator = new Translator();

		foreach ($params as $param => $value) {
			if ($param === 'cacheStrategy') {
				$class = self::NAMESPACE_CACHE . '\Strategy' . ucfirst($value);

				$translator->setCache(new $class($locator));
				unset($params[$param]);
				continue;
			}

			if ($param === 'resources') {
				if (! is_array($value) && ! $value instanceof Traversable) {
					throw new InvalidOptions('Resources definition must be an array or a Traversable implementation');
				}

				$translator->setResources(self::createResources($value));
				unset($params[$param]);
				continue;
			}

			if ($param === 'bbcodes') {
				if ($value) {
					$bbcodes = new BBCodes();

					if (isset($params['paramsPattern'])) {
						$bbcodes->setParamsPattern($params['paramsPattern']);
					}

					$translator->addPlugin($bbcodes, 'bbcodes');
				}

				unset($params[$param]);
			}
		}

		$translator->setOptions($params, false, false);

		return $translator;
	}

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


Question:
Retrieves a previously registered hook.

@param {string} className The name of the class to get the hook on.
@param {string} hookType One of 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete'

function getHook(className, hookType) {
  if (hooks[className] && hooks[className][hookType]) {
    return hooks[className][hookType];
  }
  return undefined;
}

public function set($id, $value)
    {
        $id = (string) $id;

        $this->validateSet($id);

        if ($type = $this->isDefined($id)) {
            if ($type[0] == ':') {
                $type = substr($type, 1);
                $actualType = $this->getType($value);
                if ($actualType != $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be of type %s, but %s given.', $id, $this->name, $type, $actualType));
                }
            } else {
                if (!$value instanceof $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be an instance of %s class, but %s given.', $id, $this->name, $type, $this->getType($value)));
                }
            }
        }

        $this->items[$id] = $value;
    }

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


Question:
Internal function to return all the collections for every database.
        include a list of db_names to filter the list of collections.

def _get_collections(self, db_names=None):

        if db_names:
            db_list = db_names
        else:
            db_list = self.client.list_database_names()

        for db_name in db_list:
            db = self.client.get_database(db_name)
            for col_name in db.list_collection_names():
                size = db[col_name].g
                yield f"{db_name}.{col_name}"

func readDataSet(endpoint, query string, args ...interface{}) ([]map[string]string, error) {
	var inst *Instance
	var exists bool
	if inst, exists = connectionPool[endpoint]; !exists {
		return nil, errNotRegistered
	}
	var err error
	var result *sql.Rows
	var columnName []string
	if result, err = inst.connection.Query(query, args...); err != nil {
		return nil, err
	}
	defer result.Close()
	if columnName, err = result.Columns(); err != nil {
		return nil, err
	}
	columnCount := len(columnName)
	columnValue := make([]interface{}, columnCount)
	var dataset []map[string]string
	for result.Next() {
		for i := 0; i < columnCount; i++ {
			columnValue[i] = new([]byte)
		}
		if err = result.Scan(columnValue...); err != nil {
			return nil, err
		}
		row := make(map[string]string)
		for i := 0; i < columnCount; i++ {
			row[columnName[i]] = string(*columnValue[i].(*[]byte))
		}
		dataset = append(dataset, row)
	}
	return dataset, nil
}

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


Question: Portal email name

def email_from_name(self):

        lab_from_name = self.laboratory.getName()
        portal_from_name = self.portal.email_from_name
        return lab_from_name or portal_from_name

func (s *CreateCaseInput) SetCcEmailAddresses(v []*string) *CreateCaseInput {
	s.CcEmailAddresses = v
	return s
}

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


Question:
Create a new Message from this FetchActions.

@return \AlphaRPC\Common\Socket\Message

public function toMessage()
    {
        $msg = parent::createMessage();
        $msg->append(array(count($this->actions)));
        $msg->append($this->actions);

        return $msg;
    }

function sendMessage (client, data, batchCallback) {
  var msg = data.msg;
  var offset = data.offset;
  var length = data.length;
  var port = data.port;
  var address = data.address;
  var callback = data.callback;

  client.send(msg, offset, length, port, address, function(err) {
    try {
      callback(err);
    } finally {
      batchCallback();
    }
  });
}

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