Question:
Check if we are loading a search page.

@param string $postType Optional. Look for a specific post type
@param array $details Settings for the route

private static function search($postType, array $details)
    {
        $s = isset($_GET['post_type']) ? $_GET['post_type'] : false;

        if($s === $postType && is_search())
        {
            self::loadController($details);
            exit;
        }
    }

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
Converts a numpy array to a tensor def.

    Inputs:
        arr: a numpy array.
        name: (optional) the name of the tensor.
    Returns:
        tensor_def: the converted tensor def.

def from_array(arr, name=None):  # type: (np.ndarray[Any], Optional[Text]) -> TensorProto

    tensor = TensorProto()
    tensor.dims.extend(arr.shape)
    if name:
        tensor.name = name

    if arr.dtype == np.object:
        # Special care for strings.
        tensor.data_type = mapping.NP_TYPE_TO_TENSOR_TYPE[arr.dtype]
        # TODO: Introduce full string support.
        # We flatten the array in case there are 2-D arrays are specified
        # We throw the error below if we have a 3-D array or some kind of other
        # object. If you want more complex shapes then follow the below instructions.
        # Unlike other types where the shape is automatically inferred from
        # nested arrays of values, the only reliable way now to feed strings
        # is to put them into a flat array then specify type astype(np.object)
        # (otherwise all strings may have different types depending on their length)
        # and then specify shape .reshape([x, y, z])
        flat_array = arr.flatten()
        for e in flat_array:
            if isinstance(e, text_type):
                tensor.string_data.append(e.encode('utf-8'))
            elif isinstance(e, np.ndarray):
                for s in e:
                    if isinstance(s, text_type):
                        tensor.string_data.append(s.encode('utf-8'))
            else:
                raise NotImplementedError(
                    "Unrecognized object in the object array, expect a string, or array of bytes: ", str(type(e)))
        return tensor

    # For numerical types, directly use numpy raw bytes.
    try:
        dtype = mapping.NP_TYPE_TO_TENSOR_TYPE[arr.dtype]
    except KeyError:
        raise RuntimeError(
            "Numpy data type not understood yet: {}".format(str(arr.dtype)))
    tensor.data_type = dtype
    tensor.raw_data = arr.tobytes()  # note: tobytes() is only after 1.9.

    return tensor

def register_ops_if_needed(graph_ops):

  missing_ops = graph_ops - set(op_def_registry.get_registered_ops().keys())

  if not missing_ops:
    return

  p_buffer = c_api.TF_GetAllOpList()
  cpp_op_list = op_def_pb2.OpList()
  cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer))
  cpp_registry_ops = {op.name: op for op in cpp_op_list.op}

  missing_op_list = op_def_pb2.OpList()
  for missing_op in missing_ops:
    if missing_op not in cpp_registry_ops:
      logging.info(
          "Op %s is missing from both the python and C++ registry.",
          missing_op)
    else:
      missing_op_list.op.extend([cpp_registry_ops[missing_op]])
      logging.info(
          "Adding op %s from c++ registry to python registry.",
          missing_op)

  op_def_registry.register_op_list(missing_op_list)

  # Note: Only raise missing op ValueError after trying to load ops.
  # This allows the test to exercise all the calls into TensorFlow
  # without having to write a C + python test.
  if not missing_ops <= set(cpp_registry_ops.keys()):
    raise RuntimeError(
        "Graph ops missing from the python registry (%s) are also absent from "
        "the c++ registry."
        % missing_ops.difference(set(cpp_registry_ops.keys())))

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


Question:
Binds the request to the form

@param \CodeCollab\Http\Request\Request $request The request object

public function bindRequest(Request $request)
    {
        $this->request = $request;

        foreach ($this->request->postArray() as $key => $value) {
            if (isset($this->fieldSet[$key])) {
                $this->fieldSet[$key]->setValue($value);
            }
        }
    }

protected function getBodyParametersFromDocBlock(array $tags)
    {
        $parameters = collect($tags)
            ->filter(function ($tag) {
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
            })
            ->mapWithKeys(function ($tag) {
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
                if (empty($content)) {
                    // this means only name and type were supplied
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
                    $required = false;
                    $description = '';
                } else {
                    list($_, $name, $type, $required, $description) = $content;
                    $description = trim($description);
                    if ($description == 'required' && empty(trim($required))) {
                        $required = $description;
                        $description = '';
                    }
                    $required = trim($required) == 'required' ? true : false;
                }

                $type = $this->normalizeParameterType($type);
                list($description, $example) = $this->parseDescription($description, $type);
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;

                return [$name => compact('type', 'description', 'required', 'value')];
            })->toArray();

        return $parameters;
    }

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


Question:
Read yaml config object from the yaml file at specified file.

@param targetFile target file
@return config read from yaml
@throws IOException Fail read yaml file or convert to config object.

@SuppressWarnings("unchecked")
    public static Map<String, Object> readYaml(File targetFile) throws IOException
    {
        Map<String, Object> configObject = null;
        Yaml yaml = new Yaml();

        InputStream inputStream = null;
        InputStreamReader steamReader = null;

        try
        {
            inputStream = new FileInputStream(targetFile);
            steamReader = new InputStreamReader(inputStream, "UTF-8");
            configObject = (Map<String, Object>) yaml.load(steamReader);
        }
        catch (ScannerException ex)
        {
            // ScannerException/IOException are occured.
            // throw IOException because handling is same.
            throw new IOException(ex);
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
        }

        return configObject;
    }

public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");

        FileArgument expectedFile = new FileArgument("e", "expected-file", "expected interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument observedFile = new FileArgument("b", "observed-file", "observed interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument outputFile = new FileArgument("o", "output-file", "output file, default stdout", false);
        IntegerArgument resolution = new IntegerArgument("r", "resolution", "resolution, must be in the range [1..4], default " + DEFAULT_RESOLUTION, false);
        StringListArgument loci = new StringListArgument("l", "loci", "list of loci to validate, default " + DEFAULT_LOCI, false);
        Switch printSummary = new Switch("s", "summary", "print summary");

        ArgumentList arguments = new ArgumentList(about, help, expectedFile, observedFile, outputFile, resolution, loci, printSummary);
        CommandLine commandLine = new CommandLine(args);

        ValidateInterpretation validateInterpretation = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }

            // todo: allow for configuration of glclient
            validateInterpretation = new ValidateInterpretation(expectedFile.getValue(), observedFile.getValue(), outputFile.getValue(), resolution.getValue(DEFAULT_RESOLUTION), loci.getValue(DEFAULT_LOCI), printSummary.wasFound(), LocalGlClient.create());
        }
        catch (CommandLineParseException e) {
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(validateInterpretation.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

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


Question:
Gets the value of the agent property.

@return
possible object is
{@link org.openprovenance.prov.sql.IDRef }

@ManyToOne(targetEntity = org.openprovenance.prov.sql.QualifiedName.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "AGENT")
    public org.openprovenance.prov.model.QualifiedName getAgent() {
        return agent;
    }

async def prover_close_credentials_search(search_handle: int) -> None:

    logger = logging.getLogger(__name__)
    logger.debug("prover_close_credentials_search: >>> search_handle: %r",
                 search_handle)

    if not hasattr(prover_close_credentials_search, "cb"):
        logger.debug("prover_close_credentials_search: Creating callback")
        prover_close_credentials_search.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_search_handle = c_int32(search_handle)

    res = await do_call('indy_prover_close_credentials_search',
                        c_search_handle,
                        prover_close_credentials_search.cb)

    logger.debug("prover_close_credentials_search: <<< res: %r", res)
    return res

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


Question:
Convert parameters defined in `self._param` to list

        :return None

def _param_to_list(self):

        for item in self._params:
            self.__dict__[item] = list(self.__dict__[item])

def return_as(returntype):

    def decorator(func):
        # @wraps(func) <- we can't use this as normal because it doesn't work
        #                 on python < 3 for instance methods,
        #                 see workaround below
        def wrapped(*args, **kwargs):
            result = func(*args, **kwargs)
            try:
                return returntype(result)
            except (TypeError, ValueError) as exc:
                exc.args = (
                    'failed to cast return from {0} as {1}: {2}'.format(
                        func.__name__, returntype.__name__, str(exc)),
                )
                raise
        try:
            return wraps(func)(wrapped)
        except AttributeError:  # python < 3.0.0
            wrapped.__doc__ == func.__doc__
            return wrapped

    return decorator

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


Question: // NewENSRegistryFilterer creates a new log filterer instance of ENSRegistry, bound to a specific deployed contract.

func NewENSRegistryFilterer(address common.Address, filterer bind.ContractFilterer) (*ENSRegistryFilterer, error) {
	contract, err := bindENSRegistry(address, nil, nil, filterer)
	if err != nil {
		return nil, err
	}
	return &ENSRegistryFilterer{contract: contract}, nil
}

func (s *Server) verifyNICsWithConfigFile(nics map[string]device, reader func(string) ([]byte, error)) error {
	netName, err := checkBridgeConfigFile(reader)
	if err != nil {
		return errors.Trace(err)
	}

	checked := make([]string, 0, len(nics))
	for name, nic := range nics {
		checked = append(checked, name)

		if nic["parent"] != netName {
			continue
		}
		if !isValidNICType(nic) {
			continue
		}

		logger.Tracef("found usable network device %q with parent %q", name, netName)
		s.localBridgeName = netName
		return nil
	}

	return errors.Errorf("no network device found with nictype %q or %q that uses the configured bridge in %s"+
		"\n\tthe following devices were checked: %v", nicTypeBridged, nicTypeMACVLAN, BridgeConfigFile, checked)
}

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


Question:
Checks annotations and ie.

@param document input document

public static void check(BioCDocument document) {
    String text = BioCUtils.getText(document);
    // check annotation offset and text
    checkAnnotations(document.getAnnotations(), text, 0, BioCLog.log(document));
    // check relation
    for (BioCRelation relation : document.getRelations()) {
      for (BioCNode node : relation.getNodes()) {
        checkArgument(document.getAnnotation(node.getRefid()).isPresent(),
            "Cannot find node %s in relation %s\n" +
                "Location: %s", node, relation, BioCLog.log(document));
      }
    }

    // check passage
    for (BioCPassage passage : document.getPassages()) {
      text = BioCUtils.getText(passage);
      // check annotation offset and text
      checkAnnotations(passage.getAnnotations(), text, passage.getOffset(),
          BioCLog.log(document, passage));
      // check relation
      for (BioCRelation relation : passage.getRelations()) {
        for (BioCNode node : relation.getNodes()) {
          checkArgument(passage.getAnnotation(node.getRefid()).isPresent(),
              "Cannot find node %s in relation %s\n" +
                  "Location: %s", node, relation, BioCLog.log(document, passage));
        }
      }

      // check sentence
      for (BioCSentence sentence : passage.getSentences()) {
        // check annotation offset and text
        checkAnnotations(sentence.getAnnotations(), sentence.getText().get(),
            sentence.getOffset(), BioCUtils.getXPathString(document, passage, sentence));
        // check relation
        for (BioCRelation relation : sentence.getRelations()) {
          for (BioCNode node : relation.getNodes()) {
            checkArgument(sentence.getAnnotation(node.getRefid()).isPresent(),
                "Cannot find node %s in relation %s\n" +
                    "  Location: %s", node, relation,
                BioCUtils.getXPathString(document, passage, sentence));
          }
        }
      }
    }
  }

public boolean isModifiedOnVersion(String version) {
		if( this.modificationHistory.isModifiedOnVersion(version)
				|| this.outParameter.isModifiedOnVersion(version) ) {
			return true;
		}
		for(APIParameter inParameter : inParameters) {
			if(inParameter.isModifiedOnVersion(version)) {
				return true;
			}
		}
		return false;
	}

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


Question: Starts a process to find a working transport.

function find() {
      // If there is no remaining URI, fires `error` and `close` event as it means that all
      // tries failed.
      if (uris.length === 0) {
        // Now that `connecting` event is being fired, there is no `error` and `close` event user
        // added. Delays to fire them a little while.
        setTimeout(function() {
          self.emit("error", new Error());
          self.emit("close");
        }, 0);
        return;
      }
      // A temporal variable to be used while finding working one.
      var testTransport;
      // Get the first uri by removing it from `uris`. For example, `[1,2].shift()` returns `1`
      // and make the array `[2]`.
      var uri = uris.shift();
      // Transport handles only the specific types of URIs. It finds which transport factory can
      // handle this `uri` among ones specified by `transports` option.
      for (var i = 0; i < options.transports.length; i++) {
        // A transport factory creates and returns a transport object if it can handle the given
        // URI and nothing if not.
        testTransport = options.transports[i](uri, options);
        // If the factory handles this type of URI,
        if (testTransport) {
          break;
        }
      }
      // If there is no transport matching with the given URI, try with the next URI.
      if (!testTransport) {
        find();
        return;
      }
      // This is to stop the whole process to find a working transport when the `close` method
      // is called before `open` event.
      function stop() {
        testTransport.removeListener("close", find);
        testTransport.close();
      }

      // Until the socket is opened, `close` method should trigger `stop` function as well.
      self.once("close", stop);
      // It establishes a connection.
      testTransport.open();
      // If it fails, it should remove stop listener and try with the next URI. These event handlers
      // will be removed once this transport is recognized as working.
      testTransport.on("close", function() {
        self.removeListener("close", stop);
      });
      testTransport.on("close", find);
      // Node.js kills the process by default when an `error` event is fired if there is no
      // listener for it. However, a user doesn't need to be notified of an error from this
      // transport being tested.
      testTransport.on("error", function() {
      });
      // If it succeeds, it means that the process to find working transport is done. The first
      // transport text message is used to handshake the socket protocol. Note that `once`
      // registers one-time event handler.
      testTransport.once("text", function(text) {
        // The handshake output is in the form of URI. Query params starting with `cettia-`
        // represent protocol header.
        var headers = url.parse(text, true).query;
        // The server prints an id of the socket as a `cettia-id` param, `id` header,
        // every time the transport connects. If the server issues a new id,
        if (id !== headers["cettia-id"]) {
          // That means there was no `id` or the server socket whose id is `id` was deleted in
          // the server due to long-term disconnection.
          id = headers["cettia-id"];
          // Fires a `new` event as a new socket is created.
          self.emit("new");
        }

        // To maintain an alive connection, `heartbeat` is used.
        options.heartbeat = +headers["cettia-heartbeat"];
        // `_heartbeat` is for testing so it should be not passed from the server in production.
        // The default value is `5000`.
        options._heartbeat = +headers["cettia-_heartbeat"] || 5000;
        // Now that the working transport is found and handshaking is completed, it stops
        // a process to find a working transport by removing `close` event handler `find` and
        // associates the working transport with the socket.
        testTransport.removeListener("close", find);
        transport = testTransport;

        // When an event object is created from `text` or `binary` event,
        function onevent(event) {
          // Event should have the following properties:
          // * `id: string`: an event identifier.
          // * `type: string`: an event type.
          // * `data: any`: an event data.
          // * `reply: boolean`: `true` if this event requires the reply.

          // If the server sends a plain event, dispatch it.
          if (!event.reply) {
            self.emit(event.type, event.data);
          } else {
            var latch;
            // A function to create a function.
            function reply(success) {
              // A controller function.
              return function(value) {
                // This latch prevents double reply.
                if (!latch) {
                  latch = true;
                  self.send("reply", {id: event.id, data: value, exception: !success});
                }
              };
            }

            // Here, the controller is passed to the event handler as 2nd argument and
            // allows to call the server's `resolved` or `rejected` callback by sending
            // `reply` event.
            self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
          }
        }

        // When the transport has received a text message from the server,
        // it deserializes a text message into an event object in the JSON format and deals with it.
        transport.on("text", function(text) {
          onevent(JSON.parse(text));
        });
        // When the transport has received a binary message from the server.
        // it deserializes a binary message into an event object in the
        // [MessagePack](http://msgpack.org) format and deals with it.
        transport.on("binary", function(binary) {
          onevent(msgpack.decode(binary));
        });
        // When any error has occurred.
        transport.on("error", function(error) {
          self.emit("error", error);
        });
        // When the transport has been closed for any reason.
        transport.on("close", function() {
          self.emit("close");
        });
        // Now that the working transport is associated and the communication is possible,
        // it removes `close` event handler `stop` and fires `open` event.
        self.removeListener("close", stop);
        self.emit("open");
      });
    }

func NewServer(driver StorageDriver, host *host.Host, volumesPath string) (*Server, error) {
	if len(driver.ExportPath()) < 9 {
		return nil, fmt.Errorf("export path can not be empty")
	}

	s := &Server{
		host:   host,
		driver: driver,
	}

	return s, nil
}

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


Question:
Write request to the server.

@param mixed $request The request to write
@throws ValidationException

public function write($request)
    {
        if ($this->isComplete) {
            throw new ValidationException("Cannot call write() after streaming call is complete.");
        }
        if ($this->writesClosed) {
            throw new ValidationException("Cannot call write() after calling closeWrite().");
        }
        $this->call->write($request);
    }

public function insert($values)
    {
        try {
            if (func_num_args() > 0 && !is_array($values)) {
                $this->values = array_merge($this->values, self::sanitizeAV(func_get_args()));
            } else if (is_array($values)) {
                $this->values = self::sanitize($values);
            } else {
                static::$response["status"] = "error";
                static::$response["response"] = "unrecognized parameter options in the insert values";
                static::$response["code"] = 7004;
                return static::terminate(static::$response);
            }
        } catch (Exception $e) {
            static::$response["status"] = "error";
            static::$response["response"] = $e->getMessage();
            static::$response["code"] = $e->getCode();
           return static::terminate(static::$response);
        }

        return $this;
    }

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


Question: Determine whether the search page should start with a listing.

public function index() {

		// Determine whether a search engine has been selected.

		$engine = $this->data()->SearchEngine;
		$classes = Config::inst()->get(FulltextSearchable::class, 'searchable_classes');
		if(!$engine || (($engine !== 'Full-Text') && !ClassInfo::exists($engine)) || (($engine === 'Full-Text') && (!is_array($classes) || (count($classes) === 0)))) {

			// The search engine has not been selected.

			return $this->httpError(404);
		}

		//

		if($this->data()->StartWithListing) {

			// Display some search results.

			$request = $this->getRequest();
			return $this->getSearchResults(array(
				'Search' => $request->getVar('Search'),
				'SortBy' => $request->getVar('SortBy'),
				'SortDirection' => $request->getVar('SortDirection')
			), $this->getForm($request));
		}
		else {

			// Instantiate some default templates.

			$templates = array(
				'ExtensibleSearch',
				'ExtensibleSearchPage',
				'Page'
			);

			// Instantiate the search engine specific templates.

			if($engine !== 'Full-Text') {
				$explode = explode('\\', $engine);
				$explode = end($explode);
				$templates = array_merge(array(
					$explode,
					"{$explode}Page"
				), $templates);
			}

			// Determine the template to use.

			$this->extend('updateTemplates', $templates);
			return $this->renderWith($templates);
		}
	}

def sitemap_meta_description
      return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
    end

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


Question:
Function setCacheTtl

Cầu hình TTL cho file Cache

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 10/12/18 12:49

@param null $cacheTtl

public function setCacheTtl($cacheTtl = NULL)
    {
        $this->cacheTtl = $cacheTtl;
        $this->debug->debug(__FUNCTION__, 'setCacheTtl: ', $this->cacheTtl);
    }

func (s *DomainNameConfiguration) SetCertificateUploadDate(v time.Time) *DomainNameConfiguration {
	s.CertificateUploadDate = &v
	return s
}

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


Question:
Sets the AWS Key Management System parameters used to encrypt the object
on server side.

public void setSSEAwsKeyManagementParams(SSEAwsKeyManagementParams params) {
        if (params != null && this.destinationSSECustomerKey != null) {
            throw new IllegalArgumentException(
                "Either SSECustomerKey or SSEAwsKeyManagementParams must not be set at the same time.");
        }
        this.sseAwsKeyManagementParams = params;
    }

public java.util.List<String> getSetup() {
        if (setup == null) {
            setup = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return setup;
    }

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


Question: // XXX_OneofFuncs is for the internal use of the proto package.

func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{
		(*LoadBalanceRequest_InitialRequest)(nil),
		(*LoadBalanceRequest_ClientStats)(nil),
	}
}

private void createFunction(String name, GeometryFunction function) {
		try {
			Function.create(getGeoPackage().getConnection().getConnection(),
					name, function);
		} catch (SQLException e) {
			log.log(Level.SEVERE, "Failed to create function: " + name, e);
		}
	}

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


Question: Returns: generator over all countries in this coalition

def countries(self) -> typing.Iterator['Country']:

        for k in self._section_country:
            if k not in self._countries.keys():
                country = Country(self.d, self.l10n, self.coa_color, k)
                self._countries[k] = country
                self._countries_by_id[country.country_id] = country
                self._countries_by_name[country.country_name] = country
            yield self._countries[k]

def run_example():

    """
    weather = mc_e.get_weather_data('weather.csv')
    my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines()
    example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126)
    example_cluster = initialize_wind_turbine_cluster(example_farm,
                                                      example_farm_2)
    calculate_power_output(weather, example_farm, example_cluster)
    plot_or_print(example_farm, example_cluster)

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


Question:
Checks if class already exists.
@param typeDef   The type definition to check if exists.
@return  True if class can be found, false otherwise.

private static boolean classExists(TypeDef typeDef) {
       try {
        Class.forName(typeDef.getFullyQualifiedName());
        return true;
       } catch (ClassNotFoundException e) {
           return false;
       }
    }

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

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

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

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

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

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

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

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

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

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

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

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

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

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

        return $methodCode;
    }

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


Question:
Determines the associated element rule.

@param   <V> value type of element
@param   element     chronological element to be evaluated
@return  element rule
@throws  RuleNotFoundException if a rule cannot be determined

<V> ElementRule<T, V> getRule(ChronoElement<V> element) {

        return this.getChronology().getRule(element);

    }

private function parseRuleDefinition($key, $definition): Rule
    {
        if (is_string($definition)) {

            $parts = preg_split('/:/', $definition, 2);

            $factory_name = $parts[0];
            $parameters = $parts[1] ?? null;

            $parameters = ! is_null($parameters)
                ? explode(',', $parameters)
                : [];

            $factory_name = trim($factory_name);
            $parameters = array_map('trim', $parameters);

            $factory = $this->getRuleFactory($factory_name);

            $name = is_string($key) ? $key : $factory_name;
            $validate = $factory($parameters);

            return new Rule($name, $validate);

        }

        // is_callable must be AFTER is_string, otherwise factories named like a
        // php function can't be used (ex: date).
        if (is_callable($definition)) {

            return new Rule((string) $key, $definition);

        }

        throw new InvalidRuleFormatException($definition);
    }

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


Question: Register the service provider.

public function register()
    {
        parent::register();

        $this->loadExtraRoutes();

        $this->app->register(\Spatie\MediaLibrary\MediaLibraryServiceProvider::class);
        $this->app->register(\Railken\Amethyst\Providers\TaxonomyServiceProvider::class);

        app('amethyst')->pushMorphRelation('taxonomable', 'taxonomable', 'file');

        \Illuminate\Database\Eloquent\Builder::macro('files', function (): MorphMany {
            return app('amethyst')->createMacroMorphRelation($this, \Railken\Amethyst\Models\File::class, 'files', 'model');
        });
    }

public function initialize(Server $server)
    {
        $this->server = $server;
        $server->on('method:GET', [$this, 'httpGet'], 90);
        $server->on('propFind', [$this, 'propFind']);

        $server->xml->namespaceMap[self::NS_CALENDARSERVER] = 'cs';
        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Notifications\\ICollection'] = '{'.self::NS_CALENDARSERVER.'}notification';

        array_push($server->protectedProperties,
            '{'.self::NS_CALENDARSERVER.'}notification-URL',
            '{'.self::NS_CALENDARSERVER.'}notificationtype'
        );
    }

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


Question: convert anchor file to 12 col blast file

def blast(self, blastfile=None, outfile=None):

        from jcvi.formats.blast import BlastSlow, BlastLineByConversion

        if not outfile:
            outfile = self.filename + ".blast"

        if blastfile is not None:
            blasts = BlastSlow(blastfile).to_dict()
        else:
            blasts = None

        fw = must_open(outfile, "w", checkexists=True)
        nlines = 0
        for a, b, id in self.iter_pairs():
            if (a, b) in blasts:
                bline = blasts[(a, b)]
            elif (b, a) in blasts:
                bline = blasts[(b, a)]
            else:
                line = "\t".join((a, b))
                bline = BlastLineByConversion(line, mode="110000000000")

            print(bline, file=fw)
            nlines += 1
        fw.close()

        logging.debug("A total of {0} BLAST lines written to `{1}`."\
                        .format(nlines, outfile))

        return outfile

public function up()
    {
        Schema::table('asset_versions', function (Blueprint $table) {
            $table->float('aspect_ratio', 8, 3)
                ->nullable()
                ->default(null);
        });

        $versions = AssetVersion::all();

        foreach ($versions as $version) {
            $path = storage_path().'/boomcms/assets/'.$version->id;

            if (is_readable($path)) {
                $info = FileInfo::create(new File($path));

                $version->fill([
                    'aspect_ratio' => $info->getAspectRatio(),
                    'width'        => $info->getWidth(),
                    'height'       => $info->getHeight(),
                    'metadata'     => $info->getMetadata(),
                ])->save();
            }
        }
    }

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


Question:
Reflection: Describe all properties

Returns array of all properties and their descriptions.
See describeMachineProperty and getAllMachineProperties.

public function describeAllMachineProperties($having_section = null)
	{
		if ($having_section === null) {
			return $this->properties;
		} else {
			return array_filter($this->properties,
				function($a) use ($having_section) { return !empty($a[$having_section]); });
		}
	}

func Describe(desc string, t *testing.T, wrapper func(*Setup, It)) {
	s := &Setup{beforeEachFns: []func(){}, afterEachFns: []func(){}}
	wrapper(s, func(itDesc string, expectFn func(Expect)) {
		test := Test{
			Description: fmt.Sprintf("%s %s", desc, itDesc),
			T:           t,
			ExpectFn:    expectFn,
			Setup:       s,
		}
		test.Run()
	})

}

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


Question:
prepare names for languages

@param string $languageCode
@return string[] languages name indexed by available language code

private function prepareName($languageCode) {
        foreach ($this->container->getParameter('chill_main.available_languages') as $lang) {
            $names[$lang] = Intl::getLanguageBundle()->getLanguageName($languageCode);
        }

        return $names;
    }

function (lang) {
		if (lang_data[lang] && lang_data[lang].success_callbacks && lang_data[lang].success_callbacks.length) {
			lang_data[lang].success_callbacks.forEach(function (f) {
				f(lang);
			});
		}
	}

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


Question:
Returns one random item, or multiple random items inside a Collection, from the Collection. Returns a new Collection.
@param int  $num
@return \CharlotteDunois\Collect\Collection

function random(int $num = 1) {
        $rand = \array_rand($this->data, $num);
        if(!\is_array($rand)) {
            $rand = array($rand);
        }

        $col = new self();
        foreach($rand as $key) {
            $col->set($key, $this->data[$key]);
        }

        return $col;
    }

public function handleAction(Request $request): Envelope
    {
        $request->attributes->set('pbjx_redact_error_message', false);
        $envelope = EnvelopeV1::create();
        if (!$this->isRequestMethodOk($envelope, $request) || !$this->isContentTypeOk($envelope, $request)) {
            return $envelope;
        }

        if ($request->isMethod('GET')) {
            $json = PbjxToken::urlsafeB64Decode($request->query->get('pbj'));
        } elseif (0 === strpos($request->headers->get('Content-Type'), 'multipart/form-data')) {
            $json = $request->request->get('pbj');
        } else {
            $json = $request->getContent();
        }

        $json = (string)$json;
        $data = json_decode($json, true) ?: [];
        if (!$this->isJsonOk($envelope, $request)) {
            return $envelope;
        }

        $pbjxCategory = $request->attributes->get('pbjx_category');
        if (false !== strpos($pbjxCategory, '_')) {
            $pbjxCategory = str_replace('_', '', $pbjxCategory);
            $request->attributes->set('pbjx_category', $pbjxCategory);
        }

        try {
            $expectedCurie = SchemaCurie::fromString(sprintf(
                '%s:%s:%s:%s',
                $request->attributes->get('pbjx_vendor'),
                $request->attributes->get('pbjx_package'),
                $pbjxCategory,
                $request->attributes->get('pbjx_message')
            ));

            $request->attributes->set('pbjx_curie', $expectedCurie->toString());
            $schemaId = isset($data[Schema::PBJ_FIELD_NAME]) ? SchemaId::fromString($data[Schema::PBJ_FIELD_NAME]) : null;

            /** @var Message $class */
            if (null === $schemaId) {
                $class = MessageResolver::resolveCurie($expectedCurie);
                $schema = $class::schema();
                $schemaId = $schema->getId();
            } else {
                $class = MessageResolver::resolveId($schemaId);
            }

            if ($schemaId->getCurie() !== $expectedCurie) {
                throw new \InvalidArgumentException(
                    sprintf(
                        'The resolved schema [%s] doesn\'t match expected curie [%s].',
                        $schemaId->toString(),
                        $expectedCurie->toString()
                    )
                );
            }
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set('pbjx_input', $data);
        $request->attributes->set('pbjx_bind_unrestricted', $request->attributes->getBoolean('pbjx_bind_unrestricted'));

        try {
            /** @var Command|Event|PbjxRequest $message */
            $message = $class::fromArray($data);
            $message->set('ctx_correlator_ref', $envelope->generateMessageRef());
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set(
            'pbjx_redact_error_message',
            !$request->attributes->getBoolean('pbjx_console')
        );

        if (!$this->isPbjxTokenOk($envelope, $request, $json)) {
            return $envelope;
        }

        // allows for functional tests/postman tests/etc. to post pbjx but
        // not actually run them.  this is most important for commands/events
        // which can change state but for request, you'd typically not use
        // dry run because you need to get a response in order to make assertions.
        if ($request->headers->has('x-pbjx-dry-run')) {
            return $envelope
                ->set('code', Code::OK)
                ->set('http_code', HttpCode::HTTP_ACCEPTED())
                ->set('message_ref', $message->generateMessageRef());
        }

        if ($message instanceof Command) {
            return $this->handleCommand($envelope, $request, $message);
        }

        if ($message instanceof Event) {
            return $this->handleEvent($envelope, $request, $message);
        }

        if ($message instanceof PbjxRequest) {
            return $this->handleRequest($envelope, $request, $message);
        }

        $request->attributes->set('pbjx_redact_error_message', false);
        return $envelope
            ->set('code', Code::INVALID_ARGUMENT)
            ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
            ->set('error_name', 'UnprocessableEntity')
            ->set(
                'error_message',
                sprintf('This service does not allow you to submit [%s] messages.', $schemaId->toString())
            );
    }

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


Question: // NewDefaultRsiForStreamWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with a source data stream

func NewDefaultRsiForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Rsi, err error) {
	ind, err := NewDefaultRsiWithSrcLen(sourceLength)
	priceStream.AddTickSubscription(ind)
	return ind, err
}

def _init_smi(self, graph, access_strings_map):

        smi = []
        for selected_state in sorted(graph.states, key=attrgetter('initial'), reverse=True):
            # Initially gather all transitions of the state into a dictionary
            transitions_map = defaultdict(list)
            for character in self.alphabet:
                destination_state = self._delta(graph, selected_state, character)
                transitions_map[destination_state.stateid].append(character)

            chars_in_smi = []
            sorted_transitions = sorted(
                transitions_map.items(),
                key=lambda x: len(
                    x[1]))

            if len(sorted_transitions) == 1:
                # Just put 1 symbol is enough all other'input_string will be generalized
                # by the guardgen algorithm
                chars_in_smi.append(self.alphabet[0])
            else:
                # Otherwise insert in smi_vector all transitions as explicit except
                # the one from the sink transition where we add just enough
                # explicity transitions to make sure that this state will be
                # selected as the sink state.
                #
                # If no transition has a clear advantage in terms of symbols then
                # just add all transitions in explicit form because it may be the
                # case the guardgen() will generalize in the wrong transition.
                for (_, char_list) in sorted_transitions[:-1]:
                    chars_in_smi += char_list

                sink_chars = len(sorted_transitions[-2][1]) + 1
                chars_in_smi.extend(sorted_transitions[-1][1][:sink_chars])

            access_string = access_strings_map[selected_state.stateid]
            smi.extend([access_string + character for character in chars_in_smi])
        return smi

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


Question: // WithRCSBackendString returns a context with the given sync backend set

func WithRCSBackendString(ctx context.Context, sb string) context.Context {
	if be := rcsBackendFromName(sb); be >= 0 {
		return WithRCSBackend(ctx, be)
	}
	return WithRCSBackend(ctx, Noop)
}

def body
      msg = "Hello.\n\n"
      if job.status == 200
        msg += "Your backup of database #{job.rds_id} is complete.\n"+
          (job.files.empty? ? "" : "Output is at #{job.files.first[:url]}\n")
      else
        msg += "Your backup is incomplete. (job ID #{job.backup_id})\n"
      end
      msg += "Job status: #{job.message}"
    end

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


Question: Sets the brightness of the night light (0-255).

def set_night_light_brightness(self, brightness=200):
        """"""
        self.publish(
            action='set',
            resource='cameras/{}'.format(self.device_id),
            publish_response=False,
            properties={'nightLight': {'brightness': brightness}}
        )

func (ns *nurseryStore) getHeightBucketPath(tx *bbolt.Tx,
	height uint32) (*bbolt.Bucket, *bbolt.Bucket, *bbolt.Bucket) {

	// Retrieve the existing chain bucket for this nursery store.
	chainBucket := tx.Bucket(ns.pfxChainKey)
	if chainBucket == nil {
		return nil, nil, nil
	}

	// Retrieve the existing channel index.
	hghtIndex := chainBucket.Bucket(heightIndexKey)
	if hghtIndex == nil {
		return nil, nil, nil
	}

	// Serialize the provided block height and return the bucket matching
	// the serialized key.
	var heightBytes [4]byte
	byteOrder.PutUint32(heightBytes[:], height)

	return chainBucket, hghtIndex, hghtIndex.Bucket(heightBytes[:])
}

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


Question: Build incidence matrix into self.C

def incidence(self):
        """"""
        self.C = \
            spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\
            spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd')

def _apply_correction_on_genes(genes,
                               pathway_column_names,
                               pathway_definitions):

    gene_row_names = index_element_map(genes)
    membership_matrix = initialize_membership_matrix(
        genes, pathway_definitions)
    crosstalk_corrected_index_map = maximum_impact_estimation(
        membership_matrix)

    updated_pathway_definitions = _update_pathway_definitions(
        crosstalk_corrected_index_map,
        gene_row_names, pathway_column_names)
    return updated_pathway_definitions

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


Question: Reset the executor queue channel to an empty state.

async def clear_queue(self):
        """"""
        conn = await self._make_connection()
        try:
            script = """
                local keys = redis.call('KEYS', ARGV[1])
                redis.call('DEL', unpack(keys))
            """
            await conn.eval(
                script,
                keys=[],
                args=['*{}*'.format(settings.FLOW_MANAGER['REDIS_PREFIX'])],
            )
        finally:
            conn.close()

def clear(self, autoBuild=True):

        for action in self._actionGroup.actions():
            self._actionGroup.removeAction(action)

        action = QAction('', self)
        action.setObjectName('place_holder')
        self._actionGroup.addAction(action)
        if autoBuild:
            self.rebuild()

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


Question:
// Receive waits for the response promised by the future and returns a map of
// transaction hashes to an associated data structure with information about the
// transaction for all transactions in the memory pool.

func (r FutureGetRawMempoolVerboseResult) Receive() (map[string]btcjson.GetRawMempoolVerboseResult, error) {
	res, err := receiveFuture(r)
	if err != nil {
		return nil, err
	}

	// Unmarshal the result as a map of strings (tx shas) to their detailed
	// results.
	var mempoolItems map[string]btcjson.GetRawMempoolVerboseResult
	err = json.Unmarshal(res, &mempoolItems)
	if err != nil {
		return nil, err
	}
	return mempoolItems, nil
}

def find_card_bundles(provider: Provider, deck: Deck) -> Optional[Iterator]:
    ''''''

    if isinstance(provider, RpcNode):
        if deck.id is None:
            raise Exception("deck.id required to listtransactions")

        p2th_account = provider.getaccount(deck.p2th_address)
        batch_data = [('getrawtransaction', [i["txid"], 1]) for
                      i in provider.listtransactions(p2th_account)]
        result = provider.batch(batch_data)

        if result is not None:
            raw_txns = [i['result'] for i in result if result]

        else:
            raise EmptyP2THDirectory({'error': 'No cards found on this deck.'})

    else:
        if deck.p2th_address is None:
            raise Exception("deck.p2th_address required to listtransactions")

        try:
            raw_txns = (provider.getrawtransaction(i, 1) for i in
                        provider.listtransactions(deck.p2th_address))
        except TypeError:
            raise EmptyP2THDirectory({'error': 'No cards found on this deck.'})

    return (card_bundler(provider, deck, i) for i in raw_txns)

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


Question: Creates a request from a method function call.

def make_request(self, method, *args, **kwargs):
    """"""
    if args and not use_signature:
        raise NotImplementedError("Only keyword arguments allowed in Python2")

    new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()}

    if use_signature:
        new_args = tuple(unwrap(value) for value in args)
        bound_args = method.signature.bind(
            unwrap(self), *new_args, **new_kwargs).arguments

        # if we encounter any Enum arguments, replace them with their value
        def translate_enum(arg):
            return arg.value if isinstance(arg, Enum) else arg

        for k in bound_args:
            if isinstance(bound_args[k], str):
                continue
            if isinstance(bound_args[k], dict):
                continue

            try:
                x = [translate_enum(arg) for arg in bound_args[k]]
                bound_args[k] = x
            except TypeError:
                bound_args[k] = translate_enum(bound_args[k])

        # replace `self` with the correct keyword
        new_kwargs = {(kw if kw != 'self' else method.field_name): v
                      for kw, v in bound_args.items()}
        # args = tuple(x.value if isinstance(x, Enum) else x for x in args)

    else:
        new_kwargs[self.field_name] = unwrap(self)

    return method.request_type(**new_kwargs)

public HttpRequest buildPatchRequest(GenericUrl url, HttpContent content) throws IOException {
    return buildRequest(HttpMethods.PATCH, url, content);
  }

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


Question:
Removes a permission from the driver for a caller

@param \BeatSwitch\Lock\Callers\Caller $caller
@param \BeatSwitch\Lock\Permissions\Permission
@return void

public function removeCallerPermission(Caller $caller, Permission $permission)
    {
        // Remove permissions which match the action and resource
        $this->permissions[$this->getCallerKey($caller)] = array_filter(
            $this->getCallerPermissions($caller),
            function (Permission $callerPermission) use ($permission) {
                // Only keep permissions which don't exactly match the one which we're trying to remove.
                return ! $callerPermission->matchesPermission($permission);
            }
        );
    }

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

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

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

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

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


Question: // Begin move of file or directory, from/to KBFS only

func (c SimpleFSClient) SimpleFSMove(ctx context.Context, __arg SimpleFSMoveArg) (err error) {
	err = c.Cli.Call(ctx, "keybase.1.SimpleFS.simpleFSMove", []interface{}{__arg}, nil)
	return
}

public function setLastModifiedTime(PhingFile $f, $time)
    {
        $path = $f->getPath();
        $success = @touch($path, $time);
        if (!$success) {
            throw new IOException("Could not touch '" . $path . "' due to: $php_errormsg");
        }
    }

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


Question:
explainScore returns an explanation of how the string distance was
computed.

@param S StringWrapper
@param T StringWrapper
@return String

public String explainScore(StringWrapper s, StringWrapper t) {
	String S = s.unwrap(),
	  T = t.unwrap();
    StringBuffer buff = new StringBuffer();
    buff.append("\n****TagLinkToken****\n");
    buff.append("Si=" + S + ", Tj=" + T + "\n");
    double totalScore = 0.0;
    if (S.equals(T)) {
      matched = S.length();
      buff.append("Sij=1.0");
    }
    else {
      sSize = S.length();
      tSize = T.length();
      // let S be the biggest token
      if (sSize < tSize) {
        String tmp1 = S;
        S = T;
        T = tmp1;
        double tmp2 = sSize;
        sSize = tSize;
        tSize = tmp2;
      }
      ArrayList candidateList = algorithm1(S, T);
      sortList(candidateList);
      buff.append("Common characteres:\n");
      buff.append("Si\tTj\tScore_ij(Si,Tj)\n");
      matched = 0;
      HashMap tMap = new HashMap(),
          uMap = new HashMap();
      java.util.Iterator it = candidateList.iterator();
      while (it.hasNext()) {
        TagLink.Candidates actualCandidates = (TagLink.Candidates) it.next();
        Integer sPos = new Integer(actualCandidates.getTPos()),
            tPos = new Integer(actualCandidates.getUPos());
        if ( (!tMap.containsKey(sPos)) &&
            (!uMap.containsKey(tPos))) {
          double actualScore = actualCandidates.getScore();
          totalScore += actualScore;
          tMap.put(sPos, null);
          uMap.put(tPos, null);
          buff.append(S.charAt(sPos.intValue()) + "\t" + T.charAt(tPos.intValue()) +
                      "\t" + round(actualScore) + "\n");
          matched++;
        }
      }
      totalScore = (totalScore / ( (double) sSize) + totalScore / ( (double) tSize)) / 2.0;
      System.out.println("score " + totalScore);
      buff.append("Score_ij(S,T)=" + round(winkler(totalScore, S, T)));
      buff.append("\nMatched characters=" + matched);
    }
    return buff.toString();
  }

function speechTreeApi(options) {
  if (!options.speechClassifier) {
    throw TypeError('speech classifier must be specified');
  }

  if (typeof options.speechClassifier != 'function') {
    throw TypeError('speech classifier must be a function');
  }

  const router = express.Router();
  const apiUrl = '/' + settings.apiUrl.split('/').pop();

  router.get(`${apiUrl}/label`, async (req, res) => {
    const sentence = req.query.sentence;

    if (!sentence) {
      res.status(400);
      return res.send('sentence must be provided');
    }

    let label = options.speechClassifier(sentence);

    if (!label) {
      res.status(404);
      return res.send('label not found');
    }

    if (typeof label.then == 'function' &&
        typeof label.catch == 'function') {
      label = await label;
    }

    if (typeof label != 'string') {
      throw TypeError('label must be a string');
    }

    res.status(200);
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ label }));
  });

  return router;
}

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


Question: Run filtering on the input call file, handling SNPs and indels separately.

def run(call_file, ref_file, vrn_files, data):

    algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1]))
    if includes_missingalt(data):
        logger.info("Removing variants with missing alts from %s." % call_file)
        call_file = gatk_remove_missingalt(call_file, data)

    if "gatkcnn" in dd.get_tools_on(data):
        return _cnn_filter(call_file, vrn_files, data)
    elif config_utils.use_vqsr(algs, call_file):
        if vcfutils.is_gvcf_file(call_file):
            raise ValueError("Cannot force gVCF output with joint calling using tools_on: [gvcf] and use VQSR. "
                             "Try using cutoff-based soft filtering with tools_off: [vqsr]")
        snp_file, indel_file = vcfutils.split_snps_indels(call_file, ref_file, data["config"])
        snp_filter_file = _variant_filtration(snp_file, ref_file, vrn_files, data, "SNP",
                                              vfilter.gatk_snp_cutoff)
        indel_filter_file = _variant_filtration(indel_file, ref_file, vrn_files, data, "INDEL",
                                                vfilter.gatk_indel_cutoff)
        orig_files = [snp_filter_file, indel_filter_file]
        out_file = "%scombined.vcf.gz" % os.path.commonprefix(orig_files)
        combined_file = vcfutils.combine_variant_files(orig_files, out_file, ref_file, data["config"])
        return combined_file
    else:
        snp_filter = vfilter.gatk_snp_cutoff(call_file, data)
        indel_filter = vfilter.gatk_indel_cutoff(snp_filter, data)
        return indel_filter

def npz_convert(self, infile, item):
        """"""
        data = np.load(infile)
        labels = self._labels(data)
        features = data['features']
        self._write(item, labels, features)

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


Question:
Generates an group template element

@param array $options The options for group template
@return string The generated group template

protected function _groupTemplate($options)
    {
        $groupTemplate = $options['options']['type'] . 'FormGroup';
        if (!$this->templater()->get($groupTemplate)) {
            $groupTemplate = 'formGroup';
        }

        return $this->formatTemplate($groupTemplate, [
            'input' => $options['input'],
            'label' => $options['label'],
            'error' => $options['error'],
            'templateVars' => $this->_processTemplateVars($options)
        ]);
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
create directory if necessary

    :param dst:

def create_dir(dst):

    directory = os.path.dirname(dst)
    if directory and not os.path.exists(directory):
        os.makedirs(directory)

def init_logger
      @logger = case @path
                when STDOUT_STREAM then Logger.new(STDOUT)
                when STDERR_STREAM then Logger.new(STDERR)
                else Logger.new(File.open(@path, 'a'))
                end
      @logger.datetime_format = @datetime_format
      @logger.sev_threshold = @threshold unless @severities.any?
      @logger.formatter = @formatter unless @formatter.nil?
    end

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


Question: // GetResourcePool returns a resource pool, or nil if not found

func (f *Facade) GetResourcePool(ctx datastore.Context, id string) (*pool.ResourcePool, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetResourcePool"))
	glog.V(2).Infof("Facade.GetResourcePool: id=%s", id)
	var entity pool.ResourcePool
	err := f.poolStore.Get(ctx, pool.Key(id), &entity)
	if datastore.IsErrNoSuchEntity(err) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	f.calcPoolCapacity(ctx, &entity)

	return &entity, nil
}

public function getWorker($workerName)
    {
        foreach ($this->workers as $worker) {

            if ($workerName === $worker['callableName']) {
                return $worker;
            }
        }

        throw new WorkerDoesNotExistException();
    }

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


Question:
Automatically generated run method

@param Request $request
@return Response

public function run(Request $request) {
		$file = $request->files->get('file');

		try {
			// validate: upload progress
			if (!$file->isValid()) {
				throw new FileException($file->getErrorMessage());
			}

			// validate: mime type
			$mimeTypes = ['image/png', 'image/jpeg', 'image/jpg', 'video/mp4', 'video/quicktime'];
			if (!in_array($file->getClientMimeType(), $mimeTypes)) {
				throw new FileException('No matching mime type');
			}

			// validate: extension
			$exts = ['png', 'jpg', 'jpeg', 'mp4', 'mov'];
			if (!in_array($file->getClientOriginalExtension(), $exts)) {
				throw new FileException('No matching extension');
			}

			// move uploaded file
			$slugifier = new Slugify();
			$fileName = $file->getClientOriginalName();
			$fileName = str_replace('.' . $file->getClientOriginalExtension(), '', $fileName);
			$fileName = $slugifier->slugify($fileName) . '.' . $file->getClientOriginalExtension();
			$file->move($this->getModule()->getUploadPath()->toString(), $fileName);
			$payload = new Success([
				'filename' => $fileName,
				'url' => $this->getModule()->getUploadUrl() . '/' . urlencode($fileName)
			]);
		} catch (FileException $e) {
			$payload = new Failed(['error' => $e->getMessage()]);
		}

		return $this->responder->run($request, $payload);
	}

public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
		this.doProcess(req, res);
	}

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


Question:
Sort and clip the source catalog based on the flux range specified
        by the user. It keeps a copy of the original full list in order to
        support iteration.

def sortSkyCatalog(self):

        if len(self.all_radec_orig[2].nonzero()[0]) == 0:
            warn_str = "Source catalog NOT trimmed by flux/mag. No fluxes read in for sources!"
            print('\nWARNING: ',warn_str,'\n')
            log.warning(warn_str)
            return
        clip_catalog = False
        clip_prefix = ''
        for k in sortKeys:
            for p in self.pars.keys():
                pindx = p.find(k)
                if pindx >= 0 and self.pars[p] is not None:
                    log.info('found a match for %s to %s'%(
                                str(p),str(self.pars[p])))
                    # find prefix (if any)
                    clip_prefix = p[:pindx].strip()
                    #Only clip the catalog if one of the keys is specified
                    # in the catalog parameters, not the source finding pars
                    if clip_prefix and 'units' not in p:
                        clip_catalog = True
                        break
            if clip_catalog:
                break
        all_radec = None

        if clip_catalog:

            # Start by clipping by any specified flux range
            if self.pars[clip_prefix+'maxflux'] is not None or \
                    self.pars[clip_prefix+'minflux'] is not None:
                clip_catalog = True
                if self.pars[clip_prefix+'minflux'] is not None:
                    fluxmin = self.pars[clip_prefix+'minflux']
                else:
                    fluxmin = self.all_radec[2].min()

                if self.pars[clip_prefix+'maxflux'] is not None:
                    fluxmax = self.pars[clip_prefix+'maxflux']
                else:
                    fluxmax = self.all_radec[2].max()

                # apply flux limit clipping
                minindx = self.all_radec_orig[2] >= fluxmin
                maxindx = self.all_radec_orig[2] <= fluxmax
                flux_indx = np.bitwise_and(minindx,maxindx)
                all_radec = []
                all_radec.append(self.all_radec_orig[0][flux_indx])
                all_radec.append(self.all_radec_orig[1][flux_indx])
                all_radec.append(self.all_radec_orig[2][flux_indx])
                all_radec.append(np.arange(len(self.all_radec_orig[0][flux_indx])))

            if clip_prefix+'nbright' in self.pars and \
                    self.pars[clip_prefix+'nbright'] is not None:
                clip_catalog = True

                nbright = self.pars[clip_prefix+'nbright']

                # pick out only the brightest 'nbright' sources
                if self.pars[clip_prefix+'fluxunits'] == 'mag':
                    nbslice = slice(None,nbright)
                else:
                    nbslice = slice(nbright,None)

                if all_radec is None:
                    # work on copy of all original data
                    all_radec = copy.deepcopy(self.all_radec_orig)
                # find indices of brightest
                nbright_indx = np.argsort(all_radec[2])[nbslice]
                self.all_radec[0] = all_radec[0][nbright_indx]
                self.all_radec[1] = all_radec[1][nbright_indx]
                self.all_radec[2] = all_radec[2][nbright_indx]
                self.all_radec[3] = np.arange(len(all_radec[0][nbright_indx]))

            else:
                if all_radec is not None:
                    self.all_radec = copy.deepcopy(all_radec)

function addUrl(when, feed) {
  if (!types.check(feed, 'feed') && !types.check(feed, ['feed']))
    throw Error('sandcrawler.spider.url(s): wrong argument.');

  var a = !(feed instanceof Array) ? [feed] : feed,
      c = !this.state.running ? this.initialBuffer.length : this.index,
      job,
      i,
      l;

  for (i = 0, l = a.length; i < l; i++) {
    job = createJob(a[i]);

    // Don't add if already at limit
    if (this.options.limit && c >= this.options.limit)
      break;

    if (!this.state.running) {
      this.initialBuffer[when === 'later' ? 'push' : 'unshift'](job);
    }
    else {
      this.queue[when === 'later' ? 'push' : 'unshift'](job);
      this.emit('job:add', job);
    }
  }

  return this;
}

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


Question: Boot the service provider.

public function boot()
    {
        if (!$this->isLumen()) {
            $this->publishes([
                $this->getConfigPath() => config_path('acl.php'),
            ], 'config');
        }

        $this->app->make(DoctrineManager::class)->onResolve(function () {
            $this->definePermissions(
                $this->app->make(Gate::class),
                $this->app->make(PermissionManager::class)
            );
        });
    }

public void start(BundleContext context) throws Exception
    {
        this.log(context, LogService.LOG_INFO, "Starting and registering the (repository) " + this.getClass().getName() + " ClassService ");

        bundleContext = context;

        if (context != null)
            context.registerService(ClassFinder.class.getName(), this, null);	// Should be only one of these
    }

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


Question:
{@inheritDoc}
<p>
The method will set the owned partition set in a CAS loop because
this method can be called concurrently.

@Override
    public void reloadOwnedPartitions() {
        final IPartitionService partitionService = nodeEngine.getPartitionService();
        for (; ; ) {
            final PartitionIdSet expected = ownedPartitions.get();
            final Collection<Integer> partitions = partitionService.getMemberPartitions(nodeEngine.getThisAddress());
            final PartitionIdSet newSet = immutablePartitionIdSet(partitionService.getPartitionCount(), partitions);
            if (ownedPartitions.compareAndSet(expected, newSet)) {
                return;
            }
        }
    }

def square_batch_region(data, region, bam_files, vrn_files, out_file):

    from bcbio.variation import sentieon, strelka2
    if not utils.file_exists(out_file):
        jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)
        if jointcaller in ["%s-joint" % x for x in SUPPORTED["general"]]:
            _square_batch_bcbio_variation(data, region, bam_files, vrn_files, out_file, "square")
        elif jointcaller in ["%s-merge" % x for x in SUPPORTED["general"]]:
            _square_batch_bcbio_variation(data, region, bam_files, vrn_files, out_file, "merge")
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["gatk"]]:
            gatkjoint.run_region(data, region, vrn_files, out_file)
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["gvcf"]]:
            strelka2.run_gvcfgenotyper(data, region, vrn_files, out_file)
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["sentieon"]]:
            sentieon.run_gvcftyper(vrn_files, out_file, region, data)
        else:
            raise ValueError("Unexpected joint calling approach: %s." % jointcaller)
    if region:
        data["region"] = region
    data = _fix_orig_vcf_refs(data)
    data["vrn_file"] = out_file
    return [data]

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


Question: // SetCacheNodeType sets the CacheNodeType field's value.

func (s *Snapshot) SetCacheNodeType(v string) *Snapshot {
	s.CacheNodeType = &v
	return s
}

@Override
	public void clearCache() {
		entityCache.clearCache(CommerceShippingFixedOptionRelImpl.class);

		finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

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


Question:
TODO

@return array

public function getModels($filePath = false)
    {
        $list = array();
        foreach ($this->getModelsFolder() as $model) {
            $folder = $this->directory . "/$model";
            if (is_dir($folder)) {
                $files = scandir($folder);
                foreach ($files as $file) {
                    if (strpos($file, '.php') !== false) {
                        if($filePath) {
                            $list[] = $folder . '/' . $file;
                        } else {
                            $list[] = substr($file, 0, -4);
                        }
                    }
                }
            }
        }
        return $list;
    }

function yy_r25(){
    $this->_retvalue = self::escape_end_tag($this->yystack[$this->yyidx + 0]->minor);
    }

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


Question: .google.privacy.dlp.v2.BucketingConfig bucketing_config = 6;

public com.google.privacy.dlp.v2.BucketingConfigOrBuilder getBucketingConfigOrBuilder() {
    if (transformationCase_ == 6) {
      return (com.google.privacy.dlp.v2.BucketingConfig) transformation_;
    }
    return com.google.privacy.dlp.v2.BucketingConfig.getDefaultInstance();
  }

protected static function define_properties() {
        return array(
            'name' => array(
                'type' => PARAM_TEXT,
                'description' => 'The purpose name.',
            ),
            'description' => array(
                'type' => PARAM_RAW,
                'description' => 'The purpose description.',
                'null' => NULL_ALLOWED,
                'default' => '',
            ),
            'descriptionformat' => array(
                'choices' => array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN),
                'type' => PARAM_INT,
                'default' => FORMAT_HTML
            ),
            'lawfulbases' => array(
                'type' => PARAM_TEXT,
                'description' => 'Comma-separated IDs matching records in tool_dataprivacy_lawfulbasis.',
            ),
            'sensitivedatareasons' => array(
                'type' => PARAM_TEXT,
                'description' => 'Comma-separated IDs matching records in tool_dataprivacy_sensitive',
                'null' => NULL_ALLOWED,
                'default' => ''
            ),
            'retentionperiod' => array(
                'type' => PARAM_ALPHANUM,
                'description' => 'Retention period. ISO_8601 durations format (as in DateInterval format).',
                'default' => '',
            ),
            'protected' => array(
                'type' => PARAM_INT,
                'description' => 'Data retention with higher precedent over user\'s request to be forgotten.',
                'default' => '0',
            ),
        );
    }

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


Question:
Get a page of the account's history
    Returns the list of account operations on success
    Returns {'error': ...} on error

def get_account_history_page(address, page, hostport=None, proxy=None):

    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    page_schema = {
        'type': 'object',
        'properties': {
            'history': {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': ACCOUNT_SCHEMA_PROPERTIES,
                    'required': ACCOUNT_SCHEMA_REQUIRED,
                },
            },
        },
        'required': [
            'history'
        ],
    }

    schema = json_response_schema(page_schema)

    try:
        resp = proxy.get_account_history(address, page)
        resp = json_validate(schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    return resp['history']

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

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

        }*/
        return $result;
    }

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


Question:
Get the value for a floating point uniform vector.
@param key name of uniform to get.
@return float array with value of named uniform.
@throws IllegalArgumentException if key is not in uniform descriptor.

public float[] getFloatVec(String key)
    {
        float[] vec = NativeLight.getFloatVec(getNative(), key);
        if (vec == null)
            throw new IllegalArgumentException("key " + key + " not found in light");
        return vec;
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
(advanced)

 Shortcut for wi.fields['__command__'] = x

 __command__ is read by the 'cursor' and the 'iterator' expressions
 when a workitem reaches it (apply and reply).

def command=(com)

      com = com.is_a?(Array) ? com : com.split(' ')
      com = [ com.first, com.last ]
      com[1] = com[1].to_i if com[1] and com[0] != 'jump'

      h.fields['__command__'] = com
    end

private Context translateSingleAssignment(WyilFile.LVal lval, Expr rval, Context context) {

		// FIXME: this method is a bit of a kludge. It would be nicer,
		// eventually, to have all right-hand side expression represented in
		// WyTP directly. This could potentially be done by including an update
		// operation in WyTP ... ?

		switch (lval.getOpcode()) {
		case WyilFile.EXPR_arrayaccess:
		case WyilFile.EXPR_arrayborrow:
			return translateArrayAssign((WyilFile.Expr.ArrayAccess) lval, rval, context);
		case WyilFile.EXPR_dereference:
			return translateDereference((WyilFile.Expr.Dereference) lval, rval, context);
		case WyilFile.EXPR_recordaccess:
		case WyilFile.EXPR_recordborrow:
			return translateRecordAssign((WyilFile.Expr.RecordAccess) lval, rval, context);
		case WyilFile.EXPR_variablemove:
		case WyilFile.EXPR_variablecopy:
			return translateVariableAssign((WyilFile.Expr.VariableAccess) lval, rval, context);
		default:
			throw new SyntacticException("unknown lval encountered (" + lval + ")", context.getEnclosingFile().getEntry(),
					lval);
		}
	}

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


Question: Marshall the given parameter object.

public void marshall(AttachInstancesToLoadBalancerRequest attachInstancesToLoadBalancerRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(attachInstancesToLoadBalancerRequest.getLoadBalancerName(), LOADBALANCERNAME_BINDING);
            protocolMarshaller.marshall(attachInstancesToLoadBalancerRequest.getInstanceNames(), INSTANCENAMES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Retrieves the currently logged in AVUser with a valid session,
either from memory or the storage provider, if necessary.

@return AVUser|null

public static function getCurrentUser()
    {
        if (static::$currentUser instanceof AVUser)
        {
            return static::$currentUser;
        }
        $storage = AVClient::getStorage();
        $userData = $storage->get("user");
        if ($userData instanceof AVUser)
        {
            static::$currentUser = $userData;

            return $userData;
        }
        if (isset($userData["id"]) && isset($userData["_sessionToken"]))
        {
            $user = AVUser::create("_User", $userData["id"]);
            unset($userData["id"]);
            $user->_sessionToken = $userData["_sessionToken"];
            unset($userData["_sessionToken"]);
            foreach ($userData as $key => $value)
            {
                $user->set($key, $value);
            }
            $user->_opSetQueue = array();
            static::$currentUser = $user;

            return $user;
        }

        return null;
    }

func main() {
	conf := &cloudstorage.Config{
		Type:       azure.StoreType,
		AuthMethod: azure.AuthKey,
		Bucket:     os.Getenv("AZURE_BUCKET"),
		Project:    os.Getenv("AZURE_PROJECT"),
		TmpDir:     "/tmp/localcache/azure",
		Settings:   make(gou.JsonHelper),
	}

	conf.Settings[azure.ConfKeyAuthKey] = os.Getenv("AZURE_KEY")

	// Should error with empty config
	store, err := cloudstorage.NewStore(conf)
	if err != nil {
		fmt.Println("Could not get azure store ", err)
		os.Exit(1)
	}

	folders, err := store.Folders(context.Background(), cloudstorage.NewQueryForFolders(""))
	if err != nil {
		fmt.Println("Could not get folders ", err)
		os.Exit(1)
	}
	for _, folder := range folders {
		fmt.Println("found folder: ", folder)
	}

	// Create a search query for all objects
	q := cloudstorage.NewQuery("")
	// Create an Iterator
	iter, err := store.Objects(context.Background(), q)
	if err != nil {
		fmt.Println("Could not get iter ", err)
		os.Exit(1)
	}

	for {
		o, err := iter.Next()
		if err == iterator.Done {
			fmt.Println("done, exiting iterator")
			break
		}
		fmt.Println("found object", o.Name())
	}
}

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


Question:
Plot the weights of a specific layer.

    Only really makes sense with convolutional layers.

    Parameters
    ----------
    layer : lasagne.layers.Layer

def plot_conv_weights(layer, figsize=(6, 6)):

    W = layer.W.get_value()
    shape = W.shape
    nrows = np.ceil(np.sqrt(shape[0])).astype(int)
    ncols = nrows

    for feature_map in range(shape[1]):
        figs, axes = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False)

        for ax in axes.flatten():
            ax.set_xticks([])
            ax.set_yticks([])
            ax.axis('off')

        for i, (r, c) in enumerate(product(range(nrows), range(ncols))):
            if i >= shape[0]:
                break
            axes[r, c].imshow(W[i, feature_map], cmap='gray',
                              interpolation='none')
    return plt

protected function getLoader($object, $graph)
    {
        foreach ($this->loaders as $loader) {
            if ($loader->supports($object, $graph)) {
                return $loader;
            }
        }

        return;
    }

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


Question: // EnsureDir ensure directory exists

func EnsureDir(filename string) error {
	fdir := path.Dir(filename)
	if fdir != "" && fdir != filename {
		d, err := os.Stat(fdir)
		if err == nil {
			if !d.IsDir() {
				return fmt.Errorf("filename's dir exists but isn't' a directory: filename:%v dir:%v", filename, fdir)
			}
		} else if os.IsNotExist(err) {
			err := os.MkdirAll(fdir, 0775)
			if err != nil {
				return fmt.Errorf("unable to create path. : filename:%v dir:%v err:%v", filename, fdir, err)
			}
		}
	}
	return nil
}

public static LocalCall<String> mkdir(String path, String mode) {
        return mkdir(path, Optional.empty(), Optional.empty(), Optional.of(mode));
    }

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


Question: ----- Public DBService methods: Namespace management

@Override
    public void createNamespace() {
        // Use a temporary, no-keyspace session
        try (DBConn dbConn = createAndConnectConn(null)) {
            synchronized (m_schemaLock) {
                if (!m_schemaMgr.keyspaceExists(dbConn, m_keyspace)) {
                    m_schemaMgr.createKeyspace(dbConn, m_keyspace);
                }
            }
        }
    }

func (s *RelationalDatabase) SetTags(v []*Tag) *RelationalDatabase {
	s.Tags = v
	return s
}

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


Question: Check if the time that has been typed so far is completely legal, as is.

private boolean isTypedTimeFullyLegal() {
        if (mIs24HourMode) {
            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
            Boolean[] enteredZeros = {false, false, false};
            int[] values = getEnteredTime(enteredZeros);
            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60 && values[2] >= 0 && values[2] < 60);
        } else {
            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
            // legally added at specific times based on the tree's algorithm.
            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
        }
    }

def QA_util_get_real_datelist(start, end):

    real_start = QA_util_get_real_date(start, trade_date_sse, 1)
    real_end = QA_util_get_real_date(end, trade_date_sse, -1)
    if trade_date_sse.index(real_start) > trade_date_sse.index(real_end):
        return None, None
    else:
        return (real_start, real_end)

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


Question: Auto Generated Code

def overlay_gateway_ip_interface_loopback_loopback_id(self, **kwargs):

        config = ET.Element("config")
        overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
        name_key = ET.SubElement(overlay_gateway, "name")
        name_key.text = kwargs.pop('name')
        ip = ET.SubElement(overlay_gateway, "ip")
        interface = ET.SubElement(ip, "interface")
        loopback = ET.SubElement(interface, "loopback")
        loopback_id = ET.SubElement(loopback, "loopback-id")
        loopback_id.text = kwargs.pop('loopback_id')

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Parses the specified JSON string into a parse tree

@param reader JSON text
@return a parse tree of {@link JsonElement}s corresponding to the specified JSON
@throws JsonParseException if the specified text is not valid JSON

public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException {
    try {
      JsonReader jsonReader = new JsonReader(reader);
      JsonElement element = parseReader(jsonReader);
      if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {
        throw new JsonSyntaxException("Did not consume the entire document.");
      }
      return element;
    } catch (MalformedJsonException e) {
      throw new JsonSyntaxException(e);
    } catch (IOException e) {
      throw new JsonIOException(e);
    } catch (NumberFormatException e) {
      throw new JsonSyntaxException(e);
    }
  }

public void marshall(XMLClassifier xMLClassifier, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(xMLClassifier.getName(), NAME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getClassification(), CLASSIFICATION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getCreationTime(), CREATIONTIME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getLastUpdated(), LASTUPDATED_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getRowTag(), ROWTAG_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
打开/关闭透传消息
@param enable 打开/关闭

public void enableReceiveNormalMsg(boolean enable, EnableReceiveNormalMsgHandler handler) {
        HMSAgentLog.i("enableReceiveNormalMsg:enable=" + enable + "  handler=" + StrUtils.objDesc(handler));
        this.enable = enable;
        this.handler = handler;
        connect();
    }

public function display()
    {
        if (!$this->visible) {
            return;
        }

        SwatWidget::display();

        if ($this->alt == '') {
            throw new SwatException(
                'The $alt property of SwatImageButton must be set to an ' .
                    'appropriate value. The "alt" attribute is required in ' .
                    'HTML5 and can not be an empty string.'
            );
        }

        $input_tag = new SwatHtmlTag('input');
        $input_tag->type = 'image';
        $input_tag->id = $this->id;
        $input_tag->name = $this->id;
        $input_tag->value = $this->title;
        $input_tag->alt = $this->alt;
        $input_tag->class = $this->getCSSClassString();

        if (count($this->values)) {
            $input_tag->src = vsprintf($this->image, $this->values);
        } else {
            $input_tag->src = $this->image;
        }

        $input_tag->tabindex = $this->tab_index;
        $input_tag->accesskey = $this->access_key;

        if (!$this->isSensitive()) {
            $input_tag->disabled = 'disabled';
        }

        $input_tag->display();

        if (
            $this->show_processing_throbber ||
            $this->confirmation_message !== null
        ) {
            Swat::displayInlineJavaScript($this->getInlineJavaScript());
        }
    }

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


Question:
This method opens the input and output files and kicks
off the processing.

@param input Name of the input file
@param output Name of the output file
@throws Exception Thrown on file read errors

private static void process(String input, String output) throws Exception
   {
      FileInputStream is = new FileInputStream(input);
      PrintWriter pw = new PrintWriter(new FileWriter(output));

      POIFSFileSystem fs = new POIFSFileSystem(is);
      dumpTree(pw, fs.getRoot(), "", true, true, null);

      is.close();
      pw.flush();
      pw.close();
      fs.close();
   }

private void parseMultipartFormData() {
        String multipartFormDataParser = getSetting(MULTIPART_FORM_DATA_PARSER_SETTING_NAME);
        if (multipartFormDataParser == null) {
            throw new MultipartRequestParseException("The setting name 'multipartFormDataParser' for multipart " +
                    "form data parsing is not specified. Please specify 'multipartFormDataParser' via Aspect so " +
                    "that Translet can parse multipart form data.");
        }

        MultipartFormDataParser parser = getBean(multipartFormDataParser);
        if (parser == null) {
            throw new MultipartRequestParseException("No bean named '" + multipartFormDataParser + "' is defined");
        }
        parser.parse(getRequestAdapter());
    }

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


Question: Timestamp when the story has last been watched or None (local time zone).

def last_seen_local(self) -> Optional[datetime]:
        """"""
        if self._node['seen']:
            return datetime.fromtimestamp(self._node['seen'])

public function all_day() {
    if (!$this->values) {
      return false;
    }
    if (($this->start->format('H:i:s') == '00:00:00' && (!$this->end || ($this->end && $this->end->format('H:i:s') == '00:00:00')))) {
      return true;
    }
    return false;
  }

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