Question:
// getAzureUploadID - returns new upload ID which is hex encoded 8 bytes random value.
// this 8 byte restriction is needed because Azure block id has a restriction of length
// upto 8 bytes.

func getAzureUploadID() (string, error) {
	var id [8]byte

	n, err := io.ReadFull(rand.Reader, id[:])
	if err != nil {
		return "", err
	}
	if n != len(id) {
		return "", fmt.Errorf("Unexpected random data size. Expected: %d, read: %d)", len(id), n)
	}

	return hex.EncodeToString(id[:]), nil
}

func (c *chunkedIntCoder) Write(w io.Writer) (int, error) {
	bufNeeded := binary.MaxVarintLen64 * (1 + len(c.chunkLens))
	if len(c.buf) < bufNeeded {
		c.buf = make([]byte, bufNeeded)
	}
	buf := c.buf

	// convert the chunk lengths into chunk offsets
	chunkOffsets := modifyLengthsToEndOffsets(c.chunkLens)

	// write out the number of chunks & each chunk offsets
	n := binary.PutUvarint(buf, uint64(len(chunkOffsets)))
	for _, chunkOffset := range chunkOffsets {
		n += binary.PutUvarint(buf[n:], chunkOffset)
	}

	tw, err := w.Write(buf[:n])
	if err != nil {
		return tw, err
	}

	// write out the data
	nw, err := w.Write(c.final)
	tw += nw
	if err != nil {
		return tw, err
	}
	return tw, nil
}

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


Question:
Add the cumulative constraints for each link.

Full-duplex links are considered, two cumulative constraints are defined per link by looking at
the migration direction for each link on the migration path.

@param rp the reconfiguration problem

private void addLinkConstraints(ReconfigurationProblem rp) {

        // Links limitation
        List<Task> tasksListUp = new ArrayList<>();
        List<Task> tasksListDown = new ArrayList<>();
        List<IntVar> heightsListUp = new ArrayList<>();
        List<IntVar> heightsListDown = new ArrayList<>();

        for (Link l : net.getLinks()) {

            for (VM vm : rp.getVMs()) {
                VMTransition a = rp.getVMAction(vm);

                if (a instanceof RelocatableVM
                        && !a.getDSlice().getHoster().isInstantiatedTo(a.getCSlice().getHoster().getValue())) {

                    Node src = source.getMapping().getVMLocation(vm);
                    Node dst = rp.getNode(a.getDSlice().getHoster().getValue());
                    List<Link> path = net.getRouting().getPath(src, dst);

                    // Check first if the link is on migration path
                    if (path.contains(l)) {
                        // Get link direction
                        LinkDirection linkDirection = net.getRouting().getLinkDirection(src, dst, l);
                        // UpLink
                        if (linkDirection == LinkDirection.UPLINK) {
                            tasksListUp.add(((RelocatableVM) a).getMigrationTask());
                            heightsListUp.add(((RelocatableVM) a).getBandwidth());
                        }
                        // DownLink
                        else {
                            tasksListDown.add(((RelocatableVM) a).getMigrationTask());
                            heightsListDown.add(((RelocatableVM) a).getBandwidth());
                        }
                    }
                }
            }
            if (!tasksListUp.isEmpty()) {

                // Post the cumulative constraint for the current UpLink
                csp.post(csp.cumulative(
                        tasksListUp.toArray(new Task[tasksListUp.size()]),
                        heightsListUp.toArray(new IntVar[heightsListUp.size()]),
                        csp.intVar(l.getCapacity()),
                        true
                ));

                tasksListUp.clear();
                heightsListUp.clear();
            }
            if (!tasksListDown.isEmpty()) {

                // Post the cumulative constraint for the current DownLink
                csp.post(csp.cumulative(
                        tasksListDown.toArray(new Task[tasksListDown.size()]),
                        heightsListDown.toArray(new IntVar[heightsListDown.size()]),
                        csp.intVar(l.getCapacity()),
                        true
                ));

                tasksListDown.clear();
                heightsListDown.clear();
            }
        }
    }

func SetOrdererEnv(cmd *cobra.Command, args []string) {
	// read in the legacy logging level settings and, if set,
	// notify users of the FABRIC_LOGGING_SPEC env variable
	var loggingLevel string
	if viper.GetString("logging_level") != "" {
		loggingLevel = viper.GetString("logging_level")
	} else {
		loggingLevel = viper.GetString("logging.level")
	}
	if loggingLevel != "" {
		mainLogger.Warning("CORE_LOGGING_LEVEL is no longer supported, please use the FABRIC_LOGGING_SPEC environment variable")
	}
	// need to init logging here as cobra does not currently support
	// chaining PersistentPreRun functions
	loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC")
	flogging.InitFromSpec(loggingSpec)
	// set the orderer environment from flags
	viper.Set("orderer.tls.rootcert.file", caFile)
	viper.Set("orderer.tls.clientKey.file", keyFile)
	viper.Set("orderer.tls.clientCert.file", certFile)
	viper.Set("orderer.address", OrderingEndpoint)
	viper.Set("orderer.tls.serverhostoverride", ordererTLSHostnameOverride)
	viper.Set("orderer.tls.enabled", tlsEnabled)
	viper.Set("orderer.tls.clientAuthRequired", clientAuth)
	viper.Set("orderer.client.connTimeout", connTimeout)
}

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


Question: // Stack returns the stack of frames, innermost first.

func (e *EvalError) Stack() []*Frame {
	var stack []*Frame
	for fr := e.Frame; fr != nil; fr = fr.parent {
		stack = append(stack, fr)
	}
	return stack
}

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

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


Question: ceil a number to within a given rounding accuracy

def ceil_nearest(x, dx=1):

    precision = get_sig_digits(dx)
    return round(math.ceil(float(x) / dx) * dx, precision)

public void setXi(double xi)
    {
        if(xi <= 0 || xi >= 1 || Double.isNaN(xi))
            throw new ArithmeticException("xi must be in the range (0, 1) not " + xi);
        this.xi = xi;
        this.one_min_xi = 1.0 - xi;
    }

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


Question:
Initializes database driver for databases with JDBC driver version lower than 4.0

@param databaseType Name of target database from JDBC connection string

static void initializeDatabaseDriver(String databaseType) {
    String driverClass = System.getProperty(JDBC_DRIVER_CLASS_KEY_PREFIX + databaseType);
    if (driverClass != null) {
      Log.debug("Loading " + driverClass + " to initialize database of type " + databaseType);
      try {
        Class.forName(driverClass);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException("Connection to '" + databaseType + "' database is not possible due to missing JDBC driver. " +
                "User specified driver class: " + driverClass, e);
      }
      return;
    }
    // use built-in defaults
    switch (databaseType) {
      case HIVE_DB_TYPE:
        try {
          Class.forName(HIVE_JDBC_DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException("Connection to HIVE database is not possible due to missing JDBC driver.", e);
        }
        break;
      case NETEZZA_DB_TYPE:
        try {
          Class.forName(NETEZZA_JDBC_DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException("Connection to Netezza database is not possible due to missing JDBC driver.", e);
        }
        break;
      default:
        //nothing to do
    }
  }

public void removePath(int pathId) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            // remove any enabled overrides with this path
            statement = sqlConnection.prepareStatement(
                "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE +
                    " WHERE " + Constants.ENABLED_OVERRIDES_PATH_ID + " = ?"
            );
            statement.setInt(1, pathId);
            statement.executeUpdate();
            statement.close();

            // remove path
            statement = sqlConnection.prepareStatement(
                "DELETE FROM " + Constants.DB_TABLE_PATH
                    + " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            statement.setInt(1, pathId);
            statement.executeUpdate();
            statement.close();

            //remove path from responseRequest
            statement = sqlConnection.prepareStatement(
                "DELETE FROM " + Constants.DB_TABLE_REQUEST_RESPONSE
                    + " WHERE " + Constants.REQUEST_RESPONSE_PATH_ID + " = ?"
            );
            statement.setInt(1, pathId);
            statement.executeUpdate();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (Exception e) {
            }
        }
    }

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


Question:
Creates a new key

        :type key_name: string
        :param key_name: The name of the key to create

        :rtype: :class:`boto.file.key.Key`
        :returns: An instance of the newly created key object

def new_key(self, key_name=None, key_type=Key.KEY_REGULAR_FILE):

        if key_name == '-':
            return Key(self.name, '-', key_type=Key.KEY_STREAM_WRITABLE)
        else:
            dir_name = os.path.dirname(key_name)
            if dir_name and not os.path.exists(dir_name):
                os.makedirs(dir_name)
            fp = open(key_name, 'wb')
            return Key(self.name, key_name, fp)

public static function fromGlobals()
  {
    static $instance;

    if (!isset($instance)) {

      $method   = $_SERVER['REQUEST_METHOD'] ?? 'GET';
      $headers  = function_exists('getallheaders') ? getallheaders() : [];
      $uri      = self::getUriFromGlobals();
      $body     = Stream::from(fopen('php://input', 'r+'));
      $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1';

      $instance = (new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER))
        ->withCookieParams($_COOKIE)
        ->withQueryParams($_GET)
        ->withUploadedFiles($_FILES);

      $contentType = $instance->getContentType();
      if ($method === 'POST' && (
        false !== stripos($contentType, 'application/x-www-form-urlencoded') ||
        false !== stripos($contentType, 'multipart/form-data')
      )) {
        $instance = $instance->withParsedBody($_POST);
      }
    }

    return $instance;
  }

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


