query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
function linkStreams(result, message, erroringStream) {
result.data = stream.transformPair(message.packets.stream, async (readable, writable) => {
await stream.pipe(result.data, writable, {
preventClose: true
});
const writer = stream.getWriter(writable);
try {
// Forward errors in errorin... | to result.data.
await stream.readToEnd(erroringStream || readable, arr => arr);
await writer.close();
} catch(e) {
await writer.abort(e);
}
});
} | csn_ccr |
shared methods for handling manifest lookups
note: required attribs (in host class) include:
- opts.config_path | def installed_template_manifest_patterns
# 1) search . # that is, working/current dir
# 2) search <config_dir>
# 3) search <gem>/templates
###
# Note
# -- for now - no longer ship w/ builtin template packs
# - download on demand if needed
builtin_patterns = [
## "#{Pluto.root}/templates/*.txt... | csn |
public static String getShortClassName(Object o) {
String name = o.getClass().getName();
int index = name.lastIndexOf('.');
if (index >= 0) {
| name = name.substring(index + 1);
}
return name;
} | csn_ccr |
// Validate validates a new templateinstance. | func (s *templateInstanceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
user, ok := apirequest.UserFrom(ctx)
if !ok {
return field.ErrorList{field.InternalError(field.NewPath(""), errors.New("user not found in context"))}
}
templateInstance := obj.(*templateapi.TemplateInstance)
a... | csn |
// reCalcCapacity calculates the capacity for another Chunk based on the current
// Chunk. The new capacity is doubled only when the current Chunk is full. | func reCalcCapacity(c *Chunk, maxChunkSize int) int {
if c.NumRows() < c.capacity {
return c.capacity
}
return mathutil.Min(c.capacity*2, maxChunkSize)
} | csn |
@SuppressWarnings("unchecked")
public static final <C> ClassModel<C> get(ClassAccess<C> classAccess) {
Class<?> clazz = classAccess.getType();
String classModelKey = (classAccess.getClass().getName() + ":" + clazz.getName());
ClassModel<C> classModel = (ClassModel<C>)classModels.get(classModelKey)... | {
return classModel;
} else {
classModel = new ClassModel<C>(classAccess);
classModels.put(classModelKey, classModel);
return classModel;
}
}
} | csn_ccr |
def write_xml(xml)
fname = "#{@appliance_name}.xml"
File.open("#{@dir.tmp}/#{fname}", | 'w'){|f| f.write(xml)}
register_deliverable(:xml => fname)
end | csn_ccr |
Updates an existing MetaTag model.
If update is successful, the browser will be redirected to the 'view' page.
@param integer $id
@return mixed | public function actionUpdate($id)
{
$model = $this->findModel($id);
if (!\Yii::$app->user->can('update', ['model' => $model]))
throw new ForbiddenHttpException(Module::t('metaTag', 'Access denied.'));
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
... | csn |
func New() *Pget {
return &Pget{
Trace: false,
Utils: &Data{},
Procs: | runtime.NumCPU(), // default
timeout: 10,
}
} | csn_ccr |
Creates an "OriginalMapping" object for the given entry object. | private OriginalMapping getOriginalMappingForEntry(Entry entry) {
if (entry.getSourceFileId() == UNMAPPED) {
return null;
} else {
// Adjust the line/column here to be start at 1.
Builder x = OriginalMapping.newBuilder()
.setOriginalFile(sources[entry.getSourceFileId()])
.setLi... | csn |
public static function resource($target, $handler)
{
$route = $target;
$sanitized = str_replace('/', '', $target);
static::get($route, $handler.'@index', $sanitized.'_index');
static::get($target.'/create', $handler.'@showCreateForm', $sanitized.'_create_form');
| static::post($target, $handler.'@save', $sanitized.'_save');
static::get($target.'/[i:id]', $handler.'@show', $sanitized.'_display');
static::get($target.'/[i:id]/edit', $handler.'@showEditForm', $sanitized.'_edit_form');
static::post($target.'/[i:id]', $handler.'@update', $sanitized.'_up... | csn_ccr |
def get_formatter_for_filename(fn, **options):
"""Lookup and instantiate a formatter by filename pattern.
Raises ClassNotFound if not found.
"""
fn = basename(fn)
for modname, name, _, filenames, _ in itervalues(FORMATTERS):
for filename in filenames:
if _fn_matches(fn, filename... | return _formatter_cache[name](**options)
for cls in find_plugin_formatters():
for filename in cls.filenames:
if _fn_matches(fn, filename):
return cls(**options)
raise ClassNotFound("no formatter found for file name %r" % fn) | csn_ccr |
public static int sld2awtCap( String sldCap ) {
if (sldCap.equals("") || sldCap.equals(lineCapNames[1])) {
return BasicStroke.CAP_BUTT;
} else if (sldCap.equals(lineCapNames[2])) {
return BasicStroke.CAP_ROUND;
} else if (sldCap.equals(lineCapNames[3])) {
| return BasicStroke.CAP_SQUARE;
} else {
throw new IllegalArgumentException("unsupported line cap");
}
} | csn_ccr |
// log the message, invoking the handler. We clone the entry here
// to bypass the overhead in Entry methods when the level is not
// met. | func (l *Logger) log(level Level, e *Entry, msg string) {
if level < l.Level {
return
}
if err := l.Handler.HandleLog(e.finalize(level, msg)); err != nil {
stdlog.Printf("error logging: %s", err)
}
} | csn |
def dialect_compare(dialect1, dialect2):
"""
Compares two dialects.
"""
orig = set(dialect1.items())
new = set(dialect2.items())
return dict(
| added=dict(list(new.difference(orig))),
removed=dict(list(orig.difference(new)))
) | csn_ccr |
def _set_symbols(self, file_name, configure):
"""
Load the symbols with configuration.
:param file_name: The file path of symbol configuration.
:type file_name: str
:param configure: The configuration of HaTeMiLe.
:type configure: hatemile.util.configure.Configure
... | )[0].getElementsByTagName('symbol')
for symbol_xml in symbols_xml:
self.symbols.append({
'symbol': symbol_xml.attributes['symbol'].value,
'description': configure.get_parameter(
symbol_xml.attributes['description'].value
)
... | csn_ccr |
def add_sched_block_instance(self, config_dict):
"""Add Scheduling Block to the database.
Args:
config_dict (dict): SBI configuration
"""
# Get schema for validation
schema = self._get_schema()
LOG.debug('Adding SBI with config: %s', config_dict)
# ... |
# Adding Processing block with id
for value in processing_block_data:
name = ("scheduling_block:" + updated_block["id"] +
":processing_block:" + value['id'])
self._db.set_specified_values(name, value)
# Add a event to the processing block event ... | csn_ccr |
Given a string s, return the maximum number of ocurrences of any substring under the following rules:
The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSiz... | class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
n = len(s)
count = collections.Counter(s[i : i + minSize] for i in range(0, n - minSize + 1))
res = 0
for k, v in count.items():
if len(set(k)) <= maxLetters:
... | apps |
Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the image->digest
map isn't needed after we have the image-... | def get_repositories_and_digests(self):
"""
Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the ima... | csn |
public static function parseAPI(BitRank $bitrank, $flag_data)
{
$flags = [];
foreach ($flag_data as $key => $value) {
$slug = isset($value['flag']) ? $value['flag'] : $key;
switch (self::requireValue($value, 'type')) {
case Flag::TYPE_GOOD: $... |
default:
throw new InvalidDataException("Invalid type '$value[type]' returned for flag '$slug'");
}
switch (self::requireValue($value, 'impact')) {
case Flag::IMPACT_HIGH: $impact = Flag::IMPACT_HIGH; break;
case Flag::... | csn_ccr |
Builds a CLI request object from a command line.
The given command line may be a string (e.g. "mypackage:foo do-that-thing --force") or
an array consisting of the individual parts. The array must not include the script
name (like in $argv) but start with command right away.
@param mixed $commandLine The command line,... | public function build($commandLine): Request
{
$request = new Request();
$request->setControllerObjectName(HelpCommandController::class);
if (is_array($commandLine) === true) {
$rawCommandLineArguments = $commandLine;
} else {
preg_match_all(self::ARGUMENT_MA... | csn |
func (s *Server) StreamAggregatedResources(stream ADSStream) error {
// a channel for receiving incoming requests
reqCh := make(chan *envoy.DiscoveryRequest)
reqStop := int32(0)
go func() {
for {
req, err := stream.Recv()
if atomic.LoadInt32(&reqStop) != 0 {
return
}
if err != nil {
close(reqC... | reqCh <- req
}
}()
err := s.process(stream, reqCh)
if err != nil {
s.Logger.Printf("[DEBUG] Error handling ADS stream: %s", err)
}
// prevents writing to a closed channel if send failed on blocked recv
atomic.StoreInt32(&reqStop, 1)
return err
} | csn_ccr |
Write metrics data to tab-separated file.
:param metrics: metrics data.
:param path: Path to write to. | def write_metrics_file(metrics: List[Dict[str, Any]], path: str):
"""
Write metrics data to tab-separated file.
:param metrics: metrics data.
:param path: Path to write to.
"""
with open(path, 'w') as metrics_out:
for checkpoint, metric_dict in enumerate(metrics, 1):
metrics... | csn |
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for nod... | title = _extract(node, "name")
artist = _extract(node, "name", 1)
track = Track(artist, title, self)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(track, weight))
return seq | csn_ccr |
def deprecated(f):
"""Decorate a function object as deprecated.
Work nicely with the @command and @subshell decorators.
Add a __deprecated__ field to the input object and set it to True.
"""
def inner_func(*args, **kwargs):
print(textwrap.dedent("""\
This command is depreca... | f(*args, **kwargs)
inner_func.__deprecated__ = True
inner_func.__doc__ = f.__doc__
inner_func.__name__ = f.__name__
if iscommand(f):
inner_func.__command__ = f.__command__
return inner_func | csn_ccr |
Performs RDF normalization on the given JSON-LD input.
@param dataset
the expanded JSON-LD object to normalize.
@return The normalized JSON-LD object
@throws JsonLdError
If there was an error while normalizing. | public Object normalize(Map<String, Object> dataset) throws JsonLdError {
// create quads and map bnodes to their associated quads
final List<Object> quads = new ArrayList<Object>();
final Map<String, Object> bnodes = newMap();
for (String graphName : dataset.keySet()) {
fina... | csn |
python dot write dot flush | def comment (self, s, **args):
"""Write DOT comment."""
self.write(u"// ")
self.writeln(s=s, **args) | cosqa |
Clean errors for widget.
@param Widget $widget The widget.
@param bool $ignoreErrors The flag for errors cleared.
@return void | protected function cleanErrors(Widget $widget, $ignoreErrors = false)
{
if (!$ignoreErrors) {
return;
}
// Clean the errors array and fix up the CSS class.
$reflectionPropError = new \ReflectionProperty(\get_class($widget), 'arrErrors');
$reflectionPropError->set... | csn |
@Override
public void dumpResponse(Map<String, Object> result) {
byte[] responseBodyAttachment = exchange.getAttachment(StoreResponseStreamSinkConduit.RESPONSE);
if(responseBodyAttachment != null) {
this.bodyContent | = config.isMaskEnabled() ? Mask.maskJson(new ByteArrayInputStream(responseBodyAttachment), "responseBody") : new String(responseBodyAttachment, UTF_8);
}
this.putDumpInfoTo(result);
} | csn_ccr |
public static function changeKeyCase($data, int $case = null)
{
$properties = get_object_vars($data);
foreach ($properties as &$key) {
$value = & $data->$key;
unset($data->$key);
| $changeCaseKey = ($case == CASE_UPPER) ? strtoupper($key) : strtolower($key);
$data->$changeCaseKey = & $value;
}
return $data;
} | csn_ccr |
Deserializes the encrypted serialized model
instances, tx, in a queryset of transactions.
Note: each transaction instance contains encrypted JSON text
that represents just ONE model instance. | def deserialize_transactions(self, transactions=None, deserialize_only=None):
"""Deserializes the encrypted serialized model
instances, tx, in a queryset of transactions.
Note: each transaction instance contains encrypted JSON text
that represents just ONE model instance.
"""
... | csn |
Claims modules that are under ipynb.fs | def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
... | csn |
func (a Access) EqualOrGreaterOfferAccessThan(access Access) bool {
v1, | v2 := a.offerValue(), access.offerValue()
if v1 < 0 || v2 < 0 {
return false
}
return v1 >= v2
} | csn_ccr |
Returns an associative array of the request headers
@return multitype:unknown | public function getRequestHeaders($auth = true)
{
$headers = \getallheaders();
if($auth) {
$hmac = $this->getRest()->getServer()->getHmac();
$return = array(
$hmac->getPrefix().'timestamp' => (isset($headers[$hmac->getPrefix().'timestamp']) ? $headers[$hmac->g... | csn |
Decorates given validation rules
@param array $rules
@param Model|null $model if updating, the model being updated
@return array | public function decorate(array $rules, Model $model = null)
{
$this->rules = $rules;
$this->model = $model;
$this
->replaceTranslationPlaceholders()
->replaceKeyPlaceholders();
return $this->rules;
} | csn |
Generate the miRTrace Read Length Distribution | def mirtrace_length_plot(self):
""" Generate the miRTrace Read Length Distribution"""
data = dict()
for s_name in self.length_data:
try:
data[s_name] = {int(d): int(self.length_data[s_name][d]) for d in self.length_data[s_name]}
except KeyError:
... | csn |
func (l *HostIPListener) Listen(cancel <-chan interface{}, | conn client.Connection) {
zzk.Listen2(cancel, conn, l)
} | csn_ccr |
def add(self, target, *args, **kwargs):
"""
target IS THE FUNCTION TO EXECUTE IN THE THREAD
"""
| t = Thread.run(target.__name__, target, *args, **kwargs)
self.threads.append(t) | csn_ccr |
Reduces the output of an LSTM step
Args:
outputs: (torch.FloatTensor) the hidden state outputs from the
lstm, with shape [batch_size, max_seq_length, hidden_size] | def _reduce_output(self, outputs, seq_lengths):
"""Reduces the output of an LSTM step
Args:
outputs: (torch.FloatTensor) the hidden state outputs from the
lstm, with shape [batch_size, max_seq_length, hidden_size]
"""
batch_size = outputs.shape[0]
red... | csn |
func (*DatabaseSettings) Actions(c context.Context) | ([]portal.Action, error) {
return nil, nil
} | csn_ccr |
function (surl) {
var search = (surl || window.location.search).match(/\?.*(?=\b|#)/);
search && (search = search[0].replace(/^\?/, ''));
if (!search) return {};
var queries = {},
params = | search.split('&');
util.each(params, function (item) {
var param = item.split('=');
queries[param[0]] = param[1];
});
return queries;
} | csn_ccr |
Checks the contents of executables, types and modules for member
definitions and updates the context. | def _deep_match(self, line, column):
"""Checks the contents of executables, types and modules for member
definitions and updates the context."""
#Now we just try each of the possibilities for the current line
if self._match_member(line, column):
self.el_section = "vars"
... | csn |
tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection. | def _dimensions(self):
"""tuple of dimension objects in this collection.
This composed tuple is the source for the dimension objects in this
collection.
"""
return tuple(d for d in self._all_dimensions if d.dimension_type != DT.MR_CAT) | csn |
//DeleteServiceLB deletes from etcd state | func DeleteServiceLB(stateDriver core.StateDriver, serviceName string, tenantName string) error {
log.Infof("Received Delete Service Load Balancer %s on %s", serviceName, tenantName)
serviceLBState := &mastercfg.CfgServiceLBState{}
serviceLBState.StateDriver = stateDriver
serviceLBState.ID = GetServiceID(serviceNa... | csn |
def vel_disp_one(self, gamma, rho0_r0_gamma, r_eff, r_ani, R_slit, dR_slit, FWHM):
"""
computes one realisation of the velocity dispersion realized in the slit
:param gamma: power-law slope of the mass profile (isothermal = 2)
:param rho0_r0_gamma: combination of Einstein radius and pow... | velocity dispersion of a single drawn position in the potential [km/s]
"""
a = 0.551 * r_eff
while True:
r = self.P_r(a) # draw r
R, x, y = self.R_r(r) # draw projected R
x_, y_ = self.displace_PSF(x, y, FWHM) # displace via PSF
bool = self.che... | csn_ccr |
Train the model on the incoming dstream. | def trainOn(self, dstream):
"""Train the model on the incoming dstream."""
self._validate(dstream)
def update(rdd):
self._model.update(rdd, self._decayFactor, self._timeUnit)
dstream.foreachRDD(update) | csn |
def find_object(self, pattern, hosts, services):
"""Find object from pattern
:param pattern: text to search (host1,service1)
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, u... |
elts = pattern.split(',')
host_name = elts[0].strip()
# If host_name is empty, use the host_name the business rule is bound to
if not host_name:
host_name = self.bound_item.host_name
# Look if we have a service
if len(elts) > 1:
is_service = True
... | csn_ccr |
Recover the jobs sent to a crashed agent | async def _recover_jobs(self, agent_addr):
""" Recover the jobs sent to a crashed agent """
for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())):
if agent == agent_addr:
await ZMQUtils.send_with_addr(self._client_socket, client_addr,
... | csn |
// Deallocate removes and cleans up a resource. | func (r *AutoVXLANCfgResource) Deallocate(value interface{}) error {
oper := &AutoVXLANOperResource{}
oper.StateDriver = r.StateDriver
err := oper.Read(r.ID)
if err != nil {
return err
}
pair, ok := value.(VXLANVLANPair)
if !ok {
return core.Errorf("Invalid type for vxlan-vlan pair")
}
vxlan := pair.VXLAN... | csn |
// deleteDisk deletes the persistent disk. | func (svc *googleService) deleteDisk(name string) error {
op, err := svc.service.Disks.Delete(svc.vm.Project, svc.vm.Zone, name).Do()
if err != nil {
return err
}
return svc.waitForOperationReady(op.Name)
} | csn |
// Convert_v1beta2_MetricIdentifier_To_custom_metrics_MetricIdentifier is an autogenerated conversion function. | func Convert_v1beta2_MetricIdentifier_To_custom_metrics_MetricIdentifier(in *MetricIdentifier, out *custommetrics.MetricIdentifier, s conversion.Scope) error {
return autoConvert_v1beta2_MetricIdentifier_To_custom_metrics_MetricIdentifier(in, out, s)
} | csn |
public function onKernelResponse(FilterResponseEvent $event)
{
if ($this->handleResponse && $this->http_code !== null) {
$response = $event->getResponse(); |
$response->setStatusCode($this->http_code, $this->http_status);
}
} | csn_ccr |
Converts a PHP date format to "Moment.js" format.
@param string $format
@return string | public static function momentFormat($format)
{
$replacements = [
'd' => 'DD',
'D' => 'ddd',
'j' => 'D',
'l' => 'dddd',
'N' => 'E',
'S' => 'o',
'w' => 'e',
'z' => 'DDD',
'W' => 'W',
'F' => ... | csn |
Whether the rows of the given association should be stored in a hash using the single row key column as key or
not. | public static boolean organizeAssociationMapByRowKey(
org.hibernate.ogm.model.spi.Association association,
AssociationKey key,
AssociationContext associationContext) {
if ( association.isEmpty() ) {
return false;
}
if ( key.getMetadata().getRowKeyIndexColumnNames().length != 1 ) {
return false;
... | csn |
Calculate the final digit of id card
@param string $input The 17 or 18-digit code
@return string | public function calcChecksum($input)
{
$wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
$sum = 0;
for ($i = 16; $i >= 0; $i--) {
$sum += $input[$i] * $wi[$i];
}
$checksum = (12 - $sum % 11) % 11;
return $checksum == 10 ? 'X' : (string)$... | csn |
def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region):
"""\
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matr... | row index / col index belongs to the data region.
"""
for i in range(matrix_size):
for j in range(matrix_size):
if is_encoding_region(i, j):
matrix[i][j] ^= mask_pattern(i, j) | csn_ccr |
Resolve the type name of the inner value.
@throws UnknownTypeException
@return string | public function resolve()
{
// TODO: Make this dynamic.
if (is_scalar($this->value)) {
if (is_string($this->value)) {
return ScalarTypes::SCALAR_STRING;
} elseif (is_bool($this->value)) {
return ScalarTypes::SCALAR_BOOLEAN;
} elsei... | csn |
def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
| total_len)
self.statusline = '206 Partial Content'
self.replace_header('Content-Range', content_range)
self.replace_header('Content-Length', str(part_len))
self.replace_header('Accept-Ranges', 'bytes')
return self | csn_ccr |
func (f *IndexFile) UnmarshalBinary(data []byte) error {
// Ensure magic number exists at the beginning.
if len(data) < len(FileSignature) {
return io.ErrShortBuffer
} else if !bytes.Equal(data[:len(FileSignature)], []byte(FileSignature)) {
return ErrInvalidIndexFile
}
// Read index file trailer.
t, err := R... |
itr := f.mblk.Iterator()
for m := itr.Next(); m != nil; m = itr.Next() {
e := m.(*MeasurementBlockElem)
// Slice measurement block data.
buf := data[e.tagBlock.offset:]
buf = buf[:e.tagBlock.size]
// Unmarshal measurement block.
var tblk TagBlock
if err := tblk.UnmarshalBinary(buf); err != nil {
... | csn_ccr |
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).
So given a string "super", we should return a list of [2, 4].
Some examples:
Mmmm => []
Super => [2,4]
Apple => [1,5]
YoMama -> [1,2,4... | def vowel_indices(word):
return [i for i,x in enumerate(word,1) if x.lower() in 'aeiouy'] | apps |
Closes the old session and creates and opens an untitled database.
@throws Exception if an error occurred while creating or opening the database. | private void closeSessionAndCreateAndOpenUntitledDb() throws Exception {
getExtensionLoader().sessionAboutToChangeAllPlugin(null);
model.closeSession();
log.info("Create and Open Untitled Db");
model.createAndOpenUntitledDb();
} | csn |
def act(self, cmd_name, params=None):
""" Run the specified command with its parameters."""
command = getattr(self, cmd_name)
| if params:
command(params)
else:
command() | csn_ccr |
Finds commands by finding the subclasses of Command | def find_commands(cls):
""" Finds commands by finding the subclasses of Command"""
cmds = []
for subclass in cls.__subclasses__():
cmds.append(subclass)
cmds.extend(find_commands(subclass))
return cmds | csn |
Get an device pointer through which to access a mapped graphics resource.
<pre>
cudaError_t cudaGraphicsResourceGetMappedPointer (
void** devPtr,
size_t* size,
cudaGraphicsResource_t resource )
</pre>
<div>
<p>Get an device pointer through which to
access a mapped graphics resource. Returns in <tt>*devPtr</tt> a
poin... | public static int cudaGraphicsResourceGetMappedPointer(Pointer devPtr, long size[], cudaGraphicsResource resource)
{
return checkResult(cudaGraphicsResourceGetMappedPointerNative(devPtr, size, resource));
} | csn |
def inclusive_temporal_ref?
# FIXME: NINF is used instead of 0 sometimes...? (not in the IG)
# FIXME: Given nullFlavor, but IG uses it and nullValue everywhere...
less_than_equal_tr = attr_val('../@highClosed') == 'true' &&
(attr_val('../cda:low/@value') == '0' || attr_val('... | attr_val('../cda:low/@value')
# Both less and greater require lowClosed to be set to true
(less_than_equal_tr || greater_than_equal_tr) && attr_val('../@lowClosed') == 'true'
end | csn_ccr |
def execute(self, command, future):
"""Execute a command after connecting if necessary.
:param bytes command: command to execute after the connection
is established
:param tornado.concurrent.Future future: future to resolve
when the command's response is received.
... |
if cfuture.exception():
return future.set_exception(cfuture.exception())
self._write(command, future)
self.io_loop.add_future(self.connect(), on_connected) | csn_ccr |
// GetMysqlPort returns mysql port | func (mysqld *Mysqld) GetMysqlPort() (int32, error) {
qr, err := mysqld.FetchSuperQuery(context.TODO(), "SHOW VARIABLES LIKE 'port'")
if err != nil {
return 0, err
}
if len(qr.Rows) != 1 {
return 0, errors.New("no port variable in mysql")
}
utemp, err := sqltypes.ToUint64(qr.Rows[0][1])
if err != nil {
ret... | csn |
def remove_blanks(letters: List[str]):
"""
Given a list of letters, remove any empty strings.
:param letters:
:return:
| >>> remove_blanks(['a', '', 'b', '', 'c'])
['a', 'b', 'c']
"""
cleaned = []
for letter in letters:
if letter != "":
cleaned.append(letter)
return cleaned | csn_ccr |
Get one Tag item by tag name | public function scopeByTagName($query, $tag_name)
{
// mormalize string
$tag_name = app(TaggingUtility::class)->normalizeTagName(trim($tag_name));
return $query->where('name', $tag_name);
} | csn |
Marks post as unseen.
@return bool | public function unseen()
{
$this->post_seen = self::POST_NEW;
if (!$this->save()) {
return false;
}
Podium::getInstance()->podiumCache->deleteElement('user.subscriptions', User::loggedId());
return true;
} | csn |
Find classcontents by provided classnames, criterias from request, provided start and count.
@param array $classnames
@param integer $start
@param integer $count
@return null|Paginator | private function findContentsByCriteria(array $classnames, $start, $count)
{
$criterias = array_merge([
'only_online' => false,
'site_uid' => $this->getApplication()->getSite()->getUid(),
], $this->getRequest()->query->all());
$criterias['only_online'] = (boolean)... | csn |
how to get a random float between 0 and 1 in python | def money(min=0, max=10):
"""Return a str of decimal with two digits after a decimal mark."""
value = random.choice(range(min * 100, max * 100))
return "%1.2f" % (float(value) / 100) | cosqa |
Method to delete a Rest Api named defined in the swagger file's Info Object's title value.
ret
a dictionary for returning status to Saltstack | def delete_api(self, ret):
'''
Method to delete a Rest Api named defined in the swagger file's Info Object's title value.
ret
a dictionary for returning status to Saltstack
'''
exists_response = __salt__['boto_apigateway.api_exists'](name=self.rest_api_name,
... | csn |
func NewConsumedToken(tkn *lexer.Token) ConsumedElement {
return ConsumedElement{ |
isSymbol: false,
token: tkn,
}
} | csn_ccr |
public static int jsHash(Object jsObj) {
if (jsObj == null) {
return 1;
}
// Concatenated strings in Rhino have a different type. We need to manually
// resolve to String semantics, which is what the following lines do.
if (jsObj instanceof ConsString) {
... |
}
return (jsObj instanceof ScriptableObject)
? jsScriptableObjectHashCode((ScriptableObject) jsObj)
: jsObj.hashCode();
} | csn_ccr |
public function get($filename)
{
$filename = $this->path($filename);
if (!(is_file($filename) && | stream_is_local($filename))) {
return null;
}
return file_get_contents($filename);
} | csn_ccr |
Get k-fold indices generator | def split_KFold_idx(train, cv_n_folds=5, stratified=False, random_state=None):
"""Get k-fold indices generator
"""
test_len(train)
y = train[1]
n_rows = y.shape[0]
if stratified:
if len(y.shape) > 1:
if y.shape[1] > 1:
raise ValueError("Can't use stratified K-... | csn |
protected function outputIgnoreTag(Tag $tag)
{
$tagPos = $tag->getPos();
$tagLen = $tag->getLen();
// Capture the text to ignore
$ignoreText = substr($this->text, $tagPos, $tagLen);
// Catch up with the tag's position then output the tag
$this->outputText($tagPos, 0, | false);
$this->output .= '<i>' . htmlspecialchars($ignoreText, ENT_NOQUOTES, 'UTF-8') . '</i>';
$this->isRich = true;
// Move the cursor past this tag
$this->pos = $tagPos + $tagLen;
} | csn_ccr |
from mxnet import autograd, gluon, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
net = nn.Sequential()
net.add(nn.Conv2D(channels=6, kernel_size=5, padding=2, activation='sigmoid'),
nn.AvgPool2D(pool_size=2, strides=2),
nn.Conv2D(channels=16, kernel_size=5, activatio... | import torch
from torch import nn
from d2l import torch as d2l
net = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5... | codetrans_dl |
def _get_vm_device_status(self, device='FLOPPY'):
"""Returns the given virtual media device status and device URI
:param device: virtual media device to be queried
:returns json format virtual media device status and its URI
:raises: IloError, on an error from iLO.
:raises: Il... | manager, uri = self._get_ilo_details()
try:
vmedia_uri = manager['links']['VirtualMedia']['href']
except KeyError:
msg = ('"VirtualMedia" section in Manager/links does not exist')
raise exception.IloCommandNotSupportedError(msg)
for status, hds, vmed, ... | csn_ccr |
Check if target string ends with any of a list of specified strings.
@param target
@param endWith
@return | public static boolean endAny(String target, List<String> endWith) {
if (isNull(target)) {
return false;
}
return matcher(target).ends(endWith);
} | csn |
Helper to normalize linefeeds in strings. | def s(obj):
"""Helper to normalize linefeeds in strings."""
if isinstance(obj, bytes):
return obj.replace(b'\n', os.linesep.encode())
else:
return obj.replace('\n', os.linesep) | csn |
def get(self):
"""
Constructs a TaskQueueRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueue... | return TaskQueueRealTimeStatisticsContext(
self._version,
workspace_sid=self._solution['workspace_sid'],
task_queue_sid=self._solution['task_queue_sid'],
) | csn_ccr |
def link(target, link_to):
"""
Create a link to a target file or a folder.
For simplicity sake, both target and link_to must be absolute path and must
include the filename of the file or folder.
Also do not include any trailing slash.
e.g. link('/path/to/file', '/path/to/link')
But not: l... | the link if it does not exists
abs_path = os.path.dirname(os.path.abspath(link_to))
if not os.path.isdir(abs_path):
os.makedirs(abs_path)
# Make sure the file or folder recursively has the good mode
chmod(target)
# Create the link to target
os.symlink(target, link_to) | csn_ccr |
public function addEntry($dn, $data)
{
$data = $this->normalizeData($data);
if (! (@ldap_add($this->connection, $dn, $data))) {
$code = @ldap_errno($this->connection);
throw new PersistenceException(
sprintf(
| 'Could not add entry %s: Ldap Error Code=%s - %s',
$dn,
$code,
ldap_err2str($code)
)
);
}
} | csn_ccr |
func (t *deviceDownloadState) GetBlockCounts(folder string) map[string]int {
if t == nil {
return nil
| }
t.mut.RLock()
defer t.mut.RUnlock()
for name, state := range t.folders {
if name == folder {
return state.GetBlockCounts()
}
}
return nil
} | csn_ccr |
Return a key to identify the connection descriptor. | public PBKey getPBKey()
{
if (pbKey == null)
{
this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());
}
return pbKey;
} | csn |
Returns a list of all services on the system. | def _get_services():
'''
Returns a list of all services on the system.
'''
handle_scm = win32service.OpenSCManager(
None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)
try:
services = win32service.EnumServicesStatusEx(handle_scm)
except AttributeError:
services = win3... | csn |
// Blacklisting handles the request and returns the user blacklisting | func Blacklisting() echo.HandlerFunc {
// swagger:route GET /users/{id}/blacklisting users blacklisting GetBlacklisting
//
// Show the user that placed the specified user in their blacklist
//
// You can personalize the request via query string parameters
//
// Produces:
// - application/json
//
// Security:... | csn |
Sets the values of each pixel equal to the pixels in the specified matrix.
Automatically resized to match the input image.
@param orig The original image whose value is to be copied into this one | @Override
public void setTo( Planar<T> orig) {
if (orig.width != width || orig.height != height)
reshape(orig.width,orig.height);
if( orig.getBandType() != getBandType() )
throw new IllegalArgumentException("The band type must be the same");
int N = orig.getNumBands();
if( N != getNumBands() ) {
setN... | csn |
def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column... | _logging.warning("Feature '{}' excluded. ".format(ftr) +
"Features must be specified as strings " +
"corresponding to column names in the input dataset.")
elif ftr not in column_type_map.keys():
_logging.warning("Feature '{}' excluded because... | csn_ccr |
Parse a raw columns.
@param array $rawColumns The raw columns.
@param DataTablesWrapperInterface $wrapper The wrapper.
@return DataTablesColumnInterface[] Returns the columns. | protected static function parseColumns(array $rawColumns, DataTablesWrapperInterface $wrapper) {
$dtColumns = [];
foreach ($rawColumns as $current) {
$dtColumn = static::parseColumn($current, $wrapper);
if (null === $dtColumn) {
continue;
}
... | csn |
Declares internal data structures based on the input image pyramid | protected void declareDataStructures(PyramidDiscrete<I> image) {
numPyramidLayers = image.getNumLayers();
previousDerivX = (D[])Array.newInstance(derivType,image.getNumLayers());
previousDerivY = (D[])Array.newInstance(derivType,image.getNumLayers());
currentDerivX = (D[])Array.newInstance(derivType,image.getN... | csn |
Get one MySQL connect from pool
@return bool | private function prepareDB()
{
$dbpool = DBPool::init($this->db_config);
// var_dump($dbpool->cap + $dbpool->activeCount, $dbpool->queue->isEmpty(), $dbpool->queue->count());
if ($dbpool->queue->isEmpty() && ($dbpool->cap + $dbpool->activeCount >= $this->config['max_pool_size'])) {
... | csn |
Creates the specified fixture instances.
All dependent fixtures will also be created.
@param array $fixtures the fixtures to be created. You may provide fixture names or fixture configurations.
If this parameter is not provided, the fixtures specified in [[globalFixtures()]] and [[fixtures()]] will be created.
@throw... | protected function createFixtures(array $fixtures)
{
// normalize fixture configurations
$config = []; // configuration provided in test case
$aliases = []; // class name => alias or class name
foreach ($fixtures as $name => $fixture) {
if (!is_array($fixture)) {
... | csn |
looking for similarity between 2 lists in python | def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:
"""Calculate the tanimoto set similarity."""
a, b = set(x), set(y)
union = a | b
if not union:
return 0.0
return len(a & b) / len(union) | cosqa |
Get the value for the node
@param string $path the path to the node
@return string|null | public function get($path) {
if (!$this->zookeeper->exists($path)) {
return null;
}
return $this->zookeeper->get($path);
} | csn |
python join two df and dont duplicate columns | def cross_join(df1, df2):
"""
Return a dataframe that is a cross between dataframes
df1 and df2
ref: https://github.com/pydata/pandas/issues/5401
"""
if len(df1) == 0:
return df2
if len(df2) == 0:
return df1
# Add as lists so that the new index keeps the items in
#... | cosqa |
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copied from scipy 0... | csn |
Filter profile images
@return Images | public function filterProfile()
{
return $this->filter(
function ($key, $value) {
if ($value instanceof ImageFilter && $value instanceof Image\ProfileImage) {
return true;
}
}
);
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.