query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Gets all service names | public function getNames()
{
$names = array_keys($this->getServices());
$len = strlen(self::METHOD_PREFIX);
foreach (get_class_methods($this) as $method) {
if (Text::startsWith($method, self::METHOD_PREFIX)) {
$name = lcfirst(substr($method, $len));
... | csn |
Return the verified Class Name of a model
@param string $modelo The model name
@param string $probable Optional The probable initial Model Class Name
@return boolean|string The Class Name or false if not found | private static function getModel($modelo, $probable = '') {
$modeloClass = $probable;
if (!class_exists($modeloClass)) {
$modeloClass = "App\\" . $modelo;
if (!class_exists($modeloClass)) {
$modelo = strtolower($modelo);
$modeloM = ucfirst($modelo)... | csn |
func (rs *ResultSet) Values() Values {
values := []Value{}
for _, item := range rs.items {
switch i := item.(type) {
case Value:
values = append(values, i)
case | *ResultSet:
values = append(values, i.Values()...)
}
}
return values
} | csn_ccr |
func makeACLETag(parent string, policy *acl.Policy) string {
return | fmt.Sprintf("%s:%s", parent, policy.ID)
} | csn_ccr |
// StopInbounds is the first step in shutdown. It stops all inbounds
// configured on the dispatcher, which stops routing RPCs to all registered
// procedures. It's safe to call concurrently, but all calls after the first
// return an error. | func (s *PhasedStopper) StopInbounds() error {
if s.inboundsStopInitiated.Swap(true) {
return errors.New("already began stopping inbounds")
}
defer s.inboundsStopped.Store(true)
s.log.Debug("stopping inbounds")
wait := errorsync.ErrorWaiter{}
for _, ib := range s.dispatcher.inbounds {
wait.Submit(ib.Stop)
}
... | csn |
func checkCandidateSrcset(l *absurllexer) {
q := l.consumeQuote()
if q == nil {
// srcset needs to be quoted.
return
}
// special case, not frequent (me think)
if !bytes.HasPrefix(l.content[l.pos:], relURLPrefix) {
return
}
// check for schemaless URLs
posAfter := l.pos + relURLPrefixLen
if posAfter >=... |
if r == '/' {
// schemaless: skip
return
}
posEnd := l.posAfterURL(q)
// safe guard
if posEnd < 0 || posEnd > 2000 {
return
}
if l.pos > l.start {
l.emit()
}
section := l.content[l.pos : l.pos+posEnd+1]
fields := bytes.Fields(section)
for i, f := range fields {
if f[0] == '/' {
l.w.Write(l... | csn_ccr |
Determine if the given result is success.
@param mixed $result
@return bool | protected function isSuccess($result): bool
{
return ! is_null($result) ? (is_string($result) && $result === 'true') || (is_bool($result) && $result) : false;
} | csn |
Set Theme Template
@param string $tamplate | public function setThemeTemplate($template)
{
$this->_themeTemplate = $template;
if ($this->getTheme() != null) {
$this->getTheme()->setTemplate($this->_themeTemplate);
}
} | csn |
Will walk the AST upwards until a function-like node is met
and at each level walk all previous siblings and their children to search for definitions
of that variable
@param Node $node
@param string $namePrefix Prefix to filter
@return array <Node\Expr\Variable|Node\Param|Node\Expr\ClosureUse> | private function suggestVariablesAtNode(Node $node, string $namePrefix = ''): array
{
$vars = [];
// Find variables in the node itself
// When getting completion in the middle of a function, $node will be the function node
// so we need to search it
foreach ($this->findVaria... | csn |
function handleUpdateFile(response) {
var path = response.path,
type = response.type,
$deferredHints = getPendingRequest(path, OFFSET_ZERO, type);
|
if ($deferredHints) {
$deferredHints.resolve();
}
} | csn_ccr |
private int getDatastreamPaneIndex(String id) {
int index = -1;
for (int i=0; i < m_datastreamPanes.length; i++)
| {
if(m_datastreamPanes[i].getItemId().equals(id)){
index = i;
break;
}
}
return index;
} | csn_ccr |
Redirects to the original entity when conditions are met.
@param \Drupal\Core\Url $url
The canonical url.
@param \Drupal\comment\CommentInterface $comment
The comment interface.
@param \Drupal\Core\Entity\Entity $entity
The Entity to redirect to.
@return \Symfony\Component\HttpFoundation\RedirectResponse
Returns the ... | public function redirectToOriginalEntity(Url $url, CommentInterface $comment = NULL, Entity $entity = NULL) {
$options = [];
if (isset($comment)) {
$options = ['fragment' => 'comment-' . $comment->id()];
}
return $this->redirect($url->getRouteName(), $url->getRouteParameters(), $options);
} | csn |
Check that a kafka topic exist
@param topic_name name of topic | @Then("^A kafka topic named '(.+?)' exists")
public void kafkaTopicExist(String topic_name) throws KeeperException, InterruptedException {
assert commonspec.getKafkaUtils().getZkUtils().pathExists("/" + topic_name) : "There is no topic with that name";
} | csn |
datastructure to hold coordinates in python | def make_coord_dict(coord):
"""helper function to make a dict from a coordinate for logging"""
return dict(
z=int_if_exact(coord.zoom),
x=int_if_exact(coord.column),
y=int_if_exact(coord.row),
) | cosqa |
def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
| account.housemate
except Housemate.DoesNotExist:
pass
else:
raise ValidationError('Account already has a housemate')
return account | csn_ccr |
DS method for setting the event reference.
@param service | @Reference(service = EventEngine.class,
cardinality = ReferenceCardinality.MANDATORY)
protected void setEventService(EventEngine service) {
this.eventService = service;
} | csn |
def url(self, version=None, **kwargs):
"""Returns the first matching URL found for the specified arguments"""
for url in self.urls(version):
if [key for key in kwargs.keys() if not '{' + key + '}' in url]:
| continue
return url.format(**kwargs)
raise KeyError('URL that takes all provided parameters not found') | csn_ccr |
// RemoveLast removes the last index position from the end of the list. | func (iv *indexVector) RemoveLast() {
l := len(*iv)
if l > 0 {
*iv = (*iv)[:l-1]
}
} | csn |
Allows the first input to be a numpy array and get result in numpy form | def accepts_numpy(func):
""" Allows the first input to be a numpy array and get result in numpy form """
#@ignores_exc_tb
#@wraps(func)
def wrp_accepts_numpy(self, input_, *args, **kwargs):
if not (util_type.HAVE_NUMPY and isinstance(input_, np.ndarray)):
# If the input is not numpy,... | csn |
store database credentials on environment variable in python | def set_user_password(environment, parameter, password):
"""
Sets a user's password in the keyring storage
"""
username = '%s:%s' % (environment, parameter)
return password_set(username, password) | cosqa |
protected function checkBrowserBlackBerry()
{
$found = false;
//Tablet OS check
if ($this->checkSimpleBrowserUA('RIM Tablet OS', $this->_agent, self::BROWSER_TABLET_OS, true)) {
return true;
}
//Version 6, 7 & 10 check (versions 8 & 9 does not exists)
if... | }
}
//Version 4.2 to 5.0 check
if ($this->checkSimpleBrowserUA('BlackBerry', $this->_agent, self::BROWSER_BLACKBERRY, true, false, '/', false)) {
if ($this->getVersion() == self::VERSION_UNKNOWN) {
$found = true;
} else {
retur... | csn_ccr |
Renders the upload field.
@return string
@api | public function render()
{
$nameAttribute = $this->getName();
$this->registerFieldNameForFormTokenGeneration($nameAttribute);
$output = '';
$resource = $this->getUploadedResource();
if ($resource !== null) {
$resourceIdentityAttribute = '';
if ($this-... | csn |
Given an array of integers your solution should find the smallest integer.
For example:
- Given `[34, 15, 88, 2]` your solution will return `2`
- Given `[34, -345, -1, 100]` your solution will return `-345`
You can assume, for the purpose of this kata, that the supplied array will not be empty. | def find_smallest_int(arr):
return min(arr); | apps |
Register a callable which can perform a schema upgrade between two
particular versions.
@param upgrader: A one-argument callable which will upgrade an object. It
is invoked with an instance of the old version of the object.
@param typeName: The database typename for which this is an upgrader.
@par... | def registerUpgrader(upgrader, typeName, oldVersion, newVersion):
"""
Register a callable which can perform a schema upgrade between two
particular versions.
@param upgrader: A one-argument callable which will upgrade an object. It
is invoked with an instance of the old version of the object.
... | csn |
func sb5(r0, r1, r2, r3 *uint32) {
*r0 ^= *r1
*r1 ^= *r3
*r3 = ^*r3
r4 := *r1
*r1 &= *r0
*r2 ^= *r3
*r1 ^= *r2
*r2 |= r4
r4 ^= *r3
| *r3 &= *r1
*r3 ^= *r0
r4 ^= *r1
r4 ^= *r2
*r2 ^= *r0
*r0 &= *r3
*r2 = ^*r2
*r0 ^= r4
r4 |= *r3
*r2 ^= r4
//return *r1, *r3, *r0, *r2
r4 = *r0
*r0 = *r1
*r1 = *r3
*r3 = *r2
*r2 = r4
} | csn_ccr |
// Pad will pad the data relative to how many bytes have been read.
// Pad follows the PKCS7 standard. | func (padder pkcs7Padder) Pad(buf []byte, n int) ([]byte, error) {
if padder.blockSize < 1 || padder.blockSize > pkcs7MaxPaddingSize {
return nil, awserr.New("InvalidBlockSize", "block size must be between 1 and 255", nil)
}
size := padder.blockSize - (n % padder.blockSize)
pad := bytes.Repeat([]byte{byte(size)},... | csn |
Creates the submenu for the Open As choice | def createOpenAsMenu(self, parent=None):
""" Creates the submenu for the Open As choice
"""
openAsMenu = QtWidgets.QMenu(parent=parent)
openAsMenu.setTitle("Open Item As")
registry = globalRtiRegistry()
for rtiRegItem in registry.items:
#rtiRegItem.tryImportC... | csn |
def timezone(self, lat, lon, datetime,
language=None, sensor=None):
"""Get time offset data for given location.
:param lat: Latitude of queried point
:param lon: Longitude of queried point
:param language: The language in which to return results. For full list
... | :type datetime: datetime.datetime
:param sensor: Override default client sensor parameter
"""
parameters = dict(
location="%f,%f" % (lat, lon),
timestamp=unixtimestamp(datetime),
language=language,
sensor=sensor,
)
return self... | csn_ccr |
Make the keywords entry for an ast.Call node. | def make_call_keywords(stack_builders, count):
"""
Make the keywords entry for an ast.Call node.
"""
out = []
for _ in range(count):
value = make_expr(stack_builders)
load_kwname = stack_builders.pop()
if not isinstance(load_kwname, instrs.LOAD_CONST):
raise Decom... | csn |
turn list of lists into one list python | def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l] | cosqa |
anaconda python 3 tensorflow | def transformer_ae_a3():
"""Set of hyperparameters."""
hparams = transformer_ae_base()
hparams.batch_size = 4096
hparams.layer_prepostprocess_dropout = 0.3
hparams.optimizer = "Adafactor"
hparams.learning_rate = 0.25
hparams.learning_rate_warmup_steps = 10000
return hparams | cosqa |
This method is required by the setup method below. | def run_apidoc(_):
"""This method is required by the setup method below."""
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, '../../aaf2/model'),]
# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py
argv = [
'--force',
'--no-... | csn |
def create_entity(self, *components) -> int:
"""Create a new Entity.
This method returns an Entity ID, which is just a plain integer.
You can optionally pass one or more Component instances to be
assigned to the Entity.
:param components: Optional components to be | assigned to the
entity on creation.
:return: The next Entity ID in sequence.
"""
self._next_entity_id += 1
# TODO: duplicate add_component code here for performance
for component in components:
self.add_component(self._next_entity_id, component)
# s... | csn_ccr |
Return the stack of handlers and middlewares responsible for processing
requests.
@return HandlerStack | protected function getHandlerStack()
{
$handlerStack = HandlerStack::create($this->getHandler());
$this->configureHandlerStack($handlerStack);
return $handlerStack;
} | csn |
Remove a command addition from the list of outstanding deferred additions. | public static function remove_deferred_addition( $name ) {
if ( ! array_key_exists( $name, self::$deferred_additions ) ) {
self::warning( "Trying to remove a non-existent command addition '{$name}'." );
}
unset( self::$deferred_additions[ $name ] );
} | csn |
A helper method that converts a json string into a map object.
@param json the json string
@return a map representing the json string.
@throws IOException | protected Map jsonStringToMap(String json) throws IOException {
return new JaxbJsonSerializer<HashMap>(HashMap.class).deserialize(json);
} | csn |
def validateProxy(path):
"""
Test that the proxy certificate is RFC 3820
compliant and that it is valid for at least
the next 15 minutes.
"""
# load the proxy from path
try:
proxy = M2Crypto.X509.load_cert(path)
except Exception, e:
msg = "Unable to load proxy from path ... | # problem getting or parsing time so just let the client
# continue and pass the issue along to the server
secondsLeft = 3600
if secondsLeft <= 0:
msg = """\
Your proxy certificate is expired.
Please generate a new proxy certificate and
try again.
"""
print >>sys.stderr, msg
... | csn_ccr |
public function getValueAttribute($name, $value = null)
{
if (strpos($name, '[]') !== false) {
$name = str_replace('[]', '', $name);
}
if ($this->hasOldInput()) {
return $this->getOldInput($name);
| }
if ($this->hasModelValue($name)) {
return $this->getModelValue($name);
}
return $value;
} | csn_ccr |
def remove(self, nodes):
"""Remove a node and its edges."""
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
| self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k] | csn_ccr |
def isHeld(self):
'''
isHeld - True if anyone holds the lock, otherwise False.
@return bool - If lock is held by anyone
'''
if not os.path.exists(self.lockPath):
return False
try:
| mtime = os.stat(self.lockPath).st_mtime
except FileNotFoundError as e:
return False
if self.__checkExpiration(mtime):
return False
return True | csn_ccr |
Check if file is excluded. | def _is_excluded(self, path, dir_only):
"""Check if file is excluded."""
return self.npatterns and self._match_excluded(path, self.npatterns) | csn |
public void checkpoint(ObjectEnvelope mod)
throws org.apache.ojb.broker.PersistenceBrokerException
{
mod.doDelete();
| mod.setModificationState(StateTransient.getInstance());
} | csn_ccr |
// Computes a mean of the values | func (a *AggregateSample) Mean() float64 {
if a.Count == 0 {
return 0
}
return a.Sum / float64(a.Count)
} | csn |
func (s *VirtualMachineService) NewAddNicToVirtualMachineParams(networkid string, virtualmachineid string) *AddNicToVirtualMachineParams | {
p := &AddNicToVirtualMachineParams{}
p.p = make(map[string]interface{})
p.p["networkid"] = networkid
p.p["virtualmachineid"] = virtualmachineid
return p
} | csn_ccr |
protected void connectionClosed(IoSession session) {
this.connected = false;
this._disconnect();
log.info("Connection lost to aggregator at {}:{}", this.host,
Integer.valueOf(this.port));
while (this.stayConnected) {
try {
Thread.sleep(this.connectionRetryDelay);
} catch (InterruptedException ie)... | if (this.connect(this.connectionTimeout)) {
return;
}
log.warn("Failed to reconnect to aggregator at {}:{}", this.host,
Integer.valueOf(this.port));
}
this.finishConnection();
} | csn_ccr |
// NewTimeAPI constructs a TimeAPI from the given time.Time. It presets the
// timezone for formatting to UTC. | func NewTimeAPI(t time.Time) TimeAPI {
return TimeAPI{
S: dbtypes.NewTimeDef(t),
}
} | csn |
u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict | def etree_to_dict(t, trim=True, **kw):
u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict
"""
d = {t.tag: {} if t.attrib ... | csn |
def to_filename(data,
mask=DEFAULT_PAPERS_FILENAME_MASK,
extra_formatters=None):
"""
Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
... | "authors": "",
"arxiv_version": ""
}
formatters["journal"] = entry.get("journal", "")
formatters["title"] = entry.get("title", "")
formatters["year"] = entry.get("year", "")
formatters["first"] = authors[0].split(',')[0].strip()
formatters["last"] = authors[-1].split(',')[0].stri... | csn_ccr |
Runs forward pass of the encoder.
Encodes source given source length and bucket key.
Returns encoder representation of the source, source_length, initial hidden state of decoder RNN,
and initial decoder states tiled to beam size.
:param source: Integer-coded input tokens. Shape (batch_s... | def run_encoder(self,
source: mx.nd.NDArray,
source_max_length: int) -> Tuple['ModelState', mx.nd.NDArray]:
"""
Runs forward pass of the encoder.
Encodes source given source length and bucket key.
Returns encoder representation of the source, sourc... | csn |
Automatically reloads the config file.
This is just an alias for self.load(). | def reload(self):
"""
Automatically reloads the config file.
This is just an alias for self.load()."""
if not self.fd.closed: self.fd.close()
self.fd = open(self.fd.name, 'r')
self.load() | csn |
def delete_action(plugin, action_id)
the_plugin = hawk_escape plugin
| the_action_id = hawk_escape action_id
http_delete "/actions/#{the_plugin}/#{the_action_id}"
end | csn_ccr |
Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. | def run_all():
""" Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels"
dates = os.listdir("/home/share/LAMOST/DR2/DR2_release")
dates = np.array(dates)
dates = np.delete(date... | csn |
Assume we take a number `x` and perform any one of the following operations:
```Pearl
a) Divide x by 3 (if it is divisible by 3), or
b) Multiply x by 2
```
After each operation, we write down the result. If we start with `9`, we can get a sequence such as:
```
[9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2... | def solve(a):
for i in a:
li = [i]
while 1:
if li[-1] % 3 == 0 and li[-1] // 3 in a : li.append(li[-1] // 3)
elif li[-1] * 2 in a : li.append(li[-1] * 2)
else : break
if len(li) == len(a) : return li | apps |
sets the filesource to use for new items
@author Joel Bout, <joel@taotesting.com>
@param string $filesourceId | public function setDefaultFilesourceId($filesourceId)
{
$ext = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems');
$ext->setConfig(self::CONFIG_DEFAULT_FILESOURCE, $filesourceId);
} | csn |
Parse the reason phrase | protected function reason()
{
$len = strcspn($this->data, "\x0A", $this->position);
$this->reason = trim(substr($this->data, $this->position, $len), "\x09\x0D\x20");
$this->position += $len + 1;
$this->state = 'new_line';
} | csn |
Calculates and sets the possition of the dragger element. | function calculateDraggerPosition() {
var sl = $container.scrollLeft() / scale;
var st = $container.scrollTop() / scale;
// sl / dox = dl / cw
// dl = sl * cw / dox
var left = sl * canvasSize.x / docSize.x;
var top = st * canvasSize.y / docSize.y;
view.setDraggerPosition(left, top);... | csn |
// Has checks if a specific ref is in this set. | func (w RefSet) Has(ref string) bool {
for prefix, wrp := range w.byPrefix {
nsPrefix := prefix + "/"
if strings.HasPrefix(ref, nsPrefix) && wrp.hasRef(ref) {
return true
}
}
return false
} | csn |
func CountBitmap(bitmap, sbit C.MMBitmapRef, args ...float32) int {
var tolerance C.float = | 0.01
if len(args) > 0 {
tolerance = C.float(args[0])
}
count := C.count_of_bitmap(bitmap, sbit, tolerance)
return int(count)
} | csn_ccr |
Take the View's element element out of the DOM
@returns {this} | function()
{
try
{
var el = this.el;
if (el.parentNode)
{
el.parentNode.removeChild(el);
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.DETACH));
}
}
catch(e) {}
return this;
} | csn |
func (s *Set) Flag(v interface{}, short rune, helpvalue ...string) Option {
| return s.long(v, "", short, helpvalue...)
} | csn_ccr |
protected Shape createOuterFocus(final SegmentType segmentType, final int x, final int y, final int w, final int h) {
switch (segmentType) {
case FIRST:
return shapeGenerator.createRoundRectangle(x - 2, y - 2, w + 3, h + 3, CornerSize.OUTER_FOCUS, CornerStyle.ROUNDED,
... | 3, CornerSize.OUTER_FOCUS, CornerStyle.SQUARE,
CornerStyle.SQUARE, CornerStyle.ROUNDED, CornerStyle.ROUNDED);
default:
return shapeGenerator.createRoundRectangle(x - 2, y - 2, w + 3, h + 3, CornerSize.OUTER_FOCUS);
}
} | csn_ccr |
builds the list of BAM tags to be added to output BAMs | def build_bam_tags():
'''builds the list of BAM tags to be added to output BAMs'''
#pylint: disable=unused-argument
def _combine_filters(fam, paired_align, align):
filters = [x.filter_value for x in [fam, align] if x and x.filter_value]
if filters:
return ";".join(filters).replac... | csn |
From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
... | def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 i... | csn |
Create a new context for reading data | def make_context(self, **kwargs):
"""Create a new context for reading data"""
self.check_schema()
return Context(self.driver, self.config, **kwargs) | csn |
func (lifecycle *Lifecycle) Kill() {
lifecycle.mutex.Lock()
lifecycle.killFlag | = true
lifecycle.mutex.Unlock()
} | csn_ccr |
Get Default OptionsValues
@return array | protected function getDefaultOptionsValues()
{
return array(
'data_class' => $this->mediaClass,
'delete_button' => false,
'enable_delete_button' => false,
'group_enabled' => true,
'group_render' => $this->groupRender,
'sub_... | csn |
def emit(self, record):
# pylint: disable=W0212
"""
Handle a message logged with the logger
:param record: A log record
"""
# Get the bundle
bundle = self._bundle_from_module(record.module)
# Convert to a LogEntry
| entry = LogEntry(
record.levelno, record.getMessage(), None, bundle, None
)
self._reader._store_entry(entry) | csn_ccr |
KLT does not have inactive tracks since all tracks are dropped if a problem occurs. | @Override
public List<PointTrack> getInactiveTracks(List<PointTrack> list) {
if( list == null )
list = new ArrayList<>();
return list;
} | csn |
// New returns a new hash.HashF32 interface that computes a 32 bit CrapWow hash. | func New(seed uint32) nhash.HashF32 {
s := new(State)
s.seed = seed
return s
} | csn |
// keyForLevel returns the key for a specific address and level in the address
// index entry. | func keyForLevel(addrKey [addrKeySize]byte, level uint8) [levelKeySize]byte {
var key [levelKeySize]byte
copy(key[:], addrKey[:])
key[levelOffset] = level
return key
} | csn |
private static function myValidateDomainPart(string $domainPart, ?string &$error): bool
{
if ($domainPart === '') {
$error = 'Part of domain "' . $domainPart . '" is empty.';
return false;
}
if (strlen($domainPart) > 63) {
$error = 'Part of domain "' . $... | return false;
}
if (substr($domainPart, 0, 1) === '-') {
$error = 'Part of domain "' . $domainPart . '" begins with "-".';
return false;
}
if (substr($domainPart, -1) === '-') {
$error = 'Part of domain "' . $domainPart . '" ends with "-".';
... | csn_ccr |
Prepares a file with the parameters
@param string $file
@return $file | public static function file( $file )
{
$params = array_merge( static::$params, array(
'time' => time(),
'fingerprint' => \CCSession::fingerprint(),
'random' => CCStr::random(),
));
foreach( $params as $param => $value )
{
$file = str_replace( ':'.$param, $value, $file );
}
return $file;
... | csn |
Get current exchange rate.
:param base: A base currency
:param target: Convert to the target currency
:param error_log: A callable function to track the exception
It parses current exchange rate from these services:
1) Yahoo finance
2) fixer.io
3) European Central Bank
It... | def rate(base, target, error_log=None):
"""Get current exchange rate.
:param base: A base currency
:param target: Convert to the target currency
:param error_log: A callable function to track the exception
It parses current exchange rate from these services:
1) Yahoo finance
2) fi... | csn |
public void removeTableDef(TableDefinition tableDef) {
assert tableDef != null;
assert tableDef.getAppDef() == this;
|
m_tableMap.remove(tableDef.getTableName());
} | csn_ccr |
Sets the active power limits, 'p_max' and 'p_min', according to
the pwl cost function points. | def _adjust_limits(self):
""" Sets the active power limits, 'p_max' and 'p_min', according to
the pwl cost function points.
"""
if not self.is_load:
# self.p_min = min([point[0] for point in self.p_cost])
self.p_max = max([point[0] for point in self.p_cost])
... | csn |
Make an Asynchronous request
@param string $method
@param string $uri
@param array $options
@return \GuzzleHttp\Promise\PromiseInterface
@throws \GuzzleHttp\Exception\GuzzleException | public function requestAsync($method, $uri = null, array $options = [])
{
$options = $this->setRequestOptions($options);
$query = parse_url($uri, PHP_URL_QUERY);
if (!empty($query)) {
$uri = substr($uri, 0, (strlen($query)+1) * -1);
parse_str($query, $options['query'... | csn |
// BuildCancel requests the daemon to cancel ongoing build request | func (cli *Client) BuildCancel(ctx context.Context, id string) error {
query := url.Values{}
query.Set("id", id)
serverResp, err := cli.post(ctx, "/build/cancel", query, nil, nil)
ensureReaderClosed(serverResp)
return err
} | csn |
private function colorizeRatios(Collection $ratios)
{
$colors = ['#F56954', '#00A65A', '#F39C12', '#00C0EF', '#3C8DBC']; |
return $ratios->values()->transform(function (array $values, $key) use ($colors) {
return $values + ['color' => $colors[$key]];
});
} | csn_ccr |
// Decode reads from the stream and decode the content into the MemoryIndex struct. | func (d *Decoder) Decode(idx *MemoryIndex) error {
if err := validateHeader(d); err != nil {
return err
}
flow := []func(*MemoryIndex, io.Reader) error{
readVersion,
readFanout,
readObjectNames,
readCRC32,
readOffsets,
readChecksums,
}
for _, f := range flow {
if err := f(idx, d); err != nil {
... | csn |
Returns a vocabulary with the valid and active instruments available
for the analysis passed in.
If the option "Allow instrument entry of results" for the Analysis
is disabled, the function returns an empty vocabulary.
If the analysis passed in is a Reference Analysis (Blank or Control... | def get_instruments_vocabulary(self, analysis_brain):
"""Returns a vocabulary with the valid and active instruments available
for the analysis passed in.
If the option "Allow instrument entry of results" for the Analysis
is disabled, the function returns an empty vocabulary.
If... | csn |
func (p *Pod) EmptyEnvs() *Pod {
p.Env = | make(map[string]string)
return p
} | csn_ccr |
read an attribute history. IDL 5 version. The history is filled only be
attribute polling
@param attributeName The attribute to retrieve
@param maxSize The history maximum size returned
@throws DevFailed | @Override
public DevAttrHistory_5 read_attribute_history_5(final String attributeName, final int maxSize) throws DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
checkInitialization();
deviceMonitoring.startRequest("read_attribute_history_5");
DevAttrHistory_5 resu... | csn |
def accept_operator(self, precedence):
"""Accept the next binary operator only if it's of higher precedence."""
match = grammar.infix(self.tokens)
if not match:
return
if match.operator.precedence < | precedence:
return
# The next thing is an operator that we want. Now match it for real.
return self.tokens.accept(grammar.infix) | csn_ccr |
def update_config_mode(self, prompt): # pylint: disable=no-self-use
"""Update config mode based on the prompt analysis."""
mode = 'global'
if prompt:
if 'config' in prompt:
| mode = 'config'
elif 'admin' in prompt:
mode = 'admin'
self.log("Mode: {}".format(mode))
return mode | csn_ccr |
Extract the full template type information from the given type's template parameter at the
given position.
@param type type to extract the full template parameter information from
@param templatePosition describing at which position the template type parameter is
@return Full type information describing the template p... | public static FullTypeInfo getFullTemplateType(Type type, int templatePosition) {
if (type instanceof ParameterizedType) {
return getFullTemplateType(((ParameterizedType) type).getActualTypeArguments()[templatePosition]);
} else {
throw new IllegalArgumentException();
}
} | csn |
func recursAddNode(node *client.Node, list []string) []string {
for _, innerNode := range node.Nodes {
// add | only the files.
if !innerNode.Dir {
list = append(list, innerNode.Value)
} else {
list = recursAddNode(innerNode, list)
}
}
return list
} | csn_ccr |
get install packages
@return array
@throws Exception | public function getPackages()
{
$filename = $this->vendorPath . '/composer/installed.json';
if (!file_exists($filename)) {
throw new Exception($filename . ' not exists!');
}
$packages = [];
foreach (json_decode(file_get_contents($filename), true) as $package) {
... | csn |
[comment]: # (Hello Contributors, the following guidelines in order of importance should help you write new translations and squash any pesky unintended bugs.)
[//]: # (The epsilon of all floating point test case comparisons is 0.01.)
[//]: # (Each test case shall pass if the statement "a^2 + b^2 = c^2" is true of the ... | def how_to_find_them(rt):
return {d: rt[d] if d in rt
else (rt["a"]**2 + rt["b"]**2)**.5 if d=="c"
else (rt["c"]**2 - rt[(set("ab")-{d}).pop()]**2)**.5 for d in"abc"} | apps |
def cmd_touch_note(args):
"""Create a note"""
major = args.get(0)
minor = args.get(1)
if major in penStore.data:
if minor is None: # show items in list
for note in penStore.data[major]:
puts(note)
elif minor in penStore.data[major]:
| penStore.openNote(major, minor)
else:
penStore.createNote(major, minor)
penStore.openNote(major, minor)
else:
puts("No list of that name.") | csn_ccr |
@Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
if (!checkConformance(t, args)) {
return Collections.emptyList();
}
// Get the first parameter
@SuppressWarnings("unchecked")
List<VM> s = (List<VM>) params[... | Precedence.newPrecedence(s, s2);
} else if (obj instanceof String) {
String timestamp = (String) obj;
if ("".equals(timestamp)) {
t.ignoreError("Parameter '" + params[1].getName() + "' expects a non-empty string");
return Collections.emptyList();
... | csn_ccr |
Check the data freshness.
@param {*} req
@param {*} res
@returns {Boolean} | function isFresh(req, res) {
if ((res.statusCode >= 200 && res.statusCode < 300) || 304 === res.statusCode) {
return fresh(req.headers, {
"etag": res.getHeader("ETag"),
"last-modified": res.getHeader("Last-Modified")
});
}
return false;
} | csn |
public function add_fonts(array $fonts){
if ( !\defined('BBN_LIB_PATH') ){
die('You must define BBN_LIB_PATH!');
}
if ( !is_dir(BBN_LIB_PATH . 'mpdf/mpdf/ttfonts/') ){
die("You don't have the mpdf/mpdf/ttfonts directory.");
}
foreach ($fonts as $f => $fs) {
// add to available font... | $i === 'R' ){
array_push($this->pdf->available_unifonts, $f);
}
else {
array_push($this->pdf->available_unifonts, $f.$i);
}
}
else {
unset($fs[$i]);
}
}
// add to fontdata array
$this->pdf->fontdata[$f] = $fs;
... | csn_ccr |
Returns a PSR-7 request instance that is not authenticated.
@param string $method
@param string $url
@param array $options
@return RequestInterface | public function getRequest($method, $url, array $options = [])
{
return $this->createRequest($method, $url, null, $options);
} | csn |
public function filterByGbxmapname($gbxmapname = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($gbxmapname)) {
$comparison = Criteria::IN;
}
| }
return $this->addUsingAlias(MxmapTableMap::COL_GBXMAPNAME, $gbxmapname, $comparison);
} | csn_ccr |
Helper method to set the path.
@param competency $parent The parent competency object.
@return void | protected function set_new_path(competency $parent = null) {
$path = '/0/';
if ($this->get('parentid')) {
$parent = $parent !== null ? $parent : $this->get_parent();
$path = $parent->get('path') . $this->get('parentid') . '/';
}
$this->raw_set('path', $path);
... | csn |
Returns true if the method is in the method array.
@param m the method
@param methods the method array
@return true if the method is in the method array. | public static boolean methodBelongsTo(Method m, Method[] methods){
boolean result = false;
for (int i = 0; i < methods.length && !result; i++) {
if(methodEquals (methods [i], m)){
result = true;
}
}
return result;
} | csn |
function HouseholdCommunications (f1, householdID) {
if (!householdID) {
throw new Error('HouseholdCommunications requires a household ID!')
}
| Communications.call(this, f1, {
path: '/Households/' + householdID + '/Communications'
})
} | csn_ccr |
@CheckReturnValue
@Override
public EncodingOptions buildOptions() {
// TODO When/if modelmapper supports @ConstructorProperties, we map this
// object, instead of doing new XXX(...)
// https://github.com/jhalterman/modelmapper/issues/44
return new EncodingOptions(
new MainEncodingOptions(for... | audio_sample_format,
audio_bit_rate,
audio_quality),
new VideoEncodingOptions(
video_enabled,
video_codec,
video_frame_rate,
video_width,
video_height,
video_bit_rate,
video_frames,
video_fi... | csn_ccr |
Executes a script snippet using the 'executor' service.
@param string $cmd
@return void | public function exec($cmd)
{
if (trim($cmd)) {
$this->setOutputPrefix('');
if ($this->resolve('DEBUG')) {
$this->output->writeln('<comment># ' . join('::', Debug::$scope) . "</comment>");
}
if ($this->resolve('EXPLAIN')) {
if ... | csn |
func NewTabletStatsCache(hc HealthCheck, ts *topo.Server, cell string) *TabletStatsCache {
return | newTabletStatsCache(hc, ts, cell, true /* setListener */)
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.