Question:
Find a default browser to use.

@return string|false

protected function getDefaultBrowser()
    {
        $potential = array('xdg-open', 'open', 'start');
        /** @var \Symfony\Component\Console\Helper\ProcessHelper $process */
        $process = $this->getHelper('process');
        foreach ($potential as $browser) {
            // Check if command exists by executing help flag.

            if ($process->run($this->stdOut, "command -v $browser")->isSuccessful()) {
                return $browser;
            }
        }
        return false;
    }

function assertLoadedUrlEqual(controller, targetUrl) {
  var locationBar = new elementslib.ID(controller.window.document, "urlbar");
  var currentURL = locationBar.getNode().value;

  // Load the target URL
  controller.open(targetUrl);
  controller.waitForPageLoad();

  // Check the same web page has been opened
  controller.waitForEval("subject.targetURL.value == subject.currentURL", gTimeout, 100,
                         {targetURL: locationBar.getNode(),  currentURL: currentURL});
}

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


Question: // set the request body as an io.Reader

func Body(r io.Reader) RequestOption {
	return func(req *http.Request) (*http.Request, error) {
		if r == nil {
			req.Body = http.NoBody
			req.ContentLength = 0
			return req, nil
		}

		if rc, ok := r.(io.ReadCloser); ok {
			req.Body = rc
		} else {
			req.Body = ioutil.NopCloser(r)
		}

		if v, ok := r.(interface{ Len() int }); ok {
			req.ContentLength = int64(v.Len())
		} else if v, ok := r.(interface{ Size() int64 }); ok {
			req.ContentLength = v.Size()
		}

		return req, nil
	}
}

def read (self, filename=None):

    if filename is None:
      filename = self.pathname

    stream = open(filename, 'rb')
    magic  = struct.unpack('>H', stream.read(2))[0]
    stream.close()

    if magic == Seq.Magic:
      self.readBinary(filename)
    else:
      self.readText(filename)

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


Question: // SetNextToken sets the NextToken field's value.