Question: Reset atime/mtime on all files to prevent systemd swipes only part of the files in the /tmp.

def reset_time(path='.', amt=None):
    '''

    '''
    if not amt:
        amt = int(time.time())
    for fname in os.listdir(path):
        fname = os.path.join(path, fname)
        if os.path.isdir(fname):
            reset_time(fname, amt=amt)
        os.utime(fname, (amt, amt,))

def sweep(self):
        '''

        '''
        if self.max_age < time.time() - self.timestamp:
            self.clear()
            self.timestamp = time.time()
        else:
            paterns = list(self.cache.values())
            paterns.sort()
            for idx in range(self.clear_size):
                del self.cache[paterns[idx][2]]

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


Question: // SetConfigurationId sets the ConfigurationId field's value.

func (s *UpdateApplicationInput) SetConfigurationId(v string) *UpdateApplicationInput {
	s.ConfigurationId = &v
	return s
}

def _add_discovery_config(self):

    lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'],
                  discovery_service.DiscoveryService.API_CONFIG['version'])
    self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG

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


Question:
Verifies that a webelement previously found {@code isSelected}

@param index
@param isSelected

@Then("^the element on index '(\\d+?)' (IS|IS NOT) selected$")
    public void assertSeleniumIsSelected(Integer index, Boolean isSelected) {
        assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
                .hasAtLeast(index);
        assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isSelected()).as(
                "Unexpected element selected property").isEqualTo(isSelected);
    }

def select(self, node):

        child_object = self.translate(node.child)
        where_block = node.conditions
        if child_object.where_block:
              where_block = '({0}) AND ({1})'\
                  .format(child_object.where_block, node.conditions)
        child_object.where_block = where_block
        if not child_object.select_block:
            child_object.select_block = str(node.attributes)
        return child_object

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


Question: Marshall the given parameter object.

public void marshall(CreateWorkerBlockRequest createWorkerBlockRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(createWorkerBlockRequest.getWorkerId(), WORKERID_BINDING);
            protocolMarshaller.marshall(createWorkerBlockRequest.getReason(), REASON_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:
Generate a diff changelog from SchemaDiff object.

@param SchemaDiff $schemaDiff
@param LiquibaseOutput|LiquibaseOutputOptions|null $output
@return \DOMDocument|mixed

public function diffChangeLogFromSchemaDiff(SchemaDiff $schemaDiff, $output = null)
    {
        $output = $this->sanitizeOutputParameter($output);

        $output->started($this->em);

        foreach ($schemaDiff->newNamespaces as $newNamespace) {
            $output->createSchema($newNamespace);
        }

        foreach ($schemaDiff->orphanedForeignKeys as $orphanedForeignKey) {
            $output->dropForeignKey($orphanedForeignKey, $orphanedForeignKey->getLocalTable());
        }

        foreach ($schemaDiff->changedSequences as $sequence) {
            $output->alterSequence($sequence);
        }

        foreach ($schemaDiff->removedSequences as $sequence) {
            $output->dropSequence($sequence);
        }

        foreach ($schemaDiff->newSequences as $sequence) {
            $output->createSequence($sequence);
        }

        foreach ($schemaDiff->newTables as $table) {
            $output->createTable($table);

            foreach ($table->getForeignKeys() as $foreignKey) {
                $output->createForeignKey($foreignKey, $table);
            }
        }

        foreach ($schemaDiff->removedTables as $table) {
            $output->dropTable($table);
        }

        foreach ($schemaDiff->changedTables as $tableDiff) {
            $output->alterTable($tableDiff);
        }

        $output->terminated();

        return $output->getResult();
    }

func VerifySwaggerDocsExist(kubeTypes []KubeTypes, w io.Writer) (int, error) {
	missingDocs := 0
	buffer := newBuffer()

	for _, kubeType := range kubeTypes {
		structName := kubeType[0].Name
		if kubeType[0].Doc == "" {
			format := "Missing documentation for the struct itself: %s\n"
			s := fmt.Sprintf(format, structName)
			buffer.addLine(s, 0)
			missingDocs++
		}
		kubeType = kubeType[1:] // Skip struct definition

		for _, pair := range kubeType { // Iterate only the fields
			if pair.Doc == "" {
				format := "In struct: %s, field documentation is missing: %s\n"
				s := fmt.Sprintf(format, structName, pair.Name)
				buffer.addLine(s, 0)
				missingDocs++
			}
		}
	}

	if err := buffer.flushLines(w); err != nil {
		return -1, err
	}
	return missingDocs, nil
}

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


Question: Simply write some content to a file, overriding the file if necessary.

def write_file(content, *path):

    with open(os.path.join(*path), "w") as file:
        return file.write(content)

func AppendFile(dst string, src string) error {
	appendFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		return err
	}
	defer appendFile.Close()

	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()
	// Allocate staging buffer.
	var buf = make([]byte, defaultAppendBufferSize)
	_, err = io.CopyBuffer(appendFile, srcFile, buf)
	return err
}

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


Question:
Initialize the model for simulation, possibly given a config file.

        Parameters
        ----------
        cfg_file : Optional[str]
            The name of the configuration file to load, optional.

def initialize(self, cfg_file=None, mode=None):

        self.sim = ScipyOdeSimulator(self.model)
        self.state = numpy.array(copy.copy(self.sim.initials)[0])
        self.time = numpy.array(0.0)
        self.status = 'initialized'

public function make($name, $options, $loadRelationships = true)
    {
        //make sure the options array has all the proper default values
        $options = $this->prepareOptions($name, $options, $loadRelationships);

        return $this->getFieldObject($options);
    }

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


Question:
Get the authority, creating a role authority if necessary.

@return \Illuminate\Database\Eloquent\Model|null

protected function getAuthority()
    {
        if (is_null($this->authority)) {
            return null;
        }

        if ($this->authority instanceof Model) {
            return $this->authority;
        }

        return Models::role()->firstOrCreate(['name' => $this->authority]);
    }

public function handle()
    {

        $this->line('SeAT Diagnostics');
        $this->line('If you are not already doing so, it is recommended that you ' .
            'run this as the user the workers are running as.');
        $this->line('Eg:');
        $this->info('    sudo -u apache php artisan seat:admin:diagnose');
        $this->info('    su -c "php artisan seat:admin:diagnose" -s /bin/sh www-data');
        $this->line('This helps to check whether the permissions are correct.');
        $this->line('');

        $this->environment_info();
        $this->line('');

        $this->check_debug();
        $this->line('');

        $this->check_storage();
        $this->line('');

        $this->check_database();
        $this->line('');

        $this->check_redis();
        $this->line('');

        $this->check_pheal();
        $this->line('');

        $this->call('seat:version');

        $this->line('SeAT Diagnostics complete');

    }

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


Question:
Fit to data, transform it, then visualize it.

        Fits the visualizer to X and y with opetional parameters by passing in
        all of kwargs, then calls poof with the same kwargs. This method must
        return the result of the transform method.

def fit_transform_poof(self, X, y=None, **kwargs):

        Xp = self.fit_transform(X, y, **kwargs)
        self.poof(**kwargs)
        return Xp

def calculate_flatten_output_shapes(operator):
    '''

    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    input = operator.inputs[0]
    output = operator.outputs[0]

    if len(input.type.shape) not in [2, 4]:
        raise RuntimeError('Input must be 2-D or 4-D float tensor')

    input_shape = input.type.shape
    output_shape = [input_shape[0], 1]

    # Calculate the multiplication of C, H, and W.
    for i in input_shape[1:]:
        if i != 'None':
            output_shape[1] *= i
        else:
            # If any of C, H, W-dimensions is unknown, the flatten C-dimension is unknown
            output_shape[1] = 'None'
            break

    output.type.shape = output_shape

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


Question:
// cacheSubnets tries to get and cache once all known provider subnets. It
// handles the case when subnets have duplicated CIDRs but distinct ProviderIds.
// It also handles weird edge cases, like no CIDR and/or ProviderId set for a
// subnet.

func (cache *addSubnetsCache) cacheSubnets(ctx context.ProviderCallContext) error {
	if cache.allSubnets != nil {
		// Already cached.
		logger.Tracef("using %d cached subnets", len(cache.allSubnets))
		return nil
	}

	netEnv, err := networkingEnviron(cache.api)
	if err != nil {
		return errors.Trace(err)
	}
	subnetInfo, err := netEnv.Subnets(ctx, instance.UnknownId, nil)
	if err != nil {
		return errors.Annotate(err, "cannot get provider subnets")
	}
	logger.Tracef("got %d subnets to cache from the provider", len(subnetInfo))

	if len(subnetInfo) > 0 {
		// Trying to avoid reallocations.
		cache.allSubnets = make([]network.SubnetInfo, 0, len(subnetInfo))
	}
	cache.providerIdsByCIDR = make(map[string]set.Strings)
	cache.subnetsByProviderId = make(map[string]*network.SubnetInfo)

	for i := range subnetInfo {
		subnet := subnetInfo[i]
		cidr := subnet.CIDR
		providerId := string(subnet.ProviderId)
		logger.Tracef(
			"caching subnet with CIDR %q, ProviderId %q, Zones: %q",
			cidr, providerId, subnet.AvailabilityZones,
		)

		if providerId == "" && cidr == "" {
			logger.Warningf("found subnet with empty CIDR and ProviderId")
			// But we still save it for lookups, which will probably fail anyway.
		} else if providerId == "" {
			logger.Warningf("found subnet with CIDR %q and empty ProviderId", cidr)
			// But we still save it for lookups.
		} else {
			_, ok := cache.subnetsByProviderId[providerId]
			if ok {
				logger.Warningf(
					"found subnet with CIDR %q and duplicated ProviderId %q",
					cidr, providerId,
				)
				// We just overwrite what's there for the same id.
				// It's a weird case and it shouldn't happen with
				// properly written providers, but anyway..
			}
		}
		cache.subnetsByProviderId[providerId] = &subnet

		if ids, ok := cache.providerIdsByCIDR[cidr]; !ok {
			cache.providerIdsByCIDR[cidr] = set.NewStrings(providerId)
		} else {
			ids.Add(providerId)
			logger.Debugf(
				"duplicated subnet CIDR %q; collected ProviderIds so far: %v",
				cidr, ids.SortedValues(),
			)
			cache.providerIdsByCIDR[cidr] = ids
		}

		cache.allSubnets = append(cache.allSubnets, subnet)
	}
	logger.Tracef("%d provider subnets cached", len(cache.allSubnets))
	if len(cache.allSubnets) == 0 {
		// Cached an empty list.
		return errors.Errorf("no subnets defined")
	}
	return nil
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: write the markdown formated content of the database tables' metadata to local wiki pages

def _write_wiki_pages(
            self):

        self.log.debug('starting the ``_write_wiki_pages`` method')

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Tables.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdTables)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Views.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdViews)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Streams.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdStreams)
        writeFile.close()

        self.log.debug('completed the ``_write_wiki_pages`` method')
        return None

def _getMetadata(self, key):
        """"""
        if self.isClosed:
            raise ValueError("operation illegal for closed doc")

        return _fitz.Document__getMetadata(self, key)

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *DeleteUserEndpointsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteUserEndpointsInput"}
	if s.ApplicationId == nil {
		invalidParams.Add(request.NewErrParamRequired("ApplicationId"))
	}
	if s.ApplicationId != nil && len(*s.ApplicationId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ApplicationId", 1))
	}
	if s.UserId == nil {
		invalidParams.Add(request.NewErrParamRequired("UserId"))
	}
	if s.UserId != nil && len(*s.UserId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("UserId", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question: // SetDataRetentionInHours sets the DataRetentionInHours field's value.

func (s *CreateStreamInput) SetDataRetentionInHours(v int64) *CreateStreamInput {
	s.DataRetentionInHours = &v
	return s
}

def get_allocated_time_metadata(self):

        # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
        metadata = dict(self._mdata['allocated_time'])
        metadata.update({'existing_duration_values': self._my_map['allocatedTime']})
        return Metadata(**metadata)

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


Question:
// isIsolated returns true if the device is an IOMMU group that only consists of unbound devices.
// The input device is expected to be a string like 0000:03:00.1 (Domain:Bus:Slot.Function)

func isIsolated(device string) bool {
	// Find out the other devices in the same IOMMU group as one of our unbound device.
	iommuGroupPath := filepath.Join(sysFsPCIDevicesPath, device, "iommu_group", "devices")
	otherDevices, err := ioutil.ReadDir(iommuGroupPath)
	if err != nil {
		log.Infof("Error reading %q: %v", iommuGroupPath)
		return false
	}

	for _, otherDevice := range otherDevices {
		// Check if the other device in the IOMMU group is unbound.
		if isUnbound(otherDevice.Name()) {
			continue
		}
		// If any of the other device in the IOMMU group is not unbound,
		// then our device is not isolated and cannot be safely passthrough.
		return false
	}
	return true
}

def insertSite(self, businput):

        conn = self.dbi.connection()
        tran = conn.begin()
        try:
            siteobj = { # FIXME: unused?
                "site_name" : businput["site_name"]
            }
            businput["site_id"] = self.sm.increment(conn, "SEQ_SI", tran)
            self.sitein.execute(conn, businput, tran)
            tran.commit()
        except Exception as ex:
            if (str(ex).lower().find("unique constraint") != -1 or
                str(ex).lower().find("duplicate") != -1):
                # already exists, lets fetch the ID
                self.logger.warning("Ignoring unique constraint violation")
                self.logger.warning(ex)
            else:
                if tran:
                    tran.rollback()
                self.logger.exception(ex)
                raise
        finally:
            if tran:
                tran.close()
            if conn:
                conn.close()

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


Question: // SetChangeToken sets the ChangeToken field's value.

func (s *UpdateRegexPatternSetInput) SetChangeToken(v string) *UpdateRegexPatternSetInput {
	s.ChangeToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question:
表达式前的空行

@param        $node  表达式
@param string $front_of_comment 注释前的换行
@return string 若干个换行

protected static function getFrontOfNode($node, $front_of_comment = '')
    {
        if (empty($front_of_comment)) {
            $result = self::getFrontOfComment($node);
        } else {
            $result = "\n";
        }
        return $result;
    }

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question:
Create an array of messages to send
based on a specified chunk size
@param arrayMessage
@param chunkSize
@return

public static NDArrayMessage[] chunkedMessages(NDArrayMessage arrayMessage, int chunkSize) {
        int sizeOfMessage = NDArrayMessage.byteBufferSizeForMessage(arrayMessage) - 4;
        int numMessages = sizeOfMessage / chunkSize;
        ByteBuffer direct = NDArrayMessage.toBuffer(arrayMessage).byteBuffer();
        NDArrayMessage[] ret = new NDArrayMessage[numMessages];
        for (int i = 0; i < numMessages; i++) {
            byte[] chunk = new byte[chunkSize];
            direct.get(chunk, i * chunkSize, chunkSize);
            ret[i] = NDArrayMessage.builder().chunk(chunk).numChunks(numMessages).build();
        }
        return ret;
    }

def get_arguments():
    """"""
    import argparse
    parser = argparse.ArgumentParser(
        description='Plot spectral responses for a set of satellite imagers')

    parser.add_argument("--platform_name", '-p', nargs='*',
                        help="The Platform name",
                        type=str, required=True)
    parser.add_argument("--sensor", '-s', nargs='*',
                        help="The sensor/instrument name",
                        type=str, required=True)
    parser.add_argument("-x", "--xlimits", nargs=2,
                        help=("x-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-y", "--ylimits", nargs=2,
                        help=("y-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-t", "--minimum_response",
                        help=("Minimum response: Any response lower than " +
                              "this will be ignored when plotting"),
                        default=0.015, type=float)

    parser.add_argument("-no_platform_name_in_legend", help=("No platform name in legend"),
                        action='store_true')
    parser.add_argument("--title", help=("Plot title"),
                        default=None, type=str)
    parser.add_argument("--wavelength_resolution",
                        help=("The step in wavelength (nanometers) when scanning\n" +
                              " the spectral range trying to find bands"),
                        default=0.005, type=float)
    parser.add_argument("-o", "--filename", help=("Output plot file name"),
                        default=None, type=str)
    parser.add_argument(
        "-v", '--verbose', help=("Turn logging on"), action='store_true')

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--bandname", '-b',
                       help="The sensor band name", type=str)
    group.add_argument("--wavelength", "-w", type=float,
                       help='the approximate spectral wavelength in micron')
    group.add_argument("--range", "-r", nargs='*',
                       help="The wavelength range for the plot",
                       default=[None, None], type=float)

    return parser.parse_args()

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


Question: Recursively call force_text on value.

def deep_force_unicode(value):

    if isinstance(value, (list, tuple, set)):
        value = type(value)(map(deep_force_unicode, value))
    elif isinstance(value, dict):
        value = type(value)(map(deep_force_unicode, value.items()))
    elif isinstance(value, Promise):
        value = force_text(value)
    return value

def namePop(ctxt):

    if ctxt is None: ctxt__o = None
    else: ctxt__o = ctxt._o
    ret = libxml2mod.namePop(ctxt__o)
    return ret

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


Question:
<p>
A list of the calculated facet values and counts.
</p>

@param buckets
A list of the calculated facet values and counts.

public void setBuckets(java.util.Collection<Bucket> buckets) {
        if (buckets == null) {
            this.buckets = null;
            return;
        }

        this.buckets = new com.amazonaws.internal.SdkInternalList<Bucket>(buckets);
    }

def create_node(**kwargs):
    '''

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

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

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

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

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

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

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

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

    return {}

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


Question:
Gets the current role of a user.

@param UserInterface $user

@return string

public function getUserRole(UserInterface $user)
    {
        $currentRole = '';
        $userRoles = $user->getRoles();

        if (in_array($userRoles[0], $this->getOrderedRoles())) {
            $currentRole = $userRoles[0];
        }

        return $currentRole;
    }

protected function buildUsageLine($usage_data, $options_data) {
    if ($usage_data['use_argv_self']) {
      $self_name = $_SERVER['argv'][0];
    } else {
      $self_name = $usage_data['self'];
    }

    $has_options = (count($options_data['lines']) > 0 ? true : false);
    $has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);

    $out =
      ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
      "  {$self_name}".
      ($has_options ? ' [options]' : '').
      ($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
      "\n";

    return $out;
  }

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


Question:
Cuts long sentences so only first few words are returned

@param string $sentence
@param int    $max_length
@param string $separator
@param string $postfix to add after sentence is cut

@return string

public static function cutLongStrings(string $sentence, int $max_length = 50, string $separator = ' ', string $postfix = '...'): string
    {
        // Return actual string if have nothing to cut
        if (mb_strlen($sentence, 'utf-8') <= $max_length) {
            return $sentence;
        }

        $words = mb_split("[" . $separator . "]+", $sentence);
        $res = '';
        $count_of_words = count($words);

        for ($i = 0; $i < $count_of_words; $i++) {
            if (mb_strlen($res . $words[$i] . ' ', 'utf-8') < $max_length) {
                // Add to returned string
                $res .= $words[$i] . ' ';
            } else {
                // Enough
                break;
            }
        }

        return mb_substr($res, 0, -1, 'utf-8') . $postfix;
    }

def genargs(prog: Optional[str] = None) -> ArgumentParser:

    parser = ArgumentParser(prog)
    parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
    parser.add_argument("shex", help="ShEx specification")
    parser.add_argument("-f", "--format", help="Input RDF Format", default="turtle")
    parser.add_argument("-s", "--start", help="Start shape. If absent use ShEx start node.")
    parser.add_argument("-ut", "--usetype", help="Start shape is rdf:type of focus", action="store_true")
    parser.add_argument("-sp", "--startpredicate", help="Start shape is object of this predicate")
    parser.add_argument("-fn", "--focus", help="RDF focus node")
    parser.add_argument("-A", "--allsubjects", help="Evaluate all non-bnode subjects in the graph", action="store_true")
    parser.add_argument("-d", "--debug", action="store_true", help="Add debug output")
    parser.add_argument("-ss", "--slurper", action="store_true", help="Use SPARQL slurper graph")
    parser.add_argument("-cf", "--flattener", action="store_true", help="Use RDF Collections flattener graph")
    parser.add_argument("-sq", "--sparql", help="SPARQL query to generate focus nodes")
    parser.add_argument("-se", "--stoponerror", help="Stop on an error", action="store_true")
    parser.add_argument("--stopafter", help="Stop after N nodes", type=int)
    parser.add_argument("-ps", "--printsparql", help="Print SPARQL queries as they are executed", action="store_true")
    parser.add_argument("-pr", "--printsparqlresults", help="Print SPARQL query and results", action="store_true")
    parser.add_argument("-gn", "--graphname", help="Specific SPARQL graph to query - use '' for any named graph")
    parser.add_argument("-pb", "--persistbnodes", help="Treat BNodes as persistent in SPARQL endpoint",
                        action="store_true")
    return parser

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


Question: // OptionDataDir function returns an option setter for data folder

func OptionDataDir(dataDir string) Option {
	return func(c *Config) {
		c.Daemon.DataDir = dataDir
	}
}

func (m *Module) SetMigrationSource(asset assetFunc, assetDir assetDirFunc, dir string) {
	m.migrationSource = &migrate.AssetMigrationSource{
		Asset:    asset,
		AssetDir: assetDir,
		Dir:      dir,
	}
}

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


Question:
Use the boot function to setup model event listeners.

@return void

public static function bootCascadesDeletes()
    {
        // Setup the 'deleting' event listener.
        static::deleting(function ($model) {

            // Wrap all of the cascading deletes inside of a transaction to make this an
            // all or nothing operation. Any exceptions thrown inside the transaction
            // need to bubble up to make sure all transactions will be rolled back.
            $model->getConnectionResolver()->transaction(function () use ($model) {

                $relations = $model->getCascadeDeletesRelations();

                if ($invalidRelations = $model->getInvalidCascadeDeletesRelations($relations)) {
                    throw new LogicException(sprintf('[%s]: invalid relationship(s) for cascading deletes. Relationship method(s) [%s] must return an object of type Illuminate\Database\Eloquent\Relations\Relation.', static::class, implode(', ', $invalidRelations)));
                }

                $deleteMethod = $model->isCascadeDeletesForceDeleting() ? 'forceDelete' : 'delete';

                foreach ($relations as $relationName => $relation) {
                    $expected = 0;
                    $deleted = 0;

                    if ($relation instanceof BelongsToMany) {
                        // Process the many-to-many relationships on the model.
                        // These relationships should not delete the related
                        // record, but should just detach from each other.

                        $expected = $model->getCascadeDeletesRelationQuery($relationName)->count();

                        $deleted = $model->getCascadeDeletesRelationQuery($relationName)->detach();
                    } elseif ($relation instanceof HasOneOrMany) {
                        // Process the one-to-one and one-to-many relationships
                        // on the model. These relationships should actually
                        // delete the related records from the database.

                        $children = $model->getCascadeDeletesRelationQuery($relationName)->get();

                        // To protect against potential relationship defaults,
                        // filter out any children that may not actually be
                        // Model instances, or that don't actually exist.
                        $children = $children->filter(function ($child) {
                            return $child instanceof Model && $child->exists;
                        })->all();

                        $expected = count($children);

                        foreach ($children as $child) {
                            // Delete the record using the proper method.
                            $child->$deleteMethod();

                            // forceDelete doesn't return anything until Laravel 5.2. Check
                            // exists property to determine if the delete was successful
                            // since that is the last thing set before delete returns.
                            $deleted += !$child->exists;
                        }
                    } else {
                        // Not all relationship types make sense for cascading. As an
                        // example, for a BelongsTo relationship, it does not make
                        // sense to delete the parent when the child is deleted.
                        throw new LogicException(sprintf('[%s]: error occurred deleting [%s]. Relation type [%s] not handled.', static::class, $relationName, get_class($relation)));
                    }

                    if ($deleted < $expected) {
                        throw new LogicException(sprintf('[%s]: error occurred deleting [%s]. Only deleted [%d] out of [%d] records.', static::class, $relationName, $deleted, $expected));
                    }
                }
            });
        });
    }

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

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


Question: Finds config root relative to the given file path

def find_config_root(path=sys.argv[0]):

    dirname = os.path.dirname(path)
    lastdirname = None

    while dirname != lastdirname:
        config_root = os.path.join(dirname, 'config')
        if os.path.exists(config_root):
            return config_root

        lastdirname, dirname = dirname, os.path.dirname(dirname)

public static function isRelativePathReference(UriInterface $uri)
    {
        $uriPath = $uri->getPath();
        return $uri->getScheme() === ''
            && $uri->getAuthority() === ''
            && (!isset($uriPath[0]) || $uriPath[0] !== '/');
    }

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


Question: Retrieve a summary of "safe" user information for external API calls.

public function GetSummary($OrderFields = '', $OrderDirection = 'asc', $Limit = FALSE, $Offset = FALSE) {
      $this->UserQuery(TRUE);
      return $this->SQL
         ->Where('u.Deleted', 0)
         ->OrderBy($OrderFields, $OrderDirection)
         ->Limit($Limit, $Offset)
         ->Get();
   }

func NewUniterAPIV11(context facade.Context) (*UniterAPIV11, error) {
	uniterAPI, err := NewUniterAPI(context)
	if err != nil {
		return nil, err
	}
	authorizer := context.Auth()
	st := context.State()
	resources := context.Resources()
	accessUnit := unitAccessor(authorizer, st)
	return &UniterAPIV11{
		LXDProfileAPI: NewExternalLXDProfileAPI(st, resources, authorizer, accessUnit, logger),
		UniterAPI:     *uniterAPI,
	}, nil
}

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


Question: Sets child's prototype to a new object whose prototype is parent's prototype. Used as: Meteor._inherits(ClassB, ClassA). _.extend(ClassB.prototype, { ... }) Inspired by CoffeeScript's `extend` and Google Closure's `goog.inherits`.

function (Child, Parent) {
    // copy Parent static properties
    for (var key in Parent) {
      // make sure we only copy hasOwnProperty properties vs. prototype
      // properties
      if (_.has(Parent, key))
        Child[key] = Parent[key];
    }

    // a middle member of prototype chain: takes the prototype from the Parent
    var Middle = function () {
      this.constructor = Child;
    };
    Middle.prototype = Parent.prototype;
    Child.prototype = new Middle();
    Child.__super__ = Parent.prototype;
    return Child;
  }

def normalize_type(type_, level=0):

    if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType:
        return type_
    if isinstance(type_, typing.TypeVar):
        if type_.__constraints__ or type_.__bound__:
            return type_
        else:
            return AnyType
    if issubclass(type_, typing.Union):
        if not type_.__union_params__:
            raise OverloadingError("typing.Union must be parameterized")
        return typing.Union[tuple(normalize_type(t, level) for t in type_.__union_params__)]
    if issubclass(type_, typing.Tuple):
        params = type_.__tuple_params__
        if level > 0 or params is None:
            return typing.Tuple
        elif type_.__tuple_use_ellipsis__:
            return typing.Tuple[normalize_type(params[0], level + 1), ...]
        else:
            return typing.Tuple[tuple(normalize_type(t, level + 1) for t in params)]
    if issubclass(type_, typing.Callable):
        return typing.Callable
    if isinstance(type_, typing.GenericMeta):
        base = find_base_generic(type_)
        if base is typing.Generic:
            return type_
        else:
            return GenericWrapper(type_, base, level > 0)
    raise OverloadingError("%r not supported yet" % type_)

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


Question:
// loop performs the main event loop cycle, polling for changes and
// responding to Changes requests

func (w *collectionWatcher) loop() error {
	var (
		changes []string
		in      = (<-chan watcher.Change)(w.source)
		out     = (chan<- []string)(w.sink)
	)

	w.watcher.WatchCollectionWithFilter(w.col, w.source, w.filter)
	defer w.watcher.UnwatchCollection(w.col, w.source)

	changes, err := w.initial()
	if err != nil {
		return err
	}

	for {
		select {
		case <-w.tomb.Dying():
			return tomb.ErrDying
		case <-w.watcher.Dead():
			return stateWatcherDeadError(w.watcher.Err())
		case ch := <-in:
			updates, ok := collect(ch, in, w.tomb.Dying())
			if !ok {
				return tomb.ErrDying
			}
			if err := w.mergeIds(&changes, updates); err != nil {
				return err
			}
			if len(changes) > 0 {
				out = w.sink
			}
		case out <- changes:
			changes = []string{}
			out = nil
		}
	}
}

def _outputLine(self, logevent, length=None, human=False):

        # adapt timezone output if necessary
        if self.args['timestamp_format'] != 'none':
            logevent._reformat_timestamp(self.args['timestamp_format'],
                                         force=True)
        if any(self.args['timezone']):
            if self.args['timestamp_format'] == 'none':
                self.args['timestamp_format'] = logevent.datetime_format
            logevent._reformat_timestamp(self.args['timestamp_format'],
                                         force=True)

        if self.args['json']:
            print(logevent.to_json())
            return
        line = logevent.line_str

        if length:
            if len(line) > length:
                line = (line[:int(length / 2 - 2)] + '...' +
                        line[int(-length / 2 + 1):])
        if human:
            line = self._changeMs(line)
            line = self._formatNumbers(line)

        print(line)

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


Question: helpers for select/selectEndpoints

function (list, func, args, selector) {
				for (var i = 0, j = list.length; i < j; i++) {
					list[i][func].apply(list[i], args);
				}
				return selector(list);
			}

func (s *service) Retrieve(email string) (resDTO rest.ResponseDTO, error *servicehelper.Error) {
	entity, err := s.repo.FindByEmail(email)
	if err != nil {
		return rest.ResponseDTO{}, &servicehelper.Error{
			Detail:  errors.New("user could not be found"),
			Message: "We could not find any user with the provided email address",
			Param:   "email",
			Code:    servicehelper.NotFound,
		}
	}
	return createDTOFromEntity(entity), error
}

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


Question:
/*!
\static
Initializes the eZTextCodec settings to the ones in the array \a $settings.
\sa internalCharset, httpCharset.

static function updateSettings( $settings )
    {
        unset( $GLOBALS['eZTextCodecInternalCharsetReal'] );
        unset( $GLOBALS['eZTextCodecHTTPCharsetReal'] );
        unset( $GLOBALS['eZTextCodecCharsetCheck'] );
        $GLOBALS['eZTextCodecInternalCharset'] = $settings['internal-charset'];
        $GLOBALS['eZTextCodecHTTPCharset'] = $settings['http-charset'];
        $GLOBALS['eZTextCodecMBStringExtension'] = $settings['mbstring-extension'];
        if ( function_exists( 'mb_internal_encoding' ) )
        {
            @mb_internal_encoding( $settings['internal-charset'] );
        }
    }

def gen_issuer
        name = "/C=#{EasyRSA::Config.country}"
        name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty?
        name += "/L=#{EasyRSA::Config.city}"
        name += "/O=#{EasyRSA::Config.company}"
        name += "/OU=#{EasyRSA::Config.orgunit}"
        name += "/CN=#{EasyRSA::Config.server}"
        name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty?
        name += "/name=#{EasyRSA::Config.orgunit}" if !EasyRSA::Config.name || EasyRSA::Config.name.empty?
        name += "/emailAddress=#{EasyRSA::Config.email}"

        @ca_cert.issuer = OpenSSL::X509::Name.parse(name)
      end

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


Question:
/*
filter

For internal use only. Provides a filtering function based on flags.

function(param) {
        if(!param || !($.type(param) == 'string')) return function() { return true; };
        var props = param.split(" ");
        return function(elem) {
            for(var i=0; i<props.length; i++) {
              if(elem[props[i]]) {
                return false;
              }
            }
            return true;
        };
    }

public void setMimeFilters(HashMap mimeFilters) {
        if (mimeFilters != null && mimeFilters.size() > 0) {
            this.isMimeFilteringEnabled = true;
        }
        this.mimeFilters = mimeFilters;
    }

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


Question:
Get model object by primary key.

@param int $id
@return static|null

public static function getByID($id)
    {
        $record = static::getRecordByField(static::$primaryKey ? static::$primaryKey : 'ID', $id, true);

        return static::instantiateRecord($record);
    }

public function Comment2($CommentID, $Inserted = FALSE) {
      $this->CommentModel->Save2($CommentID, $Inserted);
      $this->Render('Blank', 'Utility', 'Dashboard');
   }

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


Question:
Return detection of an iPhone or iPod Touch

        Detects if the current device is an iPhone or iPod Touch.

def detectIphoneOrIpod(self):

        #We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay.
        return UAgentInfo.deviceIphone in self.__userAgent \
            or UAgentInfo.deviceIpod in self.__userAgent

def verify_version
      app_version = options[:app_version]
      UI.message("Making sure the latest version on App Store Connect matches '#{app_version}' from the ipa file...")

      changed = options[:app].ensure_version!(app_version, platform: options[:platform])

      if changed
        UI.success("Successfully set the version to '#{app_version}'")
      else
        UI.success("'#{app_version}' is the latest version on App Store Connect")
      end
    end

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


Question:
Execute the KEEP_MATCHES mode

@param array &$str The tokens to be further tokenized

protected function match(array &$str, $pattern, $keep)
    {
        $tokens = array();
        foreach ($str as $s) {
            preg_match_all($pattern, $s, $m);
            $tokens = array_merge(
                $tokens,
                $m[$keep]
            );
        }

        $str = $tokens;
    }

def adapt_step_table!(parsed_step_table)
      # Saving off the original data
      parsed_step_table['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_step_table))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_step_table['cuke_modeler_parsing_data'][:rows] = nil

      parsed_step_table['rows'] = []
      parsed_step_table[:rows].each do |row|
        adapt_table_row!(row)
      end
      parsed_step_table['rows'].concat(parsed_step_table.delete(:rows))
      parsed_step_table['line'] = parsed_step_table.delete(:location)[:line]
    end

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


Question: // Close attempts to close the connection

func (c *SQLConnectionProducer) Close() error {
	// Grab the write lock
	c.Lock()
	defer c.Unlock()

	if c.db != nil {
		c.db.Close()
	}

	c.db = nil

	return nil
}

public function onSwooleWSClose($serv, $fd)
    {
        unset($this->fdRequest[$fd]);
        $this->portManager->eventClose($fd);
    }

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


Question:
// GetBestBlockHashAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See GetBestBlockHash for the blocking version and more details.

func (c *Client) GetBestBlockHashAsync() FutureGetBestBlockHashResult {
	cmd := btcjson.NewGetBestBlockHashCmd()
	return c.sendCmd(cmd)
}

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: // WithError add a minimal stack trace to the log Entry

func WithError(err error) Entry {
	ne := newEntryWithFields(logFields)
	return withErrFn(ne, err)
}

public function error(MvcEvent $event): void
    {
        if (
            true === $this->tracyOptions->getEnabled()
            && null !== $event->getParam('error')
            && null !== $event->getParam('exception')
        ) {
            ob_clean();

            throw $event->getParam('exception');
        }
    }

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


Question: // at marks the state to be on node n, for error reporting.

func (s *state) at(node ast.Node) {
	s.lastNode = s.node
	s.node = node
}

private final boolean block(Data data, Body body) throws TemplateException {
	if (!data.srcCode.forwardIfCurrent('{')) return false;
	comments(data);
	if (data.srcCode.forwardIfCurrent('}')) {

	    return true;
	}
	statements(data, body, false);

	if (!data.srcCode.forwardIfCurrent('}')) throw new TemplateException(data.srcCode, "Missing ending [}]");
	return true;
    }

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


Question:
// UploadToContentRepo uploads the given bytes to the content repository and returns an MXC URI.
// See http://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-media-r0-upload

func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (*RespMediaUpload, error) {
	req, err := http.NewRequest("POST", cli.BuildBaseURL("_matrix/media/r0/upload"), content)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", contentType)
	req.ContentLength = contentLength
	res, err := cli.Client.Do(req)
	if res != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return nil, err
	}
	if res.StatusCode != 200 {
		contents, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return nil, HTTPError{
				Message: "Upload request failed - Failed to read response body: " + err.Error(),
				Code:    res.StatusCode,
			}
		}
		return nil, HTTPError{
			Message: "Upload request failed: " + string(contents),
			Code:    res.StatusCode,
		}
	}
	var m RespMediaUpload
	if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
		return nil, err
	}
	return &m, nil
}

public static function createFromDataPath(string $path, $context = null): self
    {
        $file_args = [$path, false];
        $mime_args = [$path, FILEINFO_MIME];
        if (null !== $context) {
            $file_args[] = $context;
            $mime_args[] = $context;
        }

        $raw = @file_get_contents(...$file_args);
        if (false === $raw) {
            throw new SyntaxError(sprintf('The file `%s` does not exist or is not readable', $path));
        }

        return Uri::createFromComponents([
            'scheme' => 'data',
            'path' => str_replace(' ', '', (new finfo(FILEINFO_MIME))->file(...$mime_args)).';base64,'.base64_encode($raw),
        ]);
    }

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


Question: // StringIndented returns a string representation of the commit

func (commit *Commit) StringIndented(indent string) string {
	if commit == nil {
		return "nil-Commit"
	}
	precommitStrings := make([]string, len(commit.Precommits))
	for i, precommit := range commit.Precommits {
		precommitStrings[i] = precommit.String()
	}
	return fmt.Sprintf(`Commit{
%s  BlockID:    %v
%s  Precommits:
%s    %v
%s}#%v`,
		indent, commit.BlockID,
		indent,
		indent, strings.Join(precommitStrings, "\n"+indent+"    "),
		indent, commit.hash)
}

def revision(directory, message, autogenerate, sql, head, splice, branch_label,
             version_path, rev_id):
    """"""
    _revision(directory, message, autogenerate, sql, head, splice,
              branch_label, version_path, rev_id)

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


Question:
Request data fromo the server.

        :param cmd: repo handler command.

        :returns: Result.

def request(self, cmd, *args, **kwargs):

        params = {'action': cmd}
        #TODO: serialize the kwargs?
        params.update(kwargs)
        return self.__request(self.url, params)

public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }

        if (null === $this->getTargetPath()) {
            throw new BuildException('"targetPath" is required parameter');
        }

        $files = @scandir($this->getTargetPath());
        if (isset($files) && is_array($files) && (count($files) > 2)) {
            throw new BuildException(
                sprintf(
                    '"%s" target directory is not empty',
                    $this->getTargetPath()
                )
            );
        }

        try {
            $this->doClone($this->getGitClient(false, getcwd()));
        } catch (Exception $e) {
            throw new BuildException('The remote end hung up unexpectedly', $e);
        }

        $msg = 'git-clone: cloning '
            . ($this->isBare() ? '(bare) ' : '')
            . ($this->hasDepth() ? ' (depth="' . $this->getDepth() . '") ' : '')
            . '"' . $this->getRepository() . '" repository'
            . ' to "' . $this->getTargetPath() . '" directory';
        $this->log($msg, Project::MSG_INFO);
    }

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


Question:
Copies entries in the source map to target map.

@param source source map
@param target target map

private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {
        for (Map.Entry<String, NodeT> entry : source.entrySet()) {
            String key = entry.getKey();
            if (!target.containsKey(key)) {
                target.put(key, entry.getValue());
            }
        }
    }

def main():

    parser = argparse.ArgumentParser(
        description='A pipeline that generates analysis pipelines.')
    parser.add_argument('input', nargs='?',
                   help='A valid metapipe configuration file.')
    parser.add_argument('-o', '--output',
                   help='An output destination. If none is provided, the '
                   'results will be printed to stdout.',
                   default=sys.stdout)
    parser.add_argument('-t', '--temp',
                   help='A desired metapipe binary file. This is used to store '
                   'temp data between generation and execution. '
                   '(Default: "%(default)s")', default='.metapipe')
    parser.add_argument('-s', '--shell',
                   help='The path to the shell to be used when executing the '
                   'pipeline. (Default: "%(default)s)"',
                   default='/bin/bash')
    parser.add_argument('-r', '--run',
                   help='Run the pipeline as soon as it\'s ready.',
                   action='store_true')
    parser.add_argument('-n', '--name',
                   help='A name for the pipeline.',
                   default='')
    parser.add_argument('-j', '--job-type',
                   help='The destination for calculations (i.e. local, a PBS '
                   'queue on a cluster, etc).\nOptions: {}. '
                   '(Default: "%(default)s)"'.format(JOB_TYPES.keys()),
                   default='local')
    parser.add_argument('-p', '--max-jobs',
                   help='The maximum number of concurrent jobs allowed. '
                   'Defaults to maximum available cores.',
                   default=None)
    parser.add_argument('--report-type',
                   help='The output report type. By default metapipe will '
                   'print updates to the console. \nOptions: {}. '
                   '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()),
                   default='text')
    parser.add_argument('-v','--version',
                    help='Displays the current version of the application.',
                    action='store_true')
    args = parser.parse_args()

    if args.version:
        print('Version: {}'.format(__version__))
        sys.exit(0)

    try:
        with open(args.input) as f:
            config = f.read()
    except IOError:
        print('No valid config file found.')
        return -1

    run(config, args.max_jobs, args.output, args.job_type, args.report_type,
        args.shell, args.temp, args.run)

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


Question:
Get the DONNode attributes

@static
@param   DOMNode $node
@return  array

protected static function DOMNodeAttributes(DOMNode $node)
    {
        $attributes = array();

        foreach ($node->attributes as $attribute) {
            $attributes[$attribute->name] = $attribute->value;
        }

        return $attributes;
    }

public function toXML(DOMElement $parent) : DOMElement
    {
        Assert::stringNotEmpty($this->Algorithm, 'Cannot convert DigestMethod to XML without an Algorithm set.');

        $doc = $parent->ownerDocument;
        $e = $doc->createElementNS(Common::NS, 'alg:DigestMethod');
        $parent->appendChild($e);
        $e->setAttribute('Algorithm', $this->Algorithm);

        return $e;
    }

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


Question:
Ensure that we have space in the local key array for the target index.

@param index

@SuppressWarnings("unchecked")
    private void validateKey(int index) {
        final int size = (index + 1);
        if (null == this.keys) {
            // nothing has been created yet
            this.keys = (K[]) new Object[size];
        } else if (index >= this.keys.length) {
            // this row puts us beyond the current storage
            Object[] newKeys = new Object[size];
            System.arraycopy(this.keys, 0, newKeys, 0, this.keys.length);
            this.keys = (K[]) newKeys;
        }
    }

public void setArgs(java.util.Collection<String> args) {
        if (args == null) {
            this.args = null;
            return;
        }

        this.args = new com.amazonaws.internal.SdkInternalList<String>(args);
    }

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


Question:
Set 'SortDirection' value

@param \AgentSIB\Diadoc\Api\Proto\SortDirection $value

public function setSortDirection(\AgentSIB\Diadoc\Api\Proto\SortDirection $value = null)
    {
        $this->SortDirection = $value;
    }

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

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


Question: Copies the rows indicated by the row index values in the given selection from oldTable to newTable

@SuppressWarnings({"rawtypes","unchecked"})
    public static void copyRowsToTable(Selection rows, Table oldTable, Table newTable) {
        for (int columnIndex = 0; columnIndex < oldTable.columnCount(); columnIndex++) {
            Column oldColumn = oldTable.column(columnIndex);
            int r = 0;
            for (int i : rows) {
                newTable.column(columnIndex).set(r, oldColumn, i);
                r++;
            }
        }

    }

public void loadRTreeIndex(String tableName, String geometryColumnName,
			String idColumnName) {

		String sqlName = GeoPackageProperties.getProperty(SQL_PROPERTY,
				LOAD_PROPERTY);
		executeSQL(sqlName, tableName, geometryColumnName, idColumnName);
	}

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


Question:
Format a number using scientific notation.

@param {number} num
@param {number} [precision]
@param {Object} [options] Formatting options
@returns {string} Formatted number

function scino (num, precision, options) {
  if (typeof precision === 'object') {
    options = precision
    precision = undefined
  }

  if (typeof num !== 'number') {
    return num
  }

  var parsed = parse(num, precision)
  var opts = getValidOptions(options)
  var coefficient = parsed.coefficient
  var exponent = parsed.exponent.toString()
  var superscriptExponent = ''

  if (typeof coefficient === 'number' && isNaN(coefficient)) {
    return num
  }

  for (var i = 0; i < exponent.length; i++) {
    superscriptExponent += SUPERSCRIPTS[exponent[i]]
  }

  return opts.beforeCoefficient + coefficient + opts.afterCoefficient +
    opts.beforeMultiplicationSign + opts.multiplicationSign + opts.afterMultiplicationSign +
    opts.beforeBase + opts.base + opts.afterBase +
    opts.beforeExponent + superscriptExponent + opts.afterExponent
}

def parse_temperature_response(
        temperature_string: str) -> Mapping[str, Optional[float]]:
    '''

    '''
    err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
        temperature_string)
    if not temperature_string or \
            not isinstance(temperature_string, str):
        raise ParseError(err_msg)
    parsed_values = temperature_string.strip().split(' ')
    if len(parsed_values) < 2:
        log.error(err_msg)
        raise ParseError(err_msg)

    data = {
        parse_key_from_substring(s): parse_number_from_substring(s)
        for s in parsed_values[:2]
    }
    if 'C' not in data or 'T' not in data:
        raise ParseError(err_msg)
    data = {
        'current': data['C'],
        'target': data['T']
    }
    return data

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


Question:
Check if the node catches `Throwable`

@param Node $node The node to check.
@return boolean Result.

private function isIncludeThrowableNode(Node $node): bool
    {
        foreach ($node->children['class']->children as $class) {
            if ($class->children['name'] === 'Throwable') {
                return true;
            }
        }

        return false;
    }

function findProtectedNode(builder, path, callback) {
  var zk = builder.client.zk;
  var pathAndNode = utils.pathAndNode(path);
  zk.getChildren(pathAndNode.path, afterCheck);

  function afterCheck(err, children) {
    if (err && err.getCode() === Exception.NO_NODE) {
      callback();
    }
    else if (err) {
      callback(err);
    }
    else if (children.length) {
      var result = findNode(children, pathAndNode.path, builder.protectedId);
      callback(null, result);
    }
    else {
      callback();
    }
  }
}

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


Question:
A particular user's packages (watchcommits flag)

    This rule includes messages that relate to packages where the
    specified user has the watchcommits flag set.

def user_package_watch_filter(config, message, fasnick=None, *args, **kw):

    fasnick = kw.get('fasnick', fasnick)
    if fasnick:
        msg_packages = fmn.rules.utils.msg2packages(message, **config)
        if not msg_packages:
            # If the message has no packages associated with it, there's no
            # way that "one of them" is going to happen to belong to this user,
            # so let's not waste our time doing the somewhat expensive call out
            # to pkgdb on the next line to check.
            return False
        usr_packages = fmn.rules.utils.get_packages_of_user(
            config, fasnick, only_watchcommits)
        return usr_packages.intersection(msg_packages)

    return False

def is_correct(self):

        state = True

        # Internal checks before executing inherited function...
        cls = self.__class__
        if hasattr(self, 'host_name'):
            for char in cls.illegal_object_name_chars:
                if char in self.host_name:
                    self.add_error("[%s::%s] host_name contains an illegal character: %s"
                                   % (self.my_type, self.get_name(), char))
                    state = False

        # Fred: do not alert about missing check_command for an host... this because 1/ it is
        # very verbose if hosts are not checked and 2/ because it is the Nagios default behavior
        # if not self.check_command:
        #     self.add_warning("[%s::%s] has no defined check command"
        #                      % (self.my_type, self.get_name()))

        if self.notifications_enabled and not self.contacts:
            self.add_warning("[%s::%s] notifications are enabled but no contacts nor "
                             "contact_groups property is defined for this host"
                             % (self.my_type, self.get_name()))

        return super(Host, self).is_correct() and state

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


Question:
// newAddressWitnessPubKeyHash is an internal helper function to create an
// AddressWitnessPubKeyHash with a known human-readable part, rather than
// looking it up through its parameters.

func newAddressWitnessPubKeyHash(hrp string, witnessProg []byte) (*AddressWitnessPubKeyHash, error) {
	// Check for valid program length for witness version 0, which is 20
	// for P2WPKH.
	if len(witnessProg) != 20 {
		return nil, errors.New("witness program must be 20 " +
			"bytes for p2wpkh")
	}

	addr := &AddressWitnessPubKeyHash{
		hrp:            strings.ToLower(hrp),
		witnessVersion: 0x00,
	}

	copy(addr.witnessProgram[:], witnessProg)

	return addr, nil
}

def check_key(user,
              key,
              enc,
              comment,
              options,
              config='.ssh/authorized_keys',
              cache_keys=None,
              fingerprint_hash_type=None):
    '''

    '''
    if cache_keys is None:
        cache_keys = []
    enc = _refine_enc(enc)
    current = auth_keys(user,
                        config=config,
                        fingerprint_hash_type=fingerprint_hash_type)
    nline = _format_auth_line(key, enc, comment, options)

    # Removing existing keys from the auth_keys isn't really a good idea
    # in fact
    #
    # as:
    #   - We can have non-salt managed keys in that file
    #   - We can have multiple states defining keys for an user
    #     and with such code only one state will win
    #     the remove all-other-keys war
    #
    # if cache_keys:
    #     for pub_key in set(current).difference(set(cache_keys)):
    #         rm_auth_key(user, pub_key)

    if key in current:
        cline = _format_auth_line(key,
                                  current[key]['enc'],
                                  current[key]['comment'],
                                  current[key]['options'])
        if cline != nline:
            return 'update'
    else:
        return 'add'
    return 'exists'

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


function RAgent_onEvent(message) {
  DEBUG("RAgent.onEvent(" + message.name + ")")
  var name = message.name
  var body = message.body
  var agent

  if (message.from == "server") {
    if ((name == "agentCreated") || (name == "agentDestroyed")) {
      agent = this._session._ragents.get(body.id)
      if (null == agent) {
        agent = new RAgent(this._session, body)
        this._session._ragents.set(body.id, agent)
      }

      this.emit(name, agent.info)
    }
    else {
      this.emit(name, body)
    }
  }
  else {
    this.emit(name, body)
  }
}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question: create an engine connected to a mysql database using mysqldb.

def create_mysql(username, password, host, port, database, **kwargs):  # pragma: no cover

    return create_engine(
        _create_mysql(username, password, host, port, database),
        **kwargs
    )

def db_command(parser_args):

    from synergy.db.manager import db_manager

    if parser_args.reset:
        db_manager.reset_db()
        # initialize DB with the context.process_context entries
        parser_args.update = True

    if parser_args.update:
        db_manager.update_db()

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


Question:
Iterate all registered type converters. For informational purposes only.

@param aCallback
The callback invoked for all iterations.

public void iterateAllRegisteredTypeConverters (@Nonnull final ITypeConverterCallback aCallback)
  {
    // Create a copy of the map
    final Map <Class <?>, Map <Class <?>, ITypeConverter <?, ?>>> aCopy = m_aRWLock.readLocked ( () -> new CommonsHashMap <> (m_aConverter));

    // And iterate the copy
    outer: for (final Map.Entry <Class <?>, Map <Class <?>, ITypeConverter <?, ?>>> aSrcEntry : aCopy.entrySet ())
    {
      final Class <?> aSrcClass = aSrcEntry.getKey ();
      for (final Map.Entry <Class <?>, ITypeConverter <?, ?>> aDstEntry : aSrcEntry.getValue ().entrySet ())
        if (aCallback.call (aSrcClass, aDstEntry.getKey (), aDstEntry.getValue ()).isBreak ())
          break outer;
    }
  }

public void addListener(ILabelProviderListener listener)
	{
		if (fLabelDecorators != null)
		{
			for (int i = 0; i < fLabelDecorators.size(); i++)
			{
				ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators.get(i);
				decorator.addListener(listener);
			}
		}
		fListeners.add(listener);
	}

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


Question:
Add a contract to the database.

        Args:
            contract(neo.SmartContract.Contract): a Contract instance.

def AddContract(self, contract):

        super(UserWallet, self).AddContract(contract)

        try:
            db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes())
            db_contract.delete_instance()
        except Exception as e:
            logger.debug("contract does not exist yet")

        sh = bytes(contract.ScriptHash.ToArray())
        address, created = Address.get_or_create(ScriptHash=sh)
        address.IsWatchOnly = False
        address.save()
        db_contract = Contract.create(RawData=contract.ToArray(),
                                      ScriptHash=contract.ScriptHash.ToBytes(),
                                      PublicKeyHash=contract.PublicKeyHash.ToBytes(),
                                      Address=address,
                                      Account=self.__dbaccount)

        logger.debug("Creating db contract %s " % db_contract)

        db_contract.save()

def blueprint(self, blueprint, **options):
        '''
        '''
        if blueprint.name in self.blueprints:
            assert self.blueprints[blueprint.name] is blueprint, \
                'A blueprint with the name "%s" is already registered.  ' \
                'Blueprint names must be unique.' % \
                (blueprint.name,)
        else:
            self.blueprints[blueprint.name] = blueprint
            self._blueprint_order.append(blueprint)
        blueprint.register(self, options)

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


Question: Perform necessary JSON conversion on the arg.

def arg_to_json(arg):

    conversion = json_conversions.get(type(arg))
    if conversion:
        return conversion(arg)
    for type_ in subclass_conversions:
        if isinstance(arg, type_):
            return json_conversions[type_](arg)
    return json_conversions[str](arg)

func (p *WebPage) SetLibraryPath(path string) error {
	return p.ref.process.doJSON("POST", "/webpage/SetLibraryPath", map[string]interface{}{"ref": p.ref.id, "path": path}, nil)
}

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


Question:
Wrap the httplib response function to trace.

    If there is a corresponding httplib request span, update and close it.
    If not, return the response.

def wrap_httplib_response(response_func):

    def call(self, *args, **kwargs):
        _tracer = execution_context.get_opencensus_tracer()
        current_span_id = execution_context.get_opencensus_attr(
            'httplib/current_span_id')

        span = _tracer.current_span()

        # No corresponding request span is found, request not traced.
        if not span or span.span_id != current_span_id:
            return response_func(self, *args, **kwargs)

        result = response_func(self, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status))

        _tracer.end_span()
        return result

    return call

def callback(self, ch, method, properties, body):

        index = method.routing_key.split('.')[1]
        index = index.replace('/', '-')
        failed = False
        body = str(body)
        try:
            doc = json.loads(body)
        except Exception as e:  # pragma: no cover
            try:
                body = body.strip().replace('"', '\"')
                body = '{"log":"' + body + '"}'
                doc = json.loads(body)
            except Exception as e:  # pragma: no cover
                failed = True

        if not failed:
            try:
                self.es_conn.index(index=index,
                                   doc_type=method.routing_key.split('.')[1],
                                   id=method.routing_key + '.' +
                                   str(uuid.uuid4()),
                                   body=doc)
            except Exception as e:  # pragma: no cover
                print('Failed to send document to elasticsearch because: ' + str(e))

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


Question:
Display the instances of the CIM_Class defined by cim_class. If the
    namespace is None, use the interop namespace. Search all namespaces for
    instances except for CIM_RegisteredProfile

def show_instances(server, cim_class):

    if cim_class == 'CIM_RegisteredProfile':
        for inst in server.profiles:
            print(inst.tomof())
        return

    for ns in server.namespaces:
        try:
            insts = server.conn.EnumerateInstances(cim_class, namespace=ns)
            if len(insts):
                print('INSTANCES OF %s ns=%s' % (cim_class, ns))
                for inst in insts:
                    print(inst.tomof())
        except pywbem.Error as er:
            if er.status_code != pywbem.CIM_ERR_INVALID_CLASS:
                print('%s namespace %s Enumerate failed for conn=%s\n'
                      'exception=%s'
                      % (cim_class, ns, server, er))

def find_all_hid_devices():
    ""
    #
    # From DDK documentation (finding and Opening HID collection):
    # After a user-mode application is loaded, it does the following sequence
    # of operations:
    #
    #   * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass
    #     devices.
    #
    #   * Calls SetupDiGetClassDevs to obtain a handle to an opaque device
    #     information set that describes the device interfaces supported by all
    #     the HID collections currently installed in the system. The
    #     application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE
    #     in the Flags parameter passed to SetupDiGetClassDevs.
    #
    #   * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the
    #     available interface information.
    #
    #   * Calls SetupDiGetDeviceInterfaceDetail to format interface information
    #     for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure.
    #     The device_path member of this structure contains the user-mode name
    #     that the application uses with the Win32 function CreateFile to
    #     obtain a file handle to a HID collection.
    #
    # get HID device class guid
    guid = winapi.GetHidGuid()

    # retrieve all the available interface information.
    results = []
    required_size = DWORD()

    info_data         = winapi.SP_DEVINFO_DATA()
    info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA)

    with winapi.DeviceInterfaceSetInfo(guid) as h_info:
        for interface_data in winapi.enum_device_interfaces(h_info, guid):
            device_path = winapi.get_device_path(h_info,
                    interface_data,
                    byref(info_data))

            parent_device = c_ulong()

            #get parent instance id (so we can discriminate on port)
            if setup_api.CM_Get_Parent(byref(parent_device),
                    info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0
                parent_device.value = 0 #null

            #get unique instance id string
            required_size.value = 0
            winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
                    None, 0,
                    byref(required_size) )

            device_instance_id = create_unicode_buffer(required_size.value)
            if required_size.value > 0:
                winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
                        device_instance_id, required_size,
                        byref(required_size) )

                hid_device = HidDevice(device_path,
                        parent_device.value, device_instance_id.value )
            else:
                hid_device = HidDevice(device_path, parent_device.value )

            # add device to results, if not protected
            if hid_device.vendor_id:
                results.append(hid_device)
    return results

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


Question:
@param string $email
@param int    $mode

@return string|null E.g. "12831283123123"

public function resolveUserIdFromEmail(string $email, int $mode)
    {
        switch ($mode) {
            case self::MODE_RESOLVE_PRIMARY_ONLY:
                $gmailUser = $this->getGmailDomain()->findGmailUserByPrimaryEmail($email);

                break;

            case self::MODE_RESOLVE_ALIASES_ONLY:
                $gmailUser = $this->getGmailDomain()->findGmailUserByEmailAlias($email);

                break;

            case self::MODE_RESOLVE_PRIMARY_PLUS_ALIASES:
                $gmailUser = $this->getGmailDomain()->findGmailUserByEmail($email);

                break;

            default:
                throw new \InvalidArgumentException();
        }

        return $gmailUser ? $gmailUser->getUserId() : null;
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question: send and receive using a bluetooth socket

def srbt(peer, pkts, inter=0.1, *args, **kargs):
    """"""
    s = conf.BTsocket(peer=peer)
    a,b = sndrcv(s,pkts,inter=inter,*args,**kargs)
    s.close()
    return a,b

@Override
    public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options,
            FileAttribute<?>... attrs) throws IOException {
        return new ShrinkWrapFileChannel(newByteChannel(path, options, attrs));
    }

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


Question: Marshall the given parameter object.

public void marshall(InferenceSpecification inferenceSpecification, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(inferenceSpecification.getContainers(), CONTAINERS_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedTransformInstanceTypes(), SUPPORTEDTRANSFORMINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedRealtimeInferenceInstanceTypes(), SUPPORTEDREALTIMEINFERENCEINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedContentTypes(), SUPPORTEDCONTENTTYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedResponseMIMETypes(), SUPPORTEDRESPONSEMIMETYPES_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.