query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Sets the value of p1 and p2 to be equal to the values of the passed in objects | public void set( Vector3D_F64 l1 , Vector3D_F64 l2 ) {
this.l1.set(l1);
this.l2.set(l2);
} | csn |
Removes the opinion for the given opinion identifier
@type opinion_id: string
@param opinion_id: the opinion identifier to be removed | def remove_this_opinion(self,opinion_id):
"""
Removes the opinion for the given opinion identifier
@type opinion_id: string
@param opinion_id: the opinion identifier to be removed
"""
for opi in self.get_opinions():
if opi.get_id() == opinion_id:
... | csn |
Process templates by injecting vars and moving to location
@api private | def generate(template_options, color_option)
templates.each do |src, dst|
source = @source_path.join(src)
destination = @target_path.join(dst).to_s
next unless ::File.exist?(source)
within_root_path do
TTY::File.copy_file(source, destination,
{ co... | csn |
// MessageRemote just echoes the given message | func (r *Room) MessageRemote(ctx context.Context, msg *UserMessage, b bool, s string) (*UserMessage, error) {
return msg, nil
} | csn |
Generate a configuration file example.
This utility will load some number of Python modules which are assumed
to register options with confpy and generate an example configuration file
based on those options. | def generate_example():
"""Generate a configuration file example.
This utility will load some number of Python modules which are assumed
to register options with confpy and generate an example configuration file
based on those options.
"""
cmd_args = sys.argv[1:]
parser = argparse.ArgumentP... | csn |
Request the dump from your database
REST: POST /hosting/web/{serviceName}/database/{name}/dump
@param date [required] The date you want to dump
@param sendEmail [required] Send an email when dump will be available? Default: true
@param serviceName [required] The internal name of your hosting
@param name [required] Dat... | public OvhTask serviceName_database_name_dump_POST(String serviceName, String name, OvhDateEnum date, Boolean sendEmail) throws IOException {
String qPath = "/hosting/web/{serviceName}/database/{name}/dump";
StringBuilder sb = path(qPath, serviceName, name);
HashMap<String, Object>o = new HashMap<String, Object>(... | csn |
Highlight the provided set of atoms and bonds in the depiction in the
specified color.
Calling this methods appends to the current highlight buffer. The buffer
is cleared after each depiction is generated (e.g. {@link #depict(IAtomContainer)}).
@param chemObjs set of atoms and bonds
@param color the color to highl... | public DepictionGenerator withHighlight(Iterable<? extends IChemObject> chemObjs, Color color) {
DepictionGenerator copy = new DepictionGenerator(this);
for (IChemObject chemObj : chemObjs)
copy.highlight.put(chemObj, color);
return copy;
} | csn |
Add an element with the passed values.
@param string $key The key to add.
@param array $values The values to use.
@return void
@throws \InvalidArgumentException When the passed array is invalid. | protected function addItem(string $key, array $values): void
{
if (!array_key_exists('source', $values) || !array_key_exists('target', $values)) {
throw new \InvalidArgumentException('Invalid translation array: ' . var_export($values, true));
}
$this->translationBuffer[$key] = n... | csn |
If there is a "permakey", then we will verify the token by checking the
database. Otherwise, just do the normal verification.
Typically, any method that begins with an underscore in sanic-jwt should
not be touched. In this case, we are trying to break the rules a bit to handle
a unique ... | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
"""
If there is a "permakey", then we will verify the token by checking the
d... | csn |
Add a number of months to the given date | def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value | csn |
Receive a SAML 2 message sent using the HTTP-Artifact binding.
Throws an exception if it is unable receive the message.
@throws \Exception
@return \SAML2\Message|null The received message. | public function receive() : ?Message
{
if (array_key_exists('SAMLart', $_REQUEST)) {
$artifact = base64_decode($_REQUEST['SAMLart']);
$endpointIndex = bin2hex(substr($artifact, 2, 2));
$sourceId = bin2hex(substr($artifact, 4, 20));
} else {
throw new \... | csn |
Adds content for the HTML tag.
@param tagContent tag content to be added | public void addContent(Content tagContent) {
if (tagContent instanceof ContentBuilder) {
for (Content content: ((ContentBuilder)tagContent).contents) {
addContent(content);
}
}
else if (tagContent == HtmlTree.EMPTY || tagContent.isValid()) {
if... | csn |
Extract result parts of the collection.
@param mixed $parts
@return mixed | public function extract($parts = null) {
if ($parts === null) {
return $this->data;
}
if (is_array($parts)) {
$result = array();
foreach ($this->data as $match) {
$row = array();
foreach ($parts as $key) {
... | csn |
// GetPeers returns a list of peers with metadata as published by them | func (gc *gossipChannel) GetPeers() []discovery.NetworkMember {
var members []discovery.NetworkMember
if gc.hasLeftChannel() {
return members
}
for _, member := range gc.GetMembership() {
if !gc.EligibleForChannel(member) {
continue
}
stateInf := gc.stateInfoMsgStore.MsgByID(member.PKIid)
if stateInf ... | csn |
Extract all imports from a python script | def extract_imports(script):
"""Extract all imports from a python script"""
if not os.path.isfile(script):
raise ValueError('Not a file: %s' % script)
parse_tree = parse_python(script)
result = find_imports(parse_tree)
result.path = script
return result | csn |
we cannot verify that skiplist units lie on MC if they are unstable yet, but if they don't, we'll get unmatching ball hash when the current unit reaches stability | function validateSkiplist(conn, arrSkiplistUnits, callback){
var prev = "";
async.eachSeries(
arrSkiplistUnits,
function(skiplist_unit, cb){
//if (skiplist_unit.charAt(0) !== "0")
// return cb("skiplist unit doesn't start with 0");
if (skiplist_unit <= prev)
return cb(createJointError("skiplist un... | csn |
Utility function to flatten out args.
For internal use only.
:param values: list, tuple, or str
:param extra: list or None
:return: list | def _parse_values(values, extra=None):
"""
Utility function to flatten out args.
For internal use only.
:param values: list, tuple, or str
:param extra: list or None
:return: list
"""
coerced = list(values)
if coerced == values:
values = coerced
else:
coerced =... | csn |
Docker pull the image and tag it uniquely for use by this build | def _pull_and_tag_image(self, image, build_json, nonce):
"""Docker pull the image and tag it uniquely for use by this build"""
image = image.copy()
first_library_exc = None
for _ in range(20):
# retry until pull and tag is successful or definitively fails.
# shoul... | csn |
Calculates the distance between multiple origins and destinations
@param DistanceMatrixLocation[] $origins
@param DistanceMatrixLocation[] $destinations
As Google always return the distance value in meters (not km), the function multiplies
the result by 0.62 (km:mile) to calculate an approximation in imperial.
Obs: B... | public function calculateDistanceMatrix(array $origins, array $destinations) : DistanceMatrixResponse
{
$formattedOrigins = $this->formatEntities($origins);
$formattedDestinations = $this->formatEntities($destinations);
$query = http_build_query([
'origins' => $formatt... | csn |
Strip out the port number if it is a valid URI | private static String normalizeClusterUrl(String clusterIdentifier) {
try {
URI uri = new URI(clusterIdentifier.trim());
// URIs without protocol prefix
if (!uri.isOpaque() && null != uri.getHost()) {
clusterIdentifier = uri.getHost();
} else {
clusterIdentifier = uri.toStrin... | csn |
Returns whether the given table exists.
:param table:
:type table: BQTable | def table_exists(self, table):
"""Returns whether the given table exists.
:param table:
:type table: BQTable
"""
if not self.dataset_exists(table.dataset):
return False
try:
self.client.tables().get(projectId=table.project_id,
... | csn |
Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr | def parseAttributes(self, attributes=None, **kwAttributes):
"""Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is not None e... | csn |
Parses an RFC1630 query string into an existing Map.
@param str Query string
@param res Map into which insert the values.
@param encoding Encoding to be used for stored Strings | public static void parseQueryString( String str, Map res, String encoding )
{
// "Within the query string, the plus sign is reserved as
// shorthand notation for a space. Therefore, real plus signs must
// be encoded. This method was used to make query URIs easier to
// pass in syst... | csn |
Store Alias Account
Create or update an alias account, by it's username.
@param string $username
@param boolean $should_propagate_password
@param string $password
@param int $account_id
@param string $account_identifier
@param string $account_username
@param DateTime $expires_at
@param boolean $disabled
@return \Unir... | public function store(
$username,
$should_propagate_password = null,
$password = null,
$account_id = null,
$account_identifier = null,
$account_username = null,
$expires_at = null,
$disabled = null
)
{
$fields = [];
//@todo validate... | csn |
Change a configuration entry
@param \Thelia\Core\Event\Config\ConfigUpdateEvent $event
@param $eventName
@param EventDispatcherInterface $dispatcher | public function modify(ConfigUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $config = ConfigQuery::create()->findPk($event->getConfigId())) {
$config->setDispatcher($dispatcher)
->setName($event->getEventName())
->setValue($ev... | csn |
Recursively update a top-level option in the run control
Parameters
----------
k : string
the top-level key
d : dictionary or similar
the dictionary to use for updating | def recursive_update(self, k, d):
"""Recursively update a top-level option in the run control
Parameters
----------
k : string
the top-level key
d : dictionary or similar
the dictionary to use for updating
"""
u = self.__getitem__(k)
... | csn |
Internal, removes an interface from a bridge | def _linux_delif(br, iface):
'''
Internal, removes an interface from a bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delif {1} {2}'.format(brctl, br, iface),
python_shell=False) | csn |
// Poll until the proof succeeds, limited to an hour. | func (p *Prove) verifyLoop(m libkb.MetaContext) (err error) {
timeout := time.Hour
m, cancel := m.WithTimeout(timeout)
defer cancel()
uierr := m.UIs().ProveUI.Checking(m.Ctx(), keybase1.CheckingArg{
Name: p.serviceType.DisplayName(),
})
if uierr != nil {
m.Warning("prove ui Checking call error: %s", uierr)
}... | csn |
Write a mingus.Composition to a MIDI file. | def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Composition to a MIDI file."""
m = MidiFile()
t = []
for x in range(len(composition.tracks)):
t += [MidiTrack(bpm)]
m.tracks = t
while repeat >= 0:
for i in range(len(composition.tracks)... | csn |
returns the character start and end position of the span of text that
the given node spans or dominates.
Returns
-------
offsets : tuple(int, int)
character onset and offset of the span | def get_span_offsets(docgraph, node_id):
"""
returns the character start and end position of the span of text that
the given node spans or dominates.
Returns
-------
offsets : tuple(int, int)
character onset and offset of the span
"""
try:
span = get_span(docgraph, node_... | csn |
// UaaPassword builds an OauthStrategy for UAA using password_grant token requests | func UaaPassword(clientId, clientSecret, username, password string) Builder {
return Uaa(clientId, clientSecret, username, password, "", "", false)
} | csn |
Load the writer from the provided `writer_configs`. | def load_writer_configs(writer_configs, ppp_config_dir,
**writer_kwargs):
"""Load the writer from the provided `writer_configs`."""
try:
writer_info = read_writer_config(writer_configs)
writer_class = writer_info['writer']
except (ValueError, KeyError, yaml.YAMLError)... | csn |
// periodicUnblockFailedEvals periodically unblocks failed, blocked evaluations. | func (s *Server) periodicUnblockFailedEvals(stopCh chan struct{}) {
ticker := time.NewTicker(failedEvalUnblockInterval)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
// Unblock the failed allocations
s.blockedEvals.UnblockFailed()
}
}
} | csn |
// CreateTargetHTTPSProxy creates and returns a TargetHTTPSProxy with the given URLMap and SslCertificate. | func (gce *Cloud) CreateTargetHTTPSProxy(urlMap *compute.UrlMap, sslCert *compute.SslCertificate, name string) (*compute.TargetHttpsProxy, error) {
proxy := &compute.TargetHttpsProxy{
Name: name,
UrlMap: urlMap.SelfLink,
SslCertificates: []string{sslCert.SelfLink},
}
op, err := gce.service.... | csn |
The generic wiring code is not working on android.
Explicitly call the wiring methods. | @SuppressWarnings("unchecked")
private void configureViaSettersDirect(HeapCache<K,V> c) {
if (config.getLoader() != null) {
Object obj = c.createCustomization(config.getLoader());
if (obj instanceof CacheLoader) {
final CacheLoader<K,V> _loader = (CacheLoader) obj;
c.setAdvancedLoader... | csn |
Get the longest size an handle can have.
@return int | protected function getLongestSize()
{
if ($this->longest) {
return $this->longest;
}
// Build possible handles
$strings = [];
$connections = $this->connections->getActiveConnections();
$stages = (array) $this->connections->getAvailableStages() ?: [''];
... | csn |
Generate token used to trace execution of operation across multiple packets
=== Return
tr(String):: Trace token, may be empty | def trace
audit_id = self.respond_to?(:payload) && payload.is_a?(Hash) && (payload['audit_id'] || payload[:audit_id])
tok = self.respond_to?(:token) && token
tr = "<#{audit_id || nil}> <#{tok}>"
end | csn |
Create a new SignedRequest from PHP globals.
@return SignedRequest
@throws ValidationException when a required parameter is missing. | public static function createFromGlobals()
{
$body = file_get_contents('php://input');
$queryParameters = $_GET;
$requestTimestamp = $_SERVER['HTTP_MESSAGEBIRD_REQUEST_TIMESTAMP'];
$signature = $_SERVER['HTTP_MESSAGEBIRD_SIGNATURE'];
$signedRequest = new SignedRequest();
... | csn |
Return the names of valid color variants, given the base colors. | def derivative_colors(colors):
"""Return the names of valid color variants, given the base colors."""
return set([('on_' + c) for c in colors] +
[('bright_' + c) for c in colors] +
[('on_bright_' + c) for c in colors]) | csn |
Fizzbuzz benchmark using motif pattern matching. | @Benchmark
public void fizzBuzzPatternMatching() {
IntStream.range(0, 101).forEach(
n -> System.out.println(
match(Tuple2.of(n % 3, n % 5))
.when(tuple2(eq(0), eq(0))).get(() -> "FizzBuzz")
.when(tuple2(eq(0), any())).get(y -> "Fizz")
.when(tuple... | csn |
Given a map of Overlays, apply all applicable compositors. | def collapse(cls, holomap, ranges=None, mode='data'):
"""
Given a map of Overlays, apply all applicable compositors.
"""
# No potential compositors
if cls.definitions == []:
return holomap
# Apply compositors
clone = holomap.clone(shared_data=False)
... | csn |
// SetRaw convert the string or time.Time to DateTimeField | func (e *DateTimeField) SetRaw(value interface{}) error {
switch d := value.(type) {
case time.Time:
e.Set(d)
case string:
v, err := timeParse(d, formatDateTime)
if err != nil {
e.Set(v)
}
return err
default:
return fmt.Errorf("<DateTimeField.SetRaw> unknown value `%s`", value)
}
return nil
} | csn |
Retrieve a listing of Namespaces
:param paginate: If true will perform pagination based on settings.
:param marker: Specifies the namespace of the last-seen namespace.
The typical pattern of limit and marker is to make an
initial limited request and then to use the last
n... | def metadefs_namespace_list(request,
filters=None,
sort_dir='asc',
sort_key='namespace',
marker=None,
paginate=False):
"""Retrieve a listing of Namespaces
:param paginate:... | csn |
// Put stores a value by key. 0-length keys results in no-op | func (s *AESEncryptedStorage) Put(key, value string) {
if len(key) == 0 {
return
}
data, err := s.readEncryptedStorage()
if err != nil {
log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
return
}
ciphertext, iv, err := encrypt(s.key, []byte(value), []byte(key))
if err != nil {
... | csn |
Create list of all gene products as sbml readable elements. | def _add_gene_list(self, parent_tag, gene_id_dict):
"""Create list of all gene products as sbml readable elements."""
list_all_genes = ET.SubElement(parent_tag, _tag(
'listOfGeneProducts', FBC_V2))
for id, label in sorted(iteritems(gene_id_dict)):
gene_tag = ET.SubElement... | csn |
Delete Entity when last Data object is deleted. | def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | csn |
Helper method used by `_processConditions`.
@param string The field name string.
@param array The operator to parse.
@param array The schema of the field.
@param string The glue operator (e.g `'AND'` or '`OR`'.
@return mixed Returns the operator expression string or `false` if no operator
is applicable.
@throws A `Que... | protected function _processOperator($key, $value, $fieldMeta, $glue) {
if (!is_string($key) || !is_array($value)) {
return false;
}
$operator = strtoupper(key($value));
if (!is_numeric($operator)) {
if (!isset($this->_operators[$operator])) {
throw new QueryException("Unsupported operator `{$operator}... | csn |
// removeSectionHead removes the reference to a processed section from the index
// database. | func (c *ChainIndexer) removeSectionHead(section uint64) {
var data [8]byte
binary.BigEndian.PutUint64(data[:], section)
c.indexDb.Delete(append([]byte("shead"), data[:]...))
} | csn |
Create a new EBS Volume.
:type size: int
:param size: The size of the new volume, in GiB
:type zone: string or :class:`boto.ec2.zone.Zone`
:param zone: The availability zone in which the Volume will be created.
:type snapshot: string or :class:`boto.ec2.snapshot.Snapshot`
... | def create_volume(self, size, zone, snapshot=None):
"""
Create a new EBS Volume.
:type size: int
:param size: The size of the new volume, in GiB
:type zone: string or :class:`boto.ec2.zone.Zone`
:param zone: The availability zone in which the Volume will be created.
... | csn |
Create a typecheck from some value ``t``. This behaves differently
depending on what ``t`` is. It should take a value and return True if
the typecheck passes, or False otherwise. Override ``pre_validate``
in a child class to do type coercion.
* If ``t`` is a type, like basestring, in... | def typecheck(self, t):
"""Create a typecheck from some value ``t``. This behaves differently
depending on what ``t`` is. It should take a value and return True if
the typecheck passes, or False otherwise. Override ``pre_validate``
in a child class to do type coercion.
* If `... | csn |
Handles `GUILD_MEMBERS_CHUNK` packets.
@param object $data Packet data. | protected function handleGuildMembersChunk($data)
{
$guild = $this->guilds->get('id', $data->d->guild_id);
$members = $data->d->members;
$this->logger->debug('received guild member chunk', ['guild_id' => $guild->id, 'guild_name' => $guild->name, 'member_count' => count($members)]);
... | csn |
Get all possible locale names in the passed locale
@param aContentLocale
the locale ID in which the language list is required
@return The mapping from the input locale to the display text. The result
map is not ordered. | @Nonnull
@ReturnsMutableCopy
public static ICommonsMap <Locale, String> getAllLocaleDisplayNames (@Nonnull final Locale aContentLocale)
{
ValueEnforcer.notNull (aContentLocale, "ContentLocale");
return new CommonsHashMap <> (LocaleCache.getInstance ().getAllLocales (),
F... | csn |
Get a listing of all neighbors for all sites in a structure
Args:
structure (Structure): Input structure
Return:
List of NN site information for each site in the structure. Each
entry has the same format as `get_nn_info` | def get_all_nn_info(self, structure):
"""Get a listing of all neighbors for all sites in a structure
Args:
structure (Structure): Input structure
Return:
List of NN site information for each site in the structure. Each
entry has the same format as `get_nn... | csn |
Generate extra HTML output to facilitate the dynamic duplication logic
@param int $intCount
@return string | protected function getDynamicHtml($intCount = 0)
{
$strReturn = "";
if ($this->__dynamic && ! empty($this->__dynamicLabel)) {
$arrFields = array();
// Generate an array of field id's
foreach ($this->__fields as $field) {
switch (get_class($field))... | csn |
// List returns all of the transferJobs under a specific project. If the variadic argument "statuses"
// is provided, only jobs with the listed statuses are returned | func (t *Transferer) List(project string, statuses ...Status) ([]*storagetransfer.TransferJob, error) {
var jobs []*storagetransfer.TransferJob
var token string
body, err := json.Marshal(struct {
ProjectID string `json:"project_id"`
JobStatuses []Status `json:"job_statuses,omitempty"`
}{
ProjectID: pro... | csn |
Parse a YAML specification of a component group into this
object. | def parse_yaml(self, node):
'''Parse a YAML specification of a component group into this
object.
'''
self.group_id = y['groupId']
self._members = []
if 'members' in y:
for m in y.get('members'):
self._members.append(TargetComponent().parse_yam... | csn |
// readDir reads the directory named by dirname and returns
// a list of sorted directory entries. | func readDir(dirname string) ([]os.FileInfo, error) {
f, e := os.Open(dirname)
if e != nil {
return nil, e
}
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
if e = f.Close(); e != nil {
return nil, e
}
sort.Sort(byDirName(list))
return list, nil
} | csn |
Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group. | def insert_group(node, target):
"""Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group.
"""
gr... | csn |
// NewNginxParser parses the nginx conf file to find log_format with the given
// name and returns a parser for this format. It returns an error if cannot find
// the given log format. | func NewNginxParser(conf io.Reader, name string) (parser *Parser, err error) {
scanner := bufio.NewScanner(conf)
re := regexp.MustCompile(fmt.Sprintf(`^\s*log_format\s+%v\s+(.+)\s*$`, name))
found := false
var format string
for scanner.Scan() {
var line string
if !found {
// Find a log_format definition
... | csn |
Converts the CPE into the CPE 2.2 URI format.
@return the CPE 2.2 URI format of the CPE
@throws CpeEncodingException thrown if the CPE is not well formed | @Override
public String toCpe22Uri() throws CpeEncodingException {
StringBuilder sb = new StringBuilder("cpe:/");
sb.append(Convert.wellFormedToCpeUri(part)).append(":");
sb.append(Convert.wellFormedToCpeUri(vendor)).append(":");
sb.append(Convert.wellFormedToCpeUri(product)).append(... | csn |
Check an entity implments ContainerInterface.
It should be the same type of entities already in collection.
@param mixed $obj
@return bool | private function checkEntity( $obj )
{
if( $class = $this->classGet() and !( $obj instanceof $class ) ) {
throw new \InvalidArgumentException(
sprintf(
'Obj %s is not compatible with Container of class %s',
get_class( $obj ),
... | csn |
Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface.
@return DMSInterface An instance of the Document Management System | public static function inst()
{
if (!self::$instance) {
self::$instance = new static();
$dmsPath = self::$instance->getStoragePath();
if (!is_dir($dmsPath)) {
self::$instance->createStorageFolder($dmsPath);
}
if (!file_exists($dm... | csn |
// Address will return a string of the host and port separated by a colon. | func (c SMTPConfig) Address() string {
return fmt.Sprintf("%s:%d", c.Host, c.Port)
} | csn |
Set an element to active
@param string $name element's name
@return Navigation | public function setActive($name) {
$element = $this->getElement($name);
if ($element instanceof Element) {
$element->setActive();
}
return $this;
} | csn |
`tr '0-9a-f' 'a-p'` in JS
@param {string} hex like '8a7f7d'
@return {string} | function hex2a(hex) {
return Array.from(hex)
.map(s => {
if (s >= "0" && s <= "9") {
return String.fromCharCode(s.charCodeAt(0) + N_TO_A);
} else if (s >= "a" && s <= "f") {
return String.fromCharCode(s.charCodeAt(0) + A_TO_K);
}
throw new Error(`invalid char: ${s}`);
}... | csn |
Gets the alias
@return string | public function getAlias() {
//Check and see if there is another relationship with the same name
$multipleFound = false;
foreach($this->getRelationships() as $relationship) {
if($relationship !== $this && $relationship->getRemoteTable() == $this->getRemoteTable()) {
$... | csn |
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column. | def addRow(self, *value):
"""
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments ... | csn |
Returns directory where to store class and create it if needed
@uses AbstractGeneratorAware::getGenerator()
@uses AbstractModel::getOptionCategory()
@uses AbstractGeneratorAware::getContextualPart()
@uses GeneratorOptions::VALUE_CAT
@return string | public function getSubDirectory()
{
$subDirectory = '';
if ($this->getGenerator()->getOptionCategory() === GeneratorOptions::VALUE_CAT) {
$subDirectory = $this->getContextualPart();
}
return $subDirectory;
} | csn |
Import a virtual tile from a file rather than an installed module
script_path must point to a python file ending in .py that contains exactly one
VirtualTile class definition. That class is loaded and executed as if it
were installed.
To facilitate development, if there is a proxy obj... | def LoadFromFile(cls, script_path):
"""Import a virtual tile from a file rather than an installed module
script_path must point to a python file ending in .py that contains exactly one
VirtualTile class definition. That class is loaded and executed as if it
were installed.
To ... | csn |
Delete the specified object.
Arguments:
handle -- Handle of object to delete. | def delete(self, handle):
"""Delete the specified object.
Arguments:
handle -- Handle of object to delete.
"""
self._check_session()
self._rest.delete_request('objects', str(handle)) | csn |
this function returns all indexer configurations found in DB
independant of PID | public function getConfigurations()
{
$fields = '*';
$table = 'tx_kesearch_indexerconfig';
$queryBuilder = Db::getQueryBuilder('tx_kesearch_index');
return $queryBuilder
->select($fields)
->from($table)
->execute()
->fetchAll();
} | csn |
Element-wise real part
Raises:
NoConjugateMatrix: if entries have no `conjugate` method and no
other way to determine the real part
Note:
A mathematically equivalent way to obtain a real matrix from a
complex matrix ``M`` is::
(M.con... | def real(self):
"""Element-wise real part
Raises:
NoConjugateMatrix: if entries have no `conjugate` method and no
other way to determine the real part
Note:
A mathematically equivalent way to obtain a real matrix from a
complex matrix ``M`` i... | csn |
// Privmsgf is the variadic version of Privmsg that formats the message
// that is sent to the target nick or channel t using the
// fmt.Sprintf function. | func (conn *Conn) Privmsgf(t, format string, a ...interface{}) {
msg := fmt.Sprintf(format, a...)
conn.Privmsg(t, msg)
} | csn |
Convenience method for fragment activator to obtain raw layouts for fragments during
initialization. | @Override
public Document getFragmentLayout(IPerson person, IUserProfile profile) {
return this._safeGetUserLayout(person, profile);
} | csn |
Acquire lock for dvc repo. | def lock(self):
"""Acquire lock for dvc repo."""
try:
self._do_lock()
return
except LockError:
time.sleep(self.TIMEOUT)
self._do_lock() | csn |
Yield tuples of exchange compounds.
Each exchange compound is a tuple of compound, reaction ID, lower and
upper flux limits. | def parse_exchange(self):
"""Yield tuples of exchange compounds.
Each exchange compound is a tuple of compound, reaction ID, lower and
upper flux limits.
"""
if 'media' in self._model:
if 'exchange' in self._model:
raise ParseError('Both "media" and ... | csn |
Return a lookup table of the sum-of-factorial part of the radial
polynomial of the zernike indexes passed
zernike_indexes - an Nx2 array of the Zernike polynomials to be
computed. | def construct_zernike_lookuptable(zernike_indexes):
"""Return a lookup table of the sum-of-factorial part of the radial
polynomial of the zernike indexes passed
zernike_indexes - an Nx2 array of the Zernike polynomials to be
computed.
"""
n_max = np.max(zernike_indexes[:,0... | csn |
Write modbus registers.
The Modbus protocol doesn't allow requests longer than 250 bytes
(ie. 125 registers, 62 DF addresses), which this function manages by
chunking larger requests. | async def write_registers(self, address, values, skip_encode=False):
"""Write modbus registers.
The Modbus protocol doesn't allow requests longer than 250 bytes
(ie. 125 registers, 62 DF addresses), which this function manages by
chunking larger requests.
"""
while len(v... | csn |
Adds a gradient endpoint at the specified position.
@param position The endpoint position. May be Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY for endpoints.
@param color
@return
@see java.util.Map#put(java.lang.Object, java.lang.Object) | @Override
public Color put(Double position, Color color) {
if( position == null ) {
throw new NullPointerException("Null endpoint position");
}
if( color == null ){
throw new NullPointerException("Null colors are not allowed.");
}
return mapping.put(position, color);
} | csn |
// CharmModifiedVersion returns the most CharmModifiedVersion for all given
// units or applications. | func (u *UniterAPI) CharmModifiedVersion(args params.Entities) (params.IntResults, error) {
results := params.IntResults{
Results: make([]params.IntResult, len(args.Entities)),
}
accessUnitOrApplication := common.AuthAny(u.accessUnit, u.accessApplication)
canAccess, err := accessUnitOrApplication()
if err != ni... | csn |
// BootstrapEnv bootstraps the Juju environment. | func (dp DefaultProvider) BootstrapEnv(ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams) (*environs.BootstrapResult, error) {
result, err := Bootstrap(ctx, dp.Env, callCtx, args)
if err != nil {
return nil, errors.Trace(err)
}
return result, nil
} | csn |
Extract namespace from class name
@param string $class class name
@return string $class class name | private static function _extractClassName($cls)
{
$tokens = preg_split("/\\\\/", $cls);
$size = sizeof($tokens);
if ($size < 2) {
return $cls;
}
return $tokens[$size-1];
} | csn |
Validate syntax.
@access protected
@param string $procedure
@return void
@throws \JonnyW\PhantomJs\Exception\SyntaxException | protected function validateSyntax($procedure)
{
$input = new Input();
$output = new Output();
$input->set('procedure', $procedure);
$input->set('engine', $this->engine->toString());
$validator = $this->procedureLoader->load('validator');
$validator->run($input, $ou... | csn |
Reindex the page block items in order to get requestd sorting.
@param unknown $navItemPageId
@param unknown $placeholderVar
@param unknown $prevId | private function reindex($navItemPageId, $placeholderVar, $prevId)
{
$index = 0;
$datas = self::originalFind()->andWhere(['nav_item_page_id' => $navItemPageId, 'placeholder_var' => $placeholderVar, 'prev_id' => $prevId])->orderBy(['sort_index' => SORT_ASC, 'timestamp_create' => SORT_DESC])->all();
... | csn |
Attach a list of files represented as AttachedFile. | def attach_files(self, files: Sequence[AttachedFile]):
'''
Attach a list of files represented as AttachedFile.
'''
assert not self._content, 'content must be empty to attach files.'
self.content_type = 'multipart/form-data'
self._attached_files = files | csn |
Write the pid file out with the process number in the pid file | def _write_pidfile(self):
"""Write the pid file out with the process number in the pid file"""
LOGGER.debug('Writing pidfile: %s', self.pidfile_path)
with open(self.pidfile_path, "w") as handle:
handle.write(str(os.getpid())) | csn |
Return a QTextCharFormat with the given attributes. | def _format(color, style=''):
"""Return a QTextCharFormat with the given attributes.
"""
_color = QColor()
_color.setNamedColor(color)
_format = QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QFont.Bold)
if 'italic' in style:
... | csn |
change notification notification status
@param IndexListener $listener
@param mixed $id
@return RedirectResponse | public function changeStatus(IndexListener $listener, $id)
{
$model = $this->repository->find($id);
if (is_null($model)) {
return $listener->changeStatusFailed();
}
$model->active = $model->active ? 0 : 1;
$model->save();
return $listener->changeStatusSucc... | csn |
Notify interested listeners that a property has been resolved.
@param base The object on which the property was resolved
@param property The property that was resolved
@since EL 3.0 | public void notifyPropertyResolved(Object base, Object property) {
for (EvaluationListener listener : listeners) {
try {
listener.propertyResolved(this, base, property);
} catch (Throwable t) {
Util.handleThrowable(t);
// Ignore - no option... | csn |
Decrypts the file ``file``.
The encrypted file is assumed to end with the ``.enc`` extension. The
decrypted file is saved to the same location without the ``.enc``
extension.
The permissions on the decrypted file are automatically set to 0o600.
See also :func:`doctr.local.encrypt_file`. | def decrypt_file(file, key):
"""
Decrypts the file ``file``.
The encrypted file is assumed to end with the ``.enc`` extension. The
decrypted file is saved to the same location without the ``.enc``
extension.
The permissions on the decrypted file are automatically set to 0o600.
See also :f... | csn |
returns the calling class' name and dictionary | def class_space(classlevel=3):
"returns the calling class' name and dictionary"
frame = sys._getframe(classlevel)
classname = frame.f_code.co_name
classdict = frame.f_locals
return classname, classdict | csn |
Retorna valores de uma entidade correspondente ao seu armazenamento em sql na sua tabela
@return array | private function getDataOnlyEntity(): array
{
$data = [];
foreach ($this->dicionario as $meta) {
if (!in_array($meta->getFormat(), ["extend_mult", "list_mult", "selecao_mult", "information", "checkbox_mult"]) && ($meta->getFormat() !== "password" || strlen($meta->getValue()) > 3))
... | csn |
// NewWorker returns a worker that unlocks the model upgrade gate. | func NewWorker(config Config) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
// There are no upgrade steps for a CAAS model.
// We just set the status to available and unlock the gate.
return jujuworker.NewSimpleWorker(func(<-chan struct{}) error {
setStatus ... | csn |
called at detached time to signal that an element's bindings should be cleaned up. This is done asynchronously so that users have the chance to call `cancelUnbindAll` to prevent unbinding. | function() {
if (!this._unbound) {
log.unbind && console.log('[%s] asyncUnbindAll', this.localName);
this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0);
}
} | csn |
We save it the first time we get a control connection channel. | private void savePort(DriverChannel channel) {
if (port < 0) {
SocketAddress address = channel.getEndPoint().resolve();
if (address instanceof InetSocketAddress) {
port = ((InetSocketAddress) address).getPort();
}
}
} | csn |
Extracts characters from indexA up to but not including `indexB`.
@param {Number} indexA An integer between `0` and one less than the
length of the text.
@param {Number} [indexB] An integer between `0` and the length of the
string. If omitted, extracts characters to the end of the text. | function( indexA, indexB ) {
// We need the following check due to a Firefox bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=458886
if ( typeof indexB != 'number' )
return this.$.nodeValue.substr( indexA );
else
return this.$.nodeValue.substring( indexA, indexB );
} | csn |
// HasRight checks if an AccessKey has a certain right | func (k *AccessKey) HasRight(right Right) bool {
for _, r := range k.Rights {
if r == right {
return true
}
}
return false
} | csn |
Devuelve una plantilla renderizada del framework
@param string $template La ubicación de la plantilla
@param string $layout La ubicación del layout | public function getCoreRenderedTemplate( $template, $layout = NULL ) {
return $this->render(POWERON_ROOT . DS . $template, $layout ? POWERON_ROOT . DS . $layout : NULL);
} | csn |
Validate configuration for a creating MySQL table based on class configuration | function validateTableConfig(obj) {
/** If configuration has missing or invalid 'tableName' configuration, throw error */
if ( typeof obj.tableName !== `string` || !obj.tableName.match(/^[a-z_]+$/) )
throw new Error(`ezobjects.validateTableConfig(): Configuration has missing or invalid 'tableName', must be st... | csn |
Index super column name.
@param superColumnName
the super column name
@param currentDoc
the current doc | private void addSuperColumnNameToDocument(String superColumnName, Document currentDoc) {
Field luceneField = new Field(SUPERCOLUMN_INDEX, superColumnName, Store.YES, Field.Index.NO);
currentDoc.add(luceneField);
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.