func (s *GetTraceSummariesInput) SetNextToken(v string) *GetTraceSummariesInput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
/*
(non-Javadoc)
@see
org.fcrepo.server.security.xacml.pdp.finder.support.RelationshipResolver#getParents(java.
lang.String)

public Set<String> getParents(String pid) throws MelcoeXacmlException {
        logger.debug("Obtaining parents for: {}", pid);

        Set<String> parentPIDs = new HashSet<String>();
        if (pid.equalsIgnoreCase(Constants.FEDORA_REPOSITORY_PID.uri)) {
            return parentPIDs;
        }

        query: for (String relationship : relationships) {
            logger.debug("relationship query: {}, {}", pid, relationship);

            Map<String, Set<String>> mapping;
            try {
                mapping = getRelationships(pid, relationship);
            } catch (MelcoeXacmlException e) {
                Throwable t = e.getCause();
                // An object X, may legitimately declare a parent relation to
                // another object, Y which does not exist. Therefore, we don't
                // want to continue querying for Y's parents.
                if (t != null && t instanceof ObjectNotInLowlevelStorageException) {
                    logger.debug("Parent, {}, not found.", pid);
                    break query;
                } else {
                // Unexpected error, so we throw back the original
                throw e;
            }
            }

            Set<String> parents = mapping.get(relationship);
            if (parents != null) {
                for (String parent : parents) {
                    PID parentPID = PID.getInstance(parent);
                    // we want the parents in demo:123 form, not info:fedora/demo:123
                    parentPIDs.add(parentPID.toString());
                    logger.debug("added parent {}", parentPID.toString());
                }
            }
        }
        return parentPIDs;
    }

public function getChild($tag, $attrs = [])
    {
        $ret = null;
        if ($this->children) {
            if (is_int($tag)) {
                if (isset($this->children[$tag])) {
                    return $this->children[$tag];
                } else {
                    return;
                }
            }
            foreach ($this->children as $child) {
                if (strcmp($child->tag, $tag) == 0) {
                    $found = true;
                    foreach ($attrs as $key => $value) {
                        if (strcmp($child->getAttribute($key), $value) != 0) {
                            $found = false;
                            break;
                        }
                    }
                    if ($found) {
                        return $child;
                    }
                }
                $ret = $child->getChild($tag, $attrs);
                if ($ret) {
                    return $ret;
                }
            }
        }
    }

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


Question:
Detect case condition in switch statement.

@param string $file File name to be analyzed.
@param Node   $node AST node to be analyzed.
@return Hint[] List of hints obtained from results.

public function run(string $file, Node $node): array
    {
        $hints = [];
        $case_conds = [];

        foreach ($node->children as $case) {
            $cond = $case->children['cond'];
            foreach ($case_conds as $case_cond) {
                if ($this->isEqualsWithoutLineno($case_cond, $cond)) {
                    $hints[] = new Hint(
                        self::HINT_TYPE,
                        self::HINT_MESSAGE,
                        $file,
                        $case->lineno,
                        self::HINT_LINK
                    );
                }
            }
            $case_conds[] = $cond;
        }

        return $hints;
    }

func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
	return parseFiles(t, filenames...)
}

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


Question:
Download a device's attachment.

        :param id: Device ID as an int.
        :param attid: Attachment ID as an int.
        :rtype: tuple `(io.BytesIO, 'filename')`

def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin

        resp = self.service.get_id(self._base(id), attid, params={'format': 'download'}, stream=True)
        b = io.BytesIO()
        stream.stream_response_to_file(resp, path=b)
        resp.close()
        b.seek(0)
        return (b, self.service.filename(resp))

function _fillMissingFields(attrs) {
  var attr;
  for(var i = 0; i < attrs.length; ++i) {
    attr = attrs[i];

    // populate missing name
    if(typeof(attr.name) === 'undefined') {
      if(attr.type && attr.type in pki.oids) {
        attr.name = pki.oids[attr.type];
      } else if(attr.shortName && attr.shortName in _shortNames) {
        attr.name = pki.oids[_shortNames[attr.shortName]];
      }
    }

    // populate missing type (OID)
    if(typeof(attr.type) === 'undefined') {
      if(attr.name && attr.name in pki.oids) {
        attr.type = pki.oids[attr.name];
      } else {
        var error = new Error('Attribute type not specified.');
        error.attribute = attr;
        throw error;
      }
    }

    // populate missing shortname
    if(typeof(attr.shortName) === 'undefined') {
      if(attr.name && attr.name in _shortNames) {
        attr.shortName = _shortNames[attr.name];
      }
    }

    if(typeof(attr.value) === 'undefined') {
      var error = new Error('Attribute value not specified.');
      error.attribute = attr;
      throw error;
    }
  }
}

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


Question: // Metadata not implemented

func (a *Driver) Metadata(id string) (map[string]string, error) {
	return nil, nil
}

public function fill_meta($meta_data) {
	foreach ($meta_data as $key => $single_meta_data) {
		$this->add_meta($key, $single_meta_data);
	}
}

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


Question: // FreeCount returns the number of free device instances

func (i *DeviceAccounterInstance) FreeCount() int {
	count := 0
	for _, c := range i.Instances {
		if c == 0 {
			count++
		}
	}
	return count
}

public function count_response($actualresponse, $fraction, $try) {
        if (!isset($this->actualresponses[$actualresponse])) {
            if ($fraction === null) {
                $fraction = $this->fraction;
            }
            $this->add_response($actualresponse, $fraction);
        }
        $this->get_response($actualresponse)->increment_count($try);
    }

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


Question:
Returns the user object for the given username

@access public
@param string $username
@return false|\Zepi\Web\AccessControl\Entity\User

public function getUserForUsername($username)
    {
        if (!$this->accessControlManager->hasAccessEntityForName(self::ACCESS_ENTITY_TYPE, $username)) {
            return false;
        }

        // Get the access entity
        $accessEntity = $this->accessControlManager->getAccessEntityForName(self::ACCESS_ENTITY_TYPE, $username);

        if ($accessEntity === false) {
            return false;
        }

        return $accessEntity;
    }

protected void configureEndpointAccess(final HttpSecurity httpSecurity,
                                           final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests,
                                           final ActuatorEndpointProperties.EndpointAccessLevel access,
                                           final ActuatorEndpointProperties properties,
                                           final EndpointRequest.EndpointRequestMatcher endpoint) throws Exception {
        switch (access) {
            case AUTHORITY:
                configureEndpointAccessByAuthority(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case ROLE:
                configureEndpointAccessByRole(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case AUTHENTICATED:
                configureEndpointAccessAuthenticated(requests, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case IP_ADDRESS:
                configureEndpointAccessByIpAddress(requests, properties, endpoint);
                break;
            case PERMIT:
                configureEndpointAccessPermitAll(requests, endpoint);
                break;
            case ANONYMOUS:
                configureEndpointAccessAnonymously(requests, endpoint);
                break;
            case DENY:
            default:
                configureEndpointAccessToDenyAll(requests, endpoint);
                break;
        }
    }

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


Question:
Is use boolean.

@return the boolean

public boolean isUse() {
        if (!this.use) {
            return this.use;
        }

        return !(this.standardValueType != null && !this.standardValueType.equals(StandardValueType.NONE) && this.standardValue == null);
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
バインドパラメータ配列取得

@return バインドパラメータ配列

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

private static function _doResponse($type, $objects, $echoResponse, $format) {
        $ret = array();
        $ret['status'] = $type;
        if (is_array($objects)) {
            foreach ($objects as $k => $v) {
                $ret[$k] = $v;
            }
        } else {
            $ret[] = $objects;
        }

        switch ($format) {
            case 'xml':
                require_once 'XML/Serializer.php';
                $options = array(
                    "indent" => "    ",
                    "linebreak" => "\n",
                    "typeHints" => false,
                    "addDecl" => true,
                    "encoding" => "UTF-8",
                    "rootName" => "data",
//					"rootAttributes"  => array("version" => "0.91"),
                    "defaultTagName" => "item",
                    "attributesArray" => "_attributes"
                );

                $serializer = new \XML_Serializer($options);

                $rc = $serializer->serialize($ret);
                if ($rc !== TRUE) {

                }
                $ret = $serializer->getSerializedData();
                break;

            case 'json':
            default:
                $ret = json_encode($ret);
                break;
        }

        if ($echoResponse) {
            echo $ret;
        }
        return $ret;
    }

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


Question: Tensor layout conversion helper (y = alpha * x + beta * y)

public static int cudnnTransformTensor(
        cudnnHandle handle,
        Pointer alpha,
        cudnnTensorDescriptor xDesc,
        Pointer x,
        Pointer beta,
        cudnnTensorDescriptor yDesc,
        Pointer y)
    {
        return checkResult(cudnnTransformTensorNative(handle, alpha, xDesc, x, beta, yDesc, y));
    }

def _parse_lightgbm_simple_model(scope, model, inputs):
    '''

    '''
    this_operator = scope.declare_local_operator(_get_lightgbm_operator_name(type(model)), model)
    this_operator.inputs = inputs

    if type(model) in lightgbm_classifier_list:
        # For classifiers, we may have two outputs, one for label and the other one for probabilities of all classes.
        # Notice that their types here are not necessarily correct and they will be fixed in shape inference phase
        label_variable = scope.declare_local_variable('label', FloatTensorType())
        probability_map_variable = scope.declare_local_variable('probabilities', FloatTensorType())
        this_operator.outputs.append(label_variable)
        this_operator.outputs.append(probability_map_variable)
    else:
        # We assume that all scikit-learn operator can only produce a single float tensor.
        variable = scope.declare_local_variable('variable', FloatTensorType())
        this_operator.outputs.append(variable)
    return this_operator.outputs

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


Question:
Add faxes.

@param \Sulu\Bundle\ContactBundle\Entity\Fax $faxes

@return FaxType

public function addFaxe(\Sulu\Bundle\ContactBundle\Entity\Fax $faxes)
    {
        $this->faxes[] = $faxes;

        return $this;
    }

protected final PrcInvoiceGfe<IInvoice> lazyGetPrcInvoiceGfe(
    final Map<String, Object> pAddParam) throws Exception {
    @SuppressWarnings("unchecked")
    PrcInvoiceGfe<IInvoice> proc = (PrcInvoiceGfe<IInvoice>)
      this.processorsMap.get(PrcInvoiceGfe.class.getSimpleName());
    if (proc == null) {
      proc = new PrcInvoiceGfe<IInvoice>();
      @SuppressWarnings("unchecked")
      PrcEntityPbEditDelete<RS, IInvoice> procDlg =
    (PrcEntityPbEditDelete<RS, IInvoice>) this.fctBnEntitiesProcessors
  .lazyGet(pAddParam, PrcEntityPbEditDelete.class.getSimpleName());
      proc.setPrcEntityPbEditDelete(procDlg);
      //assigning fully initialized object:
      this.processorsMap
        .put(PrcInvoiceGfe.class.getSimpleName(), proc);
    }
    return proc;
  }

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


Question:
{@inheritdoc}

@throws OptimisticLockException

public function cancel(OrderInterface $order): void
    {
        $this->lockProductVariants($order);

        $this->decoratedOperator->cancel($order);
    }

def get_fd(self, fd):

        try:
            fd = self.state.solver.eval_one(fd)
        except SimSolverError:
            ideal = self._pick_fd()
            self.state.solver.add(fd == ideal)
            if not self.state.solver.satisfiable():
                raise SimPosixError("Tried to do operation on symbolic but partially constrained file descriptor")
            fd = ideal
            new_filename = b'/tmp/angr_implicit_%d' % self.autotmp_counter
            l.warning("Tried to look up a symbolic fd - constrained to %d and opened %s", ideal, new_filename)
            self.autotmp_counter += 1
            if self.open(new_filename, Flags.O_RDWR, preferred_fd=fd) != fd:
                raise SimPosixError("Something went wrong trying to open implicit temp")

        return self.fd.get(fd)

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


Question:
Create instance of SplFileInfo.

@param string $path

@return SplFileInfo

protected function createSplFileInfoInstance(string $directory, string $filename): SplFileInfo
    {
        return new SplFileInfo($directory.DIRECTORY_SEPARATOR.$filename, $directory, $filename);
    }

public function loadFile($filename)
    {
        $templateDir = Eresus_Kernel::app()->getFsRoot();
        $template = $templateDir . '/' . $filename;
        $this->template = new TemplateFile($template, null, $filename, $filename);
    }

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


Question:
Get OAuth2Client

@return \Kunnu\Dropbox\Authentication\OAuth2Client

public function getOAuth2Client()
    {
        if (!$this->oAuth2Client instanceof OAuth2Client) {
            return new OAuth2Client(
                $this->getApp(),
                $this->getClient(),
                $this->getRandomStringGenerator()
            );
        }

        return $this->oAuth2Client;
    }

def authorize_client_credentials(
        self, client_id, client_secret=None, scope="private_agent"
    ):

        self.auth_data = {
            "grant_type": "client_credentials",
            "scope": [ scope ],
            "client_id": client_id,
            "client_secret": client_secret
        }

        self._do_authorize()

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


Question:
Get possible addresses using latitude/longitude

@param  float $latitude
@param  float $longitude
@return array
@throws Exception

public function getAddresses(float $latitude, float $longitude): ?array
    {
        // init results
        $addresses = [];

        // define result
        $addressSuggestions = $this->doCall(array(
            'latlng' => $latitude . ',' . $longitude,
            'sensor' => 'false'
        ));

        // loop addresses
        foreach ($addressSuggestions as $key => $addressSuggestion) {
            $addresses[$key] = Address::createFromGoogleResult($addressSuggestion);
        }

        return $addresses;
    }

public function forward( $p ) {

        $lon = $p->x;
        $lat = $p->y;

        /* Forward equations
          ----------------- */
        $dlon = Common::adjust_lon( $lon - $this->long0 );
        $x = $this->x0 + $this->a * $dlon;
        $y = $this->y0 + $this->a * log( tan( (Common::PI / 4.0) + ($lat / 2.5) ) ) * 1.25;

        $p->x = $x;
        $p->y = $y;

        return $p;
    }

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


Question: // Running returns true if the driver is in the DRIVER_RUNNING state

func (driver *MesosSchedulerDriver) Running() bool {
	driver.eventLock.RLock()
	defer driver.eventLock.RUnlock()
	return driver.status == mesos.Status_DRIVER_RUNNING
}

def _load_all_link_database(self):
        """"""
        _LOGGER.debug("Starting: _load_all_link_database")
        self.devices.state = 'loading'
        self._get_first_all_link_record()
        _LOGGER.debug("Ending: _load_all_link_database")

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


Question:
// UserAgentHandler adds the request's user-agent as a field to the context's logger
// using fieldKey as field key.

func UserAgentHandler(fieldKey string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if ua := r.Header.Get("User-Agent"); ua != "" {
				log := zerolog.Ctx(r.Context())
				log.UpdateContext(func(c zerolog.Context) zerolog.Context {
					return c.Str(fieldKey, ua)
				})
			}
			next.ServeHTTP(w, r)
		})
	}
}

protected void writeHeader(Meta meta) throws IOException {
        addTabs(2);
        writeStart(HtmlTags.META);
        switch(meta.type()) {
            case Element.HEADER:
                write(HtmlTags.NAME, ((Header) meta).getName());
                break;
            case Element.SUBJECT:
                write(HtmlTags.NAME, HtmlTags.SUBJECT);
                break;
            case Element.KEYWORDS:
                write(HtmlTags.NAME, HtmlTags.KEYWORDS);
                break;
            case Element.AUTHOR:
                write(HtmlTags.NAME, HtmlTags.AUTHOR);
                break;
        }
        write(HtmlTags.CONTENT, HtmlEncoder.encode(meta.getContent()));
        writeEnd();
    }

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


Question:
// Draw draws the Sprite onto the provided Target. The Sprite will be transformed by the given Matrix.
//
// This method is equivalent to calling DrawColorMask with nil color mask.

func (s *Sprite) Draw(t Target, matrix Matrix) {
	s.DrawColorMask(t, matrix, nil)
}

def _read_color_and_depth_image(self):

        frames = self._pipe.wait_for_frames()
        if self._depth_align:
            frames = self._align.process(frames)

        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()

        if not depth_frame or not color_frame:
            logging.warning('Could not retrieve frames.')
            return None, None

        if self._filter_depth:
            depth_frame = self._filter_depth_frame(depth_frame)

        # convert to numpy arrays
        depth_image = self._to_numpy(depth_frame, np.float32)
        color_image = self._to_numpy(color_frame, np.uint8)

        # convert depth to meters
        depth_image *= self._depth_scale

        # bgr to rgb
        color_image = color_image[..., ::-1]

        depth = DepthImage(depth_image, frame=self._frame)
        color = ColorImage(color_image, frame=self._frame)
        return color, depth

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


Question: // getBuf gets a chunk from reuse pool or creates a new one if reuse failed.

func getBuf(size int) []byte {
	if size < config.PooledSize {
		return make([]byte, 0, size)
	}

	if c := buffers[size]; c != nil {
		v := c.Get()
		if v != nil {
			return v.([]byte)
		}
	}
	return make([]byte, 0, size)
}

def _get_content_body(self, message_uuid, body_size):

        body = bytes()
        while len(body) < body_size:
            body_piece = self._channel.rpc.get_request(message_uuid, raw=True,
                                                       multiple=True)
            if not body_piece.value:
                break
            body += body_piece.value
        return body

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


Question:
Encodes the specified cookies into a single Cookie header value.

@param cookies
some cookies
@return a Rfc6265 style Cookie header value, null if no cookies are passed.

public String encode(Cookie... cookies) {
        if (checkNotNull(cookies, "cookies").length == 0) {
            return null;
        }

        StringBuilder buf = stringBuilder();
        if (strict) {
            if (cookies.length == 1) {
                encode(buf, cookies[0]);
            } else {
                Cookie[] cookiesSorted = Arrays.copyOf(cookies, cookies.length);
                Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
                for (Cookie c : cookiesSorted) {
                    encode(buf, c);
                }
            }
        } else {
            for (Cookie c : cookies) {
                encode(buf, c);
            }
        }
        return stripTrailingSeparatorOrNull(buf);
    }

private function prepare($request)
    {
        $request->prepare();

        $curlOptions = $this->composeCurlOptions($request->getOptions());

        $method = strtoupper($request->getMethod());
        switch ($method) {
            case 'POST':
                $curlOptions[CURLOPT_POST] = true;
                break;
            default:
                $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
        }

        $content = $request->getContent();

        if ($method === 'HEAD') {
            $curlOptions[CURLOPT_NOBODY] = true;
        } else {
            $curlOptions[CURLOPT_POSTFIELDS] = $content;
        }

        $curlOptions[CURLOPT_RETURNTRANSFER] = true;
        $curlOptions[CURLOPT_URL] = $request->getFullUrl();
        $curlOptions[CURLOPT_HTTPHEADER] = $request->composeHeaderLines();

        if ($request->getOutputFile()) {
            $curlOptions[CURLOPT_FILE] = $request->getOutputFile();
        }

        return $curlOptions;
    }

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


Question:
Saves the settings for this dataset to the inputted parent xml.

        :param      xparent | <xml.etree.ElementTree.Element>

def toXml(self, xparent):

        for key, value in self.items():
            elem = ElementTree.SubElement(xparent, 'entry')
            typ = type(elem).__name__

            elem.set('key', key)
            elem.set('type', typ)

            if typ in DataSet._xmlTypes:
                DataSet._xmlTypes[typ][0](elem, value)
            else:
                elem.set('value', nstr(value))

function(metadata) {
        var types = ['name', 'desc', 'author'],
            node = this.createElementNS(this.namespaces.gpx, 'metadata');
        for (var i=0; i < types.length; i++) {
            var type = types[i];
            if (metadata[type]) {
                var n = this.createElementNS(this.namespaces.gpx, type);
                n.appendChild(this.createTextNode(metadata[type]));
                node.appendChild(n);
            }
        }
        return node;
    }

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


Question:
Returns a component by its slug

@param string $sSlug The component's slug

@return Component

public static function getBySlug($sSlug): ?Component
    {
        $aComponents = static::available();

        foreach ($aComponents as $oComponent) {
            if ($oComponent->slug === $sSlug) {
                return $oComponent;
            }
        }

        return null;
    }

def get_routing_tuples(cls):
        ''''''
        for callback in cls.callbacks:
            ep_name = '{}.{}'.format(cls.api.__name__, callback.__name__)
            yield (Rule(cls.endpoint_path,
                        endpoint=ep_name,
                        methods=callback.swagger_ops),
                   callback)

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


Question:
Validates the composer.json file: see https://getcomposer.org/doc/03-cli.md#validate

@param array $options
@param OutputInterface $output
@return \Symfony\Component\Console\Output\OutputInterface

public function validate(array $options = null, OutputInterface $output = null) {
		return $this->call_command('validate', $this->prepare_array_input_args($options), $output);
	}

public function add($job, array $config)
    {
        if (empty($config['schedule'])) {
            throw new Exception("'schedule' is required for '$job' job");
        }

        if (!(isset($config['command']) xor isset($config['closure']))) {
            throw new Exception("Either 'command' or 'closure' is required for '$job' job");
        }

        if (isset($config['command']) &&
            (
                $config['command'] instanceof Closure ||
                $config['command'] instanceof SerializableClosure
            )
        ) {
            $config['closure'] = $config['command'];
            unset($config['command']);

            if ($config['closure'] instanceof SerializableClosure) {
                $config['closure'] = $config['closure']->getClosure();
            }
        }

        $config = array_merge($this->config, $config);
        $this->jobs[$job] = $config;
    }

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


Question:
@param float $elapsed
@param float $precision

@return string

protected function _getEid($elapsed, $precision = 0.1)
    {
        $id = '';
        for ($level = 0; $level < 3; $level++) {
            /** @noinspection PowerOperatorCanBeUsedInspection */
            $current = $precision * pow(10, $level);
            if ($current >= 10) {
                break;
            }
            $count = min($elapsed / $current, 10);
            for ($i = 1; $i < $count; $i++) {
                $id .= 't' . (($current >= 1) ? $current * $i : substr(1 / $current, 1) . $i);
            }
        }

        return $id;
    }

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
Returns a list of game objects matching the search query.

Learn more:
https://github.com/justintv/Twitch-API/blob/master/v3_resources/search.md#get-searchgames

@param  string $query   Search query
@param  array $params  Optional params

@return array

public function searchGames($query, $params = [])
  {
      $defaults = [
          'query' => urlencode($query),
          'limit' => 25,
          'type'  => 'suggest',
          'live'  => false,
      ];

      return $this->wrapper->request('GET', 'search/games', ['query' => $this->resolveOptions($params, $defaults)]);
  }

def send_request(input_data, api, url, headers, kwargs):

    data = {}
    if input_data != None:
        data['data'] = input_data

    # request that the API respond with a msgpack encoded result
    serializer = kwargs.pop("serializer", config.serializer)
    data['serializer'] = serializer

    data.update(**kwargs)

    json_data = json.dumps(data)

    response = requests.post(url, data=json_data, headers=headers)

    warning = response.headers.get('x-warning')
    if warning:
        warnings.warn(warning)

    cloud = urlparse(url).hostname
    if response.status_code == 503 and not cloud.endswith('.indico.io'):
        raise APIDoesNotExist("Private cloud '%s' does not include api '%s'" % (cloud, api))

    try:
        if serializer == 'msgpack':
            json_results = msgpack.unpackb(response.content)
        else:
            json_results = response.json()
    except (msgpack.exceptions.UnpackException, msgpack.exceptions.ExtraData):
        try:
            json_results = response.json()
        except:
            json_results = {"error": response.text}

    if config.PY3:
        json_results = convert(json_results)

    results = json_results.get('results', False)
    if results is False:
        error = json_results.get('error')
        raise convert_to_py_error(error)
    return results

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


Question: // SetSegmentNum sets the SegmentNum field's value.

func (s *Scte35SegmentationDescriptor) SetSegmentNum(v int64) *Scte35SegmentationDescriptor {
	s.SegmentNum = &v
	return s
}

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

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

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


Question:
Build the set of inhertied modules. Due to xml inheritence mecanism, there may be cicles in the inheritence
graph, so we build a set of inherited modules

public Set<GwtModule> getInherits()
		throws GwtModuleReaderException
    {
        if ( inherits != null )
        {
            return inherits;
        }

        inherits = new HashSet<GwtModule>();
        addInheritedModules( inherits, getLocalInherits() );

        return inherits;
    }

def x_build_targets_target( self, node ):
        '''

        '''
        target_node = node
        name = self.get_child_data(target_node,tag='name',strip=True)
        path = self.get_child_data(target_node,tag='path',strip=True)
        jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
        #~ Map for jam targets to virtual targets.
        self.target[jam_target] = {
            'name' : name,
            'path' : path
            }
        #~ Create the ancestry.
        dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
        while dep_node:
            child = self.get_data(dep_node,strip=True)
            child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
            self.parent[child_jam_target] = jam_target
            dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
        return None

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


Question: // ExclusiveOpenFailsOnDevice is shared with NsEnterMounter

func ExclusiveOpenFailsOnDevice(pathname string) (bool, error) {
	var isDevice bool
	finfo, err := os.Stat(pathname)
	if os.IsNotExist(err) {
		isDevice = false
	}
	// err in call to os.Stat
	if err != nil {
		return false, fmt.Errorf(
			"PathIsDevice failed for path %q: %v",
			pathname,
			err)
	}
	// path refers to a device
	if finfo.Mode()&os.ModeDevice != 0 {
		isDevice = true
	}

	if !isDevice {
		klog.Errorf("Path %q is not referring to a device.", pathname)
		return false, nil
	}
	fd, errno := unix.Open(pathname, unix.O_RDONLY|unix.O_EXCL, 0)
	// If the device is in use, open will return an invalid fd.
	// When this happens, it is expected that Close will fail and throw an error.
	defer unix.Close(fd)
	if errno == nil {
		// device not in use
		return false, nil
	} else if errno == unix.EBUSY {
		// device is in use
		return true, nil
	}
	// error during call to Open
	return false, errno
}

func waitOpenClipboard() error {
	started := time.Now()
	limit := started.Add(time.Second)
	var r uintptr
	var err error
	for time.Now().Before(limit) {
		r, _, err = openClipboard.Call(0)
		if r != 0 {
			return nil
		}
		time.Sleep(time.Millisecond)
	}
	return err
}

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


Question:
How to serialize as a string

@example "full", "basic", "raw"
@param string $format

public static function setStringFormat(string $format)
    {
        switch ($format) {
            case 'raw':
                self::$format = 'raw';
                break;
            case 'basic':
                self::$format = 'basic';
                break;
            case 'full':
            default:
                self::$format = 'full';
                break;
        }
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question: // GetRoutingProfile returns the routing-profile matching the given id.

func (n *NetworkServerAPI) GetRoutingProfile(ctx context.Context, req *ns.GetRoutingProfileRequest) (*ns.GetRoutingProfileResponse, error) {
	var rpID uuid.UUID
	copy(rpID[:], req.Id)

	rp, err := storage.GetRoutingProfile(storage.DB(), rpID)
	if err != nil {
		return nil, errToRPCError(err)
	}

	resp := ns.GetRoutingProfileResponse{
		RoutingProfile: &ns.RoutingProfile{
			Id:      rp.ID.Bytes(),
			AsId:    rp.ASID,
			CaCert:  rp.CACert,
			TlsCert: rp.TLSCert,
		},
	}

	resp.CreatedAt, err = ptypes.TimestampProto(rp.CreatedAt)
	if err != nil {
		return nil, errToRPCError(err)
	}

	resp.UpdatedAt, err = ptypes.TimestampProto(rp.UpdatedAt)
	if err != nil {
		return nil, errToRPCError(err)
	}

	return &resp, nil
}

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid) {
	t := self.validateType(wireExample)
	obj := &restObjUdid{
		restShared: restShared{
			typ:   t,
			name:  name,
			index: index,
			post:  post,
		},
		find: find,
		del:  del,
		put:  put,
	}
	node.ResUdid[strings.ToLower(name)] = obj
}

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


Question:
internal method for handling request and response
        and raising an exception is http return status code is not success

        :rtype : response object from requests.post()

def _http_request(self, api, data, headers=None):

        if not headers:
            headers = {'Content-Type': 'application/json'}
        if not self._token_valid:
            self._token = self.get_token(self._app_name, self._username, self._password)
        response = requests.post(self._base_url + '/' + api, data=json.dumps(data),
                                 headers=headers)
        # raise an exception if the status was not 200
        logger.debug(json.dumps(data))
        logger.debug(response.text)
        response.raise_for_status()
        return response

public synchronized void onRequestFailed(String message, Throwable ex) {
		String reason = message + ": " + ex.getClass().getName() + ": " + ex.getMessage();
		allRequestsTracker.onRequestFailed(reason);
		recentRequestsTracker.onRequestFailed(reason);
		meter.mark();
	}

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


Question: Attach a data disk to a VMSS VM model

def attach_model(subscription, rgname, vmssvm_model, diskname, lun):
    ''''''
    disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + \
        '/providers/Microsoft.Compute/disks/' + diskname
    disk_model = {'lun': lun, 'createOption': 'Attach', 'caching': 'None',
                  'managedDisk': {'storageAccountType': 'Standard_LRS', 'id': disk_id}}
    vmssvm_model['properties']['storageProfile']['dataDisks'].append(
        disk_model)
    return vmssvm_model

public void serviceName_dedicatedConnect_name_PUT(String serviceName, String name, OvhDedicatedConnect body) throws IOException {
		String qPath = "/vrack/{serviceName}/dedicatedConnect/{name}";
		StringBuilder sb = path(qPath, serviceName, name);
		exec(qPath, "PUT", sb.toString(), body);
	}

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


Question:
Get a class name

@param $name
@return string

public function getClassName($name)
    {
        $name = $this->replaceDollar($name);
        $name = preg_replace_callback('#[/\{\}]+(\w)#', function ($matches) {
            return ucfirst($matches[1]);
        }, $name);
        $name = Inflector::classify($name);

        if (preg_match(self::BAD_CLASS_NAME_REGEX, $name)) {
            $name = '_'.$name;
        }

        return $name;
    }

public function getRendererName()
    {
        $options = $this->getOptions();
        $parameterName = $options['generalParameterNames']['rendererType'];

        if ($this->forceRenderer !== null) {
            // A special renderer was given -> use is
            $rendererName = $this->forceRenderer;
        } else {
            // DEFAULT
            if ($this->getRequest() instanceof ConsoleRequest) {
                $rendererName = $options['settings']['default']['renderer']['console'];
            } else {
                $rendererName = $options['settings']['default']['renderer']['http'];
            }
        }

        // From request
        if ($this->getRequest() instanceof HttpRequest && $this->getRequest()->getQuery($parameterName) != '') {
            $rendererName = $this->getRequest()->getQuery($parameterName);
        }

        return $rendererName;
    }

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


Question:
Commit and close the DB session associated with this task (no error is raised if None is open)

        Args:
            commit (bool): commit session before closing (default=True)

def close_session(self, commit=True):

        if self._session is not None:
            if commit:
                self._session.commit()
            self._session.close()
            self._session = None

def setup_schema(command, conf, vars):
    """"""
    # Load the models

    # <websetup.websetup.schema.before.model.import>
    from depotexample import model
    # <websetup.websetup.schema.after.model.import>

    # <websetup.websetup.schema.before.metadata.create_all>
    print("Creating tables")
    model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
    # <websetup.websetup.schema.after.metadata.create_all>
    transaction.commit()
    print('Initializing Migrations')
    import alembic.config, alembic.command
    alembic_cfg = alembic.config.Config()
    alembic_cfg.set_main_option("script_location", "migration")
    alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
    alembic.command.stamp(alembic_cfg, "head")

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


Question:
prepend
@param {Element} element
@param {String|Node|NodeList|Array<Node>} content

function prepend(element, content) {
  if (isString(content)) {
    return element.insertAdjacentHTML('afterBegin', content);
  } else {
    return element.insertBefore(normalizeContent(content), element.firstChild);
  }
}

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Load and parse seed files in a list of directories. Returns a dict
           that maps unique ids onto ParsedNodes

def load_and_parse(self, package_name, root_dir, relative_dirs, tags=None):
        """"""

        extension = "[!.#~]*.csv"
        if dbt.flags.STRICT_MODE:
            dbt.contracts.project.ProjectList(**self.all_projects)

        file_matches = dbt.clients.system.find_matching(
            root_dir,
            relative_dirs,
            extension)

        # we only want to parse seeds if we're inside 'dbt seed'
        should_parse = self.root_project_config.args.which == 'seed'

        result = {}
        for file_match in file_matches:
            node, agate_table = self.parse_seed_file(file_match, root_dir,
                                                     package_name,
                                                     should_parse)
            node_path = self.get_path(NodeType.Seed, package_name, node.name)
            parsed = self.parse_node(node, node_path,
                                     self.all_projects.get(package_name),
                                     tags=tags, agate_table=agate_table)
            result[node_path] = parsed

        return result

def extract_all_snow_tweets_from_disk_generator(json_folder_path):

    # Get a generator with all file paths in the folder
    json_file_path_generator = (json_folder_path + "/" + name for name in os.listdir(json_folder_path))

    for path in json_file_path_generator:
        for tweet in extract_snow_tweets_from_file_generator(path):
            yield tweet

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


Question:
Set search query elements from the request’s arguments array.

@param array $newArguments

public function setQueryFromArguments($newArguments)
    {
        $this->setQueryString(trim($newArguments['queryString']));
        $this->querySwitchFulltext = ($newArguments['querySwitchFulltext'] != '');
        $this->queryStringTitle = trim($newArguments['queryStringTitle']);
        $this->querySwitchJournalOnly = ($newArguments['querySwitchJournalOnly'] != '');
        $this->queryStringPerson = trim($newArguments['queryStringPerson']);
        $this->queryStringKeyword = trim($newArguments['queryStringKeyword']);
        $this->queryStringDate = trim($newArguments['queryStringDate']);
    }

public function scene($name,$args=null) {
        if($args) {
            $this->scene[$name] = $args;
        }
        // 设置当前场景
        $this->currentScene = $name;

        return $this;
    }

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


Question: Create a new UndoManager with an optional maximum history size.

function UndoManager (maxItems) {
    this.maxItems  = maxItems || 50;
    this.state = NORMAL_STATE;
    this.dontCompose = false;
    this.undoStack = [];
    this.redoStack = [];
  }

public Graph<K, VV, EV> reverse() throws UnsupportedOperationException {
		DataSet<Edge<K, EV>> reversedEdges = edges.map(new ReverseEdgesMap<>()).name("Reverse edges");
		return new Graph<>(vertices, reversedEdges, this.context);
	}

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


Question:
// DeleteSeriesID flags a series as permanently deleted.
// If the series is reintroduced later then it must create a new id.

func (f *SeriesFile) DeleteSeriesID(id SeriesID) error {
	p := f.SeriesIDPartition(id)
	if p == nil {
		return ErrInvalidSeriesPartitionID
	}
	return p.DeleteSeriesID(id)
}

public function build(&$query)
    {
        if (isset($query['alias']) && isset($query['id'])) {
            $query['id'] = $query['id'].'-'.$query['alias'];
            unset($query['alias']);
        }

        $segments = array();

        if (isset($query['oid'])) {
            if ($query['oid'] == 'viewer') {
                $query['oid'] = get_viewer()->uniqueAlias;
            }
            $segments[] = '@'.$query['oid'];
            unset($query['oid']);
        }

        $segments = array_merge($segments, parent::build($query));

        return $segments;
    }

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


Question: Parse ISO date string (YYYY-MM-DD)

def from_iso_date_string(self, date_str: str) -> datetime:

        assert isinstance(date_str, str)

        self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
        return self.value

def CopyToDateTimeString(self):

    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(JavaTime, self).CopyToDateTimeString()

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


Question: Compiles Webpack assets

async function _compileAssets(wwwDir, tmpDir) {
  const nodeDir = resolve(wwwDir, '../node_modules');
  const moduleDirs = (function _moduleDirs() {
    const dirs = [wwwDir];
    if (fs.existsSync(nodeDir)) dirs.push(nodeDir);
    return dirs;
  }());

  const config = webPackConfig('production', tmpDir, moduleDirs, tmpDir);
  if (Utils.isEmpty(config.entry)) return;

  const compiler = Webpack(config);
  await new Promise((_resolve, _reject) => {
    compiler.run((err, stats) => {
      if (stats.hasErrors()) {
        _reject(new Error('Failed to compile assets'));
      }

      _resolve();
    });
  });
}

def output_pdf(html, filename)
      html = add_head html
      load_stylesheets
      generate_cover!
      append_stylesheets html
      puts @wkhtmltopdf.command(output_file(filename)).join(' ') if @config.debug
      @wkhtmltopdf.output_pdf html, output_file(filename)
    end

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


Question: sends header with 503 Service Unavailable status

public function sendServiceUnavailableStatus() {
    $Config = GiroCheckout_SDK_Config::getInstance();

    if ($Config->getConfig('DEBUG_MODE')) {
      GiroCheckout_SDK_Debug_helper::getInstance()->logNotificationOutput('sendServiceUnavailableStatus');
    }

    header('HTTP/1.1 503 Service Unavailable');
  }

public static function retError($value, $http_code = HttpCodes::HTTP_BAD_REQUEST, $prettyPrint = false)
    {
        $response = self::buildResponse($value, false, $http_code);

        return self::retJSON($response, $prettyPrint);
    }

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


Question: // SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value.

func (s *PutBucketEncryptionInput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *PutBucketEncryptionInput {
	s.ServerSideEncryptionConfiguration = v
	return s
}

def read_developer_settings():

    ret = read_cfg("/.rwmeta/developer_settings.json")

    env_developer_settings = os.environ.get('META_SERVICE_ACCOUNT_SECRET', None)
    if not env_developer_settings:
        env_developer_settings = os.environ.get('X-META-Developer-Settings', None)
    if env_developer_settings:
        ret = json.loads(env_developer_settings)

    return ret

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


Question:
Gets the api either from the cache or from ES.
@param orgId
@param apiId
@param version

protected Api getApi(String orgId, String apiId, String version) throws IOException {
        String apiIdx = getApiIdx(orgId, apiId, version);
        Api api;
        synchronized (mutex) {
            api = apiCache.get(apiIdx);
        }

        if (api == null) {
            api = super.getApi(getApiId(orgId, apiId, version));
            synchronized (mutex) {
                if (api != null) {
                    apiCache.put(apiIdx, api);
                }
            }
        }

        return api;
    }

def build_collection_query_object(name, additional_parameters, *args)
    root = "/#{name.to_s}"
    if args.empty?
      #nothing to add
    elsif args.size == 1
      if args.first.to_s =~ /\d+/
        id_metadata = find_id_metadata(name.to_s)
        root << build_id_path(args.first, id_metadata)
      else
        root << "(#{args.first})"
      end
    else
      root << "(#{args.join(',')})"
    end
    QueryBuilder.new(root, additional_parameters)
  end

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


Question:
行驶证驾驶证识别.

@param mixed $image 支持 JPG PNG BMP 格式
@param int   $type  识别类型，0-行驶证识别，1-驾驶证识别

@throws TencentAIException

@return array

@see   https://ai.qq.com/doc/ocrdriverlicenseocr.shtml

private function driver($image, int $type = 0)
    {
        $image = self::encode($image);

        return Request::exec(self::DRIVE, compact('type', 'image'));
    }

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

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


Question:
Transform action to async branch
@param {Function} action
@param {Array|Function} parentAction
@param {Array} path
@param {Array} actions
@param {Boolean} isSync
@returns {*}

function transformAsyncBranch (action, parentAction, path, actions, isSync) {
  action = action.slice();
  isSync = !isSync;
  return action
    .map((subAction, index) => {
      path.push(index);
      var result = transformBranch(subAction, action, path, actions, isSync);
      path.pop();
      return result;
    })
    .filter(branch => !!branch);
}

func kvPaths(b *backend) []*framework.Path {
	return []*framework.Path{
		&framework.Path{
			Pattern: "kv/?",
			Callbacks: map[logical.Operation]framework.OperationFunc{
				logical.ListOperation: b.pathKVList,
			},
		},
		&framework.Path{
			Pattern: "kv/" + framework.GenericNameRegex("key"),
			Fields: map[string]*framework.FieldSchema{
				"key":     &framework.FieldSchema{Type: framework.TypeString},
				"value":   &framework.FieldSchema{Type: framework.TypeString},
				"version": &framework.FieldSchema{Type: framework.TypeInt},
			},
			ExistenceCheck: b.pathExistenceCheck,
			Callbacks: map[logical.Operation]framework.OperationFunc{
				logical.ReadOperation:   b.pathKVRead,
				logical.CreateOperation: b.pathKVCreateUpdate,
				logical.UpdateOperation: b.pathKVCreateUpdate,
				logical.DeleteOperation: b.pathKVDelete,
			},
		},
	}
}

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


Question: Prepare GUI for reset

def reset(self):
        """"""
        self.info(self.tr("About to reset.."))

        models = self.data["models"]

        models["instances"].store_checkstate()
        models["plugins"].store_checkstate()

        # Reset current ids to secure no previous instances get mixed in.
        models["instances"].ids = []

        for m in models.values():
            m.reset()

        for b in self.data["buttons"].values():
            b.hide()

        comment_box = self.findChild(QtWidgets.QWidget, "CommentBox")
        comment_box.hide()

        util.defer(500, self.controller.reset)

public void setText(final String TEXT) {
        if (null == text) {
            _text = TEXT;
            fireUpdateEvent(REDRAW_EVENT);
        } else {
            text.set(TEXT);
        }
    }

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


Question:
Creates a UTC offset from a {@link TimeZone} object.
@param timezone the timezone
@return the UTC offset

public static UtcOffset parse(TimeZone timezone) {
		long offset = timezone.getOffset(System.currentTimeMillis());
		return new UtcOffset(offset);
	}

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
popinLoad

@param {string} name
@param {string} url
@param {object} [options]

function popinLoad(name, url, options) {

            var id          = 'gina-popin-' + instance.id +'-'+ name;

            // popin element
            var $el         = document.getElementById(id) || null;

            if ( $el == null ) {

                var className   = self.options.class +' '+ id;
                $el             = document.createElement('div');
                $el.setAttribute('id', id);
                $el.setAttribute('class', className);
                instance.target.firstChild.appendChild($el);
            }

            if ( typeof(options) != 'undefined' ) {
                var options = merge(options, xhrOptions);
            } else {
                var options = xhrOptions;
            }

            options.url     = url;

            if ( options.withCredentials ) {
                if ('withCredentials' in xhr) {
                    // XHR for Chrome/Firefox/Opera/Safari.
                    if (options.isSynchrone) {
                        xhr.open(options.method, options.url, options.isSynchrone)
                    } else {
                        xhr.open(options.method, options.url)
                    }
                } else if ( typeof XDomainRequest != 'undefined' ) {
                    // XDomainRequest for IE.
                    xhr = new XDomainRequest();
                    xhr.open(options.method, options.url);
                } else {
                    // CORS not supported.
                    xhr = null;
                    var result = 'CORS not supported: the server is missing the header `"Access-Control-Allow-Credentials": true` ';
                    triggerEvent(gina, $el, 'error.' + id, result)
                }
            } else {
                if (options.isSynchrone) {
                    xhr.open(options.method, options.url, options.isSynchrone)
                } else {
                    xhr.open(options.method, options.url)
                }
            }

            // setting up headers
            for (var hearder in options.headers) {
                xhr.setRequestHeader(hearder, options.headers[hearder]);
            }

            if (xhr) {
                // catching ready state cb
                xhr.onreadystatechange = function (event) {
                    if (xhr.readyState == 4) {
                        // 200, 201, 201' etc ...
                        if( /^2/.test(xhr.status) ) {

                            try {
                                var result = xhr.responseText;
                                if ( /json$/.test( xhr.getResponseHeader("Content-Type") ) ) {
                                    result = JSON.parse(xhr.responseText)
                                }

                                instance.eventData.success = result;

                                triggerEvent(gina, $el, 'loaded.' + id, result);

                            } catch (err) {
                                var result = {
                                    'status':  422,
                                    'error' : err.description
                                };

                                instance.eventData.error = result;

                                triggerEvent(gina, $el, 'error.' + id, result)
                            }

                        } else {
                            //console.log('error event triggered ', event.target, $form);
                            var result = {
                                'status':  xhr.status,
                                'error' : xhr.responseText
                            };

                            instance.eventData.error = result;

                            // update toolbar
                            var XHRData = result;
                            if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                                try {
                                    if ( XHRData.error && /^(\{|\[).test(XHRData.error) /)
                                        XHRData.error = JSON.parse(XHRData.error);

                                    // bad .. should not happen
                                    if ( typeof(XHRData.error.error) != 'undefined' )
                                        XHRData.error = XHRData.error.error;

                                    ginaToolbar.update("data-xhr", XHRData )
                                } catch (err) {
                                    throw err
                                }
                            }

                            triggerEvent(gina, $el, 'error.' + id, result)
                        }
                    }
                };

                // catching request progress
                // xhr.onprogress = function(event) {
                //     //console.log(
                //     //    'progress position '+ event.position,
                //     //    '\nprogress total size '+ event.totalSize
                //     //);
                //
                //     var percentComplete = (event.position / event.totalSize)*100;
                //     var result = {
                //         'status': 100,
                //         'progress': percentComplete
                //     };
                //
                //     instance.eventData.onprogress = result;
                //
                //     triggerEvent(gina, $el, 'progress.' + id, result)
                // };

                // catching timeout
                // xhr.ontimeout = function (event) {
                //     var result = {
                //         'status': 408,
                //         'error': 'Request Timeout'
                //     };
                //
                //     instance.eventData.ontimeout = result;
                //
                //     triggerEvent(gina, $el, 'error.' + id, result)
                // };

                // sending
                xhr.send();

                return {
                    'open': function () {
                        var fired = false;
                        addListener(gina, $el, 'loaded.' + id, function(e) {
                        //$popin.on('loaded', function (e) {
                            e.preventDefault();

                            if (!fired) {
                                fired = true;

                                e.target.innerHTML = e.detail;

                                // bind with formValidator if forms are found
                                if ( /<form/i.test(e.target.innerHTML) && typeof($validator) != 'undefined' ) {
                                    var _id = null;
                                    var $forms = e.target.getElementsByTagName('form');
                                    for (var i = 0, len = $forms.length; i < len; ++i) {

                                        if ( !$forms[i]['id'] || typeof($forms[i]) != 'string' ) {
                                            _id = $forms[i].getAttribute('id') || 'form.' + uuid.v1();
                                            $forms[i].setAttribute('id', _id);// just in case
                                            $forms[i]['id'] = _id
                                        } else {
                                            _id = $forms[i]['id']
                                        }

                                        //console.log('pushing ', _id, $forms[i]['id'], typeof($forms[i]['id']), $forms[i].getAttribute('id'));
                                        if ($popin['$forms'].indexOf(_id) < 0)
                                            $popin['$forms'].push(_id);

                                        $forms[i].close = popinClose;
                                        $validator.validateFormById($forms[i].getAttribute('id')) //$forms[i]['id']

                                        removeListener(gina, $popin.target, e.type);
                                    }
                                }

                                popinOpen($popin.name);
                            }
                        });
                    }
                }
            }

        }

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

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


Question: Logs the transition into the database.

def db_log(self, transition, from_state, instance, *args, **kwargs):
        """"""
        if self.log_model:
            model_class = self._get_log_model_class()

            extras = {}
            for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES:
                extras[db_field] = kwargs.get(transition_arg, default)

            return model_class.log_transition(
                modified_object=instance,
                transition=transition.name,
                from_state=from_state.name,
                to_state=transition.target.name,
                **extras)

function resolve(){
		LRState::clear_index();
		LRStation::clear_index();
		// create Root Set
		// we SHOULD have a single etransition to an intial state
		return LRStateSet::init( $this->etransitions[0], $this->Grammar );
	}

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


Question:
Performs a reverse lookup for the given {@code value}.
If multiple keys resolve to the same value, this method
will return the first key match as per the JDBM impl.

@param value
@return
@see InverseHashView#findKeyForValue(Object)

public synchronized K reverseLookup(final V value) {
        if (tmap == null) {
            throw new IllegalStateException("not open");
        }
        return invTmap.findKeyForValue(value);
    }

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: Check if a value is not None

def is_not_none(self, a, message=None):
        ""
        if a is None:
            self.log_error("{} is None".format(str(a)), message)
            return False
        return True

def is_empty(self):

        for family in self.iter_package_families():
            for pkg in self.iter_packages(family):
                return False

        return True

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


Question: // AccessLog is a middleware which prints access log to stdout

func AccessLog(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	start := time.Now()
	w := &responseWriter{
		ResponseWriter: rw,
	}
	next(w, req)
	end := time.Now()

	webgo.LOGHANDLER.Info(
		fmt.Sprintf(
			"%s %s %s %s %d",
			end.Format("2006-01-02 15:04:05 -0700 MST"),
			req.Method,
			req.URL.String(),
			end.Sub(start).String(),
			w.code,
		),
	)
}

public function addOutput($string)
    {
        if (!$this->logFile) {
            throw new \LogicException('The has not started to run yet.');
        }

        file_put_contents($this->logFile, $string, (FILE_APPEND | FILE_BINARY));
    }

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


Question: // NewUntrackEngine creates a default UntrackEngine for tracking theirName.

func NewUntrackEngine(g *libkb.GlobalContext, arg *UntrackEngineArg) *UntrackEngine {
	if libkb.SigVersion(arg.SigVersion) == libkb.KeybaseNullSigVersion {
		arg.SigVersion = libkb.GetDefaultSigVersion(g)
	}

	return &UntrackEngine{
		arg:          arg,
		Contextified: libkb.NewContextified(g),
	}
}

def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False):

		platform = self._transformBuildToolPlatform(platform)
		arguments = [self.getBuildScript(), target, platform, configuration] + args
		if capture == True:
			return Utility.capture(arguments, cwd=self.getEngineRoot(), raiseOnError=True)
		else:
			Utility.run(arguments, cwd=self.getEngineRoot(), raiseOnError=True)

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


Question: Merges all the missing FactFields from oldDefinition into newDeclaration.

protected void mergeTypeDeclarations(TypeDeclaration oldDeclaration,
                                       TypeDeclaration newDeclaration) {
        if (oldDeclaration == null) {
            return;
        }

        //add the missing fields (if any) to newDeclaration
        for (FieldDefinition oldFactField : oldDeclaration.getTypeClassDef().getFieldsDefinitions()) {
            FieldDefinition newFactField = newDeclaration.getTypeClassDef().getField(oldFactField.getName());
            if (newFactField == null) {
                newDeclaration.getTypeClassDef().addField(oldFactField);
            }
        }

        //copy the defined class
        newDeclaration.setTypeClass( oldDeclaration.getTypeClass() );
    }

def _generate_union_properties(self, fields):
        """"""
        for field in fields:
            # void types do not need properties to store additional state
            # information
            if not is_void_type(field.data_type):
                doc = self.process_doc(
                    field.doc, self._docf) if field.doc else undocumented
                warning_str = (
                    ' @note Ensure the `is{}` method returns true before accessing, '
                    'otherwise a runtime exception will be raised.')
                doc += warning_str.format(fmt_camel_upper(field.name))
                self.emit_wrapped_text(
                    self.process_doc(doc, self._docf), prefix=comment_prefix)
                self.emit(fmt_property(field=field))
                self.emit()

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


Question: // Define callbacks for querying

func init() {
	DefaultCallback.Query().Register("gorm:query", queryCallback)
	DefaultCallback.Query().Register("gorm:preload", preloadCallback)
	DefaultCallback.Query().Register("gorm:after_query", afterQueryCallback)
}

func (c *RetrieveCall) Context(ctx context.Context) *RetrieveCall {
	c.ctx_ = ctx
	return c
}

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


Question:
Load an XML string without PHP errors - throws exception instead

@param string $xmlString
@throws \Exception
@return \SimpleXMLElement

private function xmlLoadString($xmlString)
    {
        libxml_clear_errors();
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($xmlString);

        if ($errors = libxml_get_errors()) {
            throw new \RuntimeException('Failed to parse OFX: ' . var_export($errors, true));
        }

        return $xml;
    }

protected function ExecuteExternalPaymentCall()
    {
        $aParameter = $this->GetPaymentParameter();
        $sExternalHandlerURL = $this->GetPaymentURL().'?'.str_replace('&', '&', TTools::GetArrayAsURL($aParameter));
        TTools::WriteLogEntry('OGONE DirectLink: called url: '.$sExternalHandlerURL, 4, __FILE__, __LINE__);
        $sResult = file_get_contents($sExternalHandlerURL);
        TTools::WriteLogEntry('OGONE DirectLink: XML response from DirectLink call: '.$sResult, 1, __FILE__, __LINE__);

        if (false !== $sResult) {
            $this->ParseXMLResponse($sResult);
        }

        return $this->PaymentSuccess();
    }

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


Question:
If frequencies and eigenvectors are supplied they are used
    instead of calculating them at q-point (but not at q+dq and q-dq).

    reciprocal lattice has to be given as
    [[a_x, b_x, c_x],
     [a_y, b_y, c_y],
     [a_z, b_z, c_z]]

def get_group_velocity(q,  # q-point
                       dynamical_matrix,
                       q_length=None,  # finite distance in q
                       symmetry=None,
                       frequency_factor_to_THz=VaspToTHz):

    gv = GroupVelocity(dynamical_matrix,
                       q_length=q_length,
                       symmetry=symmetry,
                       frequency_factor_to_THz=frequency_factor_to_THz)
    gv.set_q_points([q])
    return gv.get_group_velocity()[0]

def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):

    gene_jsd_dict = dict()
    reference_genes = ref_gene_expression_dict.keys()
    assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.'

    for gene in gene_set:
        if gene not in network.nodes:
            continue

        neighbors = find_neighbors(network, gene)

        query_expression_vec = get_neighbor_expression_vector(neighbors, query_gene_expression_dict)
        ref_expression_vec = get_neighbor_expression_vector(neighbors, ref_gene_expression_dict)
        assert len(query_expression_vec) == len(ref_expression_vec), 'Topology of reference network and query network differs. Please check.'

        # A gene which has non-expressed neighbors is ignored.
        if np.sum(query_expression_vec) == 0 and np.sum(ref_expression_vec) == 0:
            continue

        query_p_vec = exp2prob(query_expression_vec)
        ref_p_vec = exp2prob(ref_expression_vec)

        gene_jsd_dict[gene] = jsd(query_p_vec, ref_p_vec)

    return np.mean(list(gene_jsd_dict.values()))

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


Question: // WriteConfig saves a config to a file

func WriteConfig(filename string, cfg *Config) error {
	b, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filename, b, 0600)
}

func (ini *INI) SetComments(section, key string, comments ...string) {
	sec := ini.getSection(section)

	if key == "" {
		if sec == nil {
			sec = ini.addSection(section)
		}
		sec.Comments = comments
		return
	}

	if item := sec.getItem(key, ini.isCaseSensitive); item != nil {
		item.Comments = comments
	}
}

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


Question: // Fingerprint generates a colon-separated fingerprint string from a public key.

func Fingerprint(key ssh.PublicKey) string {
	hash := md5.Sum(key.Marshal())
	buf := make([]byte, hex.EncodedLen(len(hash)))
	hex.Encode(buf, hash[:])
	// We need this in colon notation:
	fp := make([]byte, len(buf)+15)

	i, j := 0, 0
	for ; i < len(buf); i++ {
		if i > 0 && i%2 == 0 {
			fp[j] = ':'
			j++
		}
		fp[j] = buf[i]
		j++
	}

	return string(fp)
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

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


Question: // CreateInputField creates an input field at x, y that is w by h

func CreateInputField(x, y, w, h int, fg, bg termbox.Attribute) *InputField {
	c := InputField{x: x, y: y, width: w, height: h,
		fg: fg, bg: bg, cursorFg: bg, cursorBg: fg, activeFg: fg, activeBg: bg,
	}
	return &c
}

def get_window_size(self):

        if not self._window_size:
            if self.driver_wrapper.is_android_web_test() and self.driver_wrapper.driver.current_context != 'NATIVE_APP':
                window_width = self.driver_wrapper.driver.execute_script("return window.innerWidth")
                window_height = self.driver_wrapper.driver.execute_script("return window.innerHeight")
                self._window_size = {'width': window_width, 'height': window_height}
            else:
                self._window_size = self.driver_wrapper.driver.get_window_size()
        return self._window_size

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


Question: log transform each value in table

def log_trans(table):

    t = []
    all = [item for sublist in table for item in sublist]
    if min(all) == 0:
        scale = min([i for i in all if i != 0]) * 10e-10
    else:
        scale = 0
    for i in table:
        t.append(np.ndarray.tolist(np.log10([j + scale for j in i])))
    return t

def _generate_reversed_sql(self, keys, changed_keys):

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

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

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


Question: Validator for the "regex" form field property

public function validateRegex(string $key, array $def, $value)
    {
        if (is_scalar($value) && isset($def['regex']) && !empty($value) && !preg_match($def['regex'], $value)) {
            $this->addError($key, 'form.value_not_valid_regex');
        }
    }

protected function getValidationRule($inputName)
    {
        $rules = $this->getValidationRules();

        return is_array($rules[$inputName]) ? $rules[$inputName] : explode('|', $rules[$inputName]);
    }

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


Question: Scrub PII from the given participant table.

def _scrub_participant_table(path_to_data):
    """"""
    path = os.path.join(path_to_data, "participant.csv")
    with open_for_csv(path, "r") as input, open("{}.0".format(path), "w") as output:
        reader = csv.reader(input)
        writer = csv.writer(output)
        headers = next(reader)
        writer.writerow(headers)
        for i, row in enumerate(reader):
            row[headers.index("worker_id")] = row[headers.index("id")]
            row[headers.index("unique_id")] = "{}:{}".format(
                row[headers.index("id")], row[headers.index("assignment_id")]
            )
            writer.writerow(row)

        os.rename("{}.0".format(path), path)

protected static function getUserGroups(array $user): array
    {
        $table = TableRegistry::get('Groups.Groups');
        Assert::isInstanceOf($table, GroupsTable::class);

        return $table->getUserGroups($user['id'], [
            'fields' => ['id'],
            'contain' => [],
        ]);
    }

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


Question:
Returns a random string, based on the provided arguments.

    It returns capital letters and numbers by default.
    Ambiguous characters are left out, repetitions will be avoided.

def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789',
                         repetitions=False):

    if repetitions:
        return ''.join(random.choice(chars) for _ in range(length))
    return ''.join(random.sample(chars, length))

private function getRandomTags($count = 5)
    {
        $tags = ['action', 'adult', 'adventure', 'alpha', 'animals', 'animation', 'anime', 'architecture', 'art',
            'astronomy', 'baby', 'batshitinsane', 'biography', 'biology', 'book', 'books', 'business', 'business',
            'camera', 'cars', 'cats', 'cinema', 'classic', 'comedy', 'comics', 'computers', 'cookbook', 'cooking',
            'crime', 'culture', 'dark', 'design', 'digital', 'documentary', 'dogs', 'drama', 'drugs', 'education',
            'environment', 'evolution', 'family', 'fantasy', 'fashion', 'fiction', 'film', 'fitness', 'food',
            'football', 'fun', 'gaming', 'gift', 'health', 'hip', 'historical', 'history', 'horror', 'humor',
            'illustration', 'inspirational', 'internet', 'journalism', 'kids', 'language', 'law', 'literature', 'love',
            'magic', 'math', 'media', 'medicine', 'military', 'money', 'movies', 'mp3', 'murder', 'music', 'mystery',
            'news', 'nonfiction', 'nsfw', 'paranormal', 'parody', 'philosophy', 'photography', 'photos', 'physics',
            'poetry', 'politics', 'post-apocalyptic', 'privacy', 'psychology', 'radio', 'relationships', 'research',
            'rock', 'romance', 'rpg', 'satire', 'science', 'sciencefiction', 'scifi', 'security', 'self-help',
            'series', 'software', 'space', 'spirituality', 'sports', 'story', 'suspense', 'technology', 'teen',
            'television', 'terrorism', 'thriller', 'travel', 'tv', 'uk', 'urban', 'us', 'usa', 'vampire', 'video',
            'videogames', 'war', 'web', 'women', 'world', 'writing', 'wtf', 'zombies',
        ];

        shuffle($tags);

        $picked = array_slice($tags, 0, $count);

        return $picked;
    }

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


Question:
Receive the feedback tuples from APNS

@return array Array containing FeedbackTuples received from Apple

public function receive()
	{
		// Initialize variables
		$feedbackData = '';
		$tuples = array();

		// Connect to the feedback service
		$this->connect(Certificate::ENDPOINT_TYPE_FEEDBACK);

		// Read all data from the feedback service
		while ( !feof($this->getConnection()) )
		{
			// Make sure signals to this process are respected and handled
			if (function_exists('pcntl_signal_dispatch')) {
				pcntl_signal_dispatch();
			}

			// Fetch the available feedback data from the socket
			$feedbackData .= fread($this->getConnection(), 16384);

			// Loop over all tuples in the current feedbackdata
			while (strlen($feedbackData) >= Tuple::BINARY_LENGTH)
			{
				// Get the first tuple out of the data and unpack the data
				$binaryTupleData = substr($feedbackData, 0, Tuple::BINARY_LENGTH);
				$tupleData = unpack('Ntimestamp/ntokenLength/H*deviceToken', $binaryTupleData);

				// Create a tuple object from it
				$tuples[] = new Tuple($tupleData['timestamp'], $tupleData['deviceToken'], $this->getCertificate());

				// Remove the tuple from the feedbackdata
				$feedbackData = substr($feedbackData, Tuple::BINARY_LENGTH);
			}

			// All messages send, wait some time for an APNS response
			$read = array($this->getConnection());
			$write = $except = null;
			$changedStreams = stream_select($read, $write, $except, 0, self::READ_TIMEOUT);

			// Did waiting for the response succeed?
			if (false === $changedStreams)
			{
				// We'll just stop reading and do not throw an error, because we don't want to loose any tuples
				break;
			}
		}

		// And we're done, disconnect from the service
		$this->disconnect();

		$this->logger->info('Apns\Feedback recieved ' . count($tuples) . ' tuples from APNS feedback service using certificate "' . $this->getCertificate()->getFingerprint() . '"');

		return $tuples;
	}

def set_bucket_notification(self, bucket_name, notifications):

        is_valid_bucket_name(bucket_name)
        is_valid_bucket_notification_config(notifications)

        content = xml_marshal_bucket_notifications(notifications)
        headers = {
            'Content-Length': str(len(content)),
            'Content-Md5': get_md5_base64digest(content)
        }
        content_sha256_hex = get_sha256_hexdigest(content)
        self._url_open(
            'PUT',
            bucket_name=bucket_name,
            query={"notification": ""},
            headers=headers,
            body=content,
            content_sha256=content_sha256_hex
        )

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


Question:
Gets allowable values of the enum
@return string[]

public function getStatusAllowableValues()
    {
        return [
            self::STATUS_ACTIVE,
            self::STATUS_PAUSED,
            self::STATUS_READY,
            self::STATUS_DELIVERED,
            self::STATUS_CANCELLED,
            self::STATUS_REVERTED,
        ];
    }

function yy_r130()
    {
        $this->_retvalue = '[' . $this->compiler->compileTag('private_special_variable', array(), '[\'section\'][\'' .
                                                                                $this->yystack[ $this->yyidx +
                                                                                - 1 ]->minor .
                                                                                '\'][\'index\']') . ']';
    }

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


Question: Determine the media type to use for the response

protected String getMediaType(
            HttpServletRequest req,
            HttpServletResponse res,
            PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader) {
        final String mediaType = pipelineEventReader.getOutputProperty(OutputKeys.MEDIA_TYPE);
        if (mediaType != null) {
            return mediaType;
        }

        this.logger.warn(
                "No mediaType was specified in the pipeline output properties, defaulting to "
                        + DEFAULT_MEDIA_TYPE);
        return DEFAULT_MEDIA_TYPE;
    }

public static function UnsupportedMediaType($body = NULL, \Exception $previous = NULL) {
    return self::code(415, $body, $previous);
  }

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


Question:
Autoload Children - Checks structure for nested structures

@since  1.0.0
@access public

public function setup() {

		foreach ( $this->struct as $struct_key => $sub_struct ) {
			if ( is_array( $sub_struct ) && uix()->get_register_callback( $struct_key ) ) {
				$this->process_child( $struct_key );
			}
		}
	}

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
/*
(non-Javadoc)

@see com.ibm.ws.sib.msgstore.ItemStream#getCountLowWaterMark()

@Override
    public long getCountLowWaterMark() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "getCountLowWaterMark");

        long destLow = _destLowMsgs + getSubscriberCount();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "getCountLowWaterMark", Long.valueOf(destLow));
        return destLow;
    }

public function importSubscribers($listId = '', $subscribers = array())
    {
        $settings = CmService::$plugin->getSettings();

        try {
            $auth = array(
                'api_key' => (string)$settings->apiKey);
            $client = new \CS_REST_Subscribers(
                $listId,
                $auth);
            $result = $client->import($subscribers, false);

            if($result->was_successful()) {
                $body = $result->response;
                return [
                    'success' => true,
                    'statusCode' => $result->http_status_code,
                    'body' => $body
                ];
            } else {
                return [
                    'success' => false,
                    'statusCode' => $result->http_status_code,
                    'reason' => $result->response->Message
                ];
            }
        } catch (\Exception $e) {
            return [
                'success' => false,
                'reason' => $e->getMessage()
            ];
        }
    }

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