query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
// Create the canonicalized header string part of a request's signature body. | func (vg *Vangoh) createHeadersString(r *http.Request) string {
if len(vg.includedHeaders) == 0 {
return ""
}
// For each defined regex, determine the set of headers that match. Repeat
// for all regexes, without duplication, to get the final set of custom
// headers to use.
var sanitizedHeaders = make(map[str... | csn |
function (node, aChild) {
$.each(aChild, function (idx, child) {
| node.appendChild(child);
});
return node;
} | csn_ccr |
public function getTemplateVars(array $extra = [])
{
$extraKeys = array_keys($extra);
if (0 < count($extraKeys)) {
foreach (array_keys($this->resources) as $key) {
if (array_key_exists($key, $extraKeys)) {
throw new \RuntimeException(sprintf('Key "%s" ... | }
}
}
return array_merge($this->resources, [
'identifiers' => $this->getIdentifiers(),
'resource_name' => $this->config->getResourceName(),
'resource_id' => $this->config->getId(),
'route_prefix' => $this->config->getRoutePrefix(),
... | csn_ccr |
private void drawEnabledGraphic(Graphics2D g, int width, int height) {
Shape s = shapeGenerator.createTabCloseIcon(2, 2, | width - 4, height - 4);
g.setPaint(createGraphicInnerShadowGradient(s));
g.fill(s);
} | csn_ccr |
Set axis formatter based on dimension formatter. | def _set_axis_formatter(self, axis, dim, formatter):
"""
Set axis formatter based on dimension formatter.
"""
if isinstance(dim, list): dim = dim[0]
if formatter is not None:
pass
elif dim.value_format:
formatter = dim.value_format
elif dim... | csn |
adds text to
a nested verb | public function addNestedText($index, $text) {
if (!($index <= sizeof($this->verbs))) {
throw new \CatapultApiException("This verb does not have $index nested verbs");
}
$this->verbs[$index]->addText($text);
} | csn |
function safe3(fn) {
var queue = Queue.new();
var safe = true;
function checkQueue() {
var next = queue.shift();
safe = false;
fn(next[0], next[1], next[2], function (error, result) {
next[3](error, result);
if (queue.length > 0) {
checkQueue();
| } else {
safe = true;
}
});
}
return function (arg1, arg2, arg3, callback) {
queue.push(arguments);
if (safe) {
checkQueue();
}
};
} | csn_ccr |
public static function GetFileNames($dir, $filters = array()) {
$filenames = array_diff(scandir($dir), array('..', '.'));
if (count($filters > 0)) {
| $filenames = self::FilterArray($filenames, $filters);
}
return $filenames;
} | csn_ccr |
def show
closed!
if @debug
ary = @leds.map { |value| Rainbow(@debug).color(*to_rgb(value)) }
| $stdout.print "\r#{ary.join}"
end
self
end | csn_ccr |
private function voteForPage(TokenInterface $token, Page $page, array $attributes)
{
if (self::ACCESS_DENIED === $result = $this->voteForObject($token, $page, $attributes)) {
if (null !== $page->getParent()) {
| $result = $this->voteForPage($token, $page->getParent(), $attributes);
}
}
return $result;
} | csn_ccr |
Returns the virtual column value
@param string $name
@return mixed | protected function &getVirtualValue($name)
{
$result = $this->callGetter($name, $this->virtualData[$name]);
if ($result) {
return $this->virtualData[$name];
}
throw new InvalidArgumentException('Invalid virtual column: ' . $name);
} | csn |
func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options types.CopyToContainerOptions) error {
query := url.Values{}
query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API.
// Do not allow for an existing directory to be overwritten ... |
if err != nil {
return wrapResponseError(err, response, "container:path", containerID+":"+dstPath)
}
// TODO this code converts non-error status-codes (e.g., "204 No Content") into an error; verify if this is the desired behavior
if response.statusCode != http.StatusOK {
return fmt.Errorf("unexpected status c... | csn_ccr |
function doSequentiallyInBackground(items, fnProcessItem, maxBlockingTime, idleTime) {
maxBlockingTime = maxBlockingTime || 15;
idleTime = idleTime || 30;
var sliceStartTime = (new Date()).getTime();
return doSequentially(items, function (item, i) {
var result = new $.Defe... | window.setTimeout(function () {
sliceStartTime = (new Date()).getTime();
result.resolve();
}, idleTime);
} else {
//continue processing
result.resolve();
}
return result;
}... | csn_ccr |
Puts multiple tasks on the queue using batch puts. The tasks argument
can contain more than 10 Tasks, in that case there will be multiple SQS
batch send requests made each containing up to 10 messages.
@param tasks | @Override
public void put(Set<Task> tasks) {
String msgBody = null;
SendMessageBatchRequestEntry msgEntry = null;
Set<SendMessageBatchRequestEntry> msgEntries = new HashSet<>();
for (Task task : tasks) {
msgBody = unmarshallTask(task);
msgEntry = new SendMessa... | csn |
Finds all matches above ``similarity`` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester | def findAllMatches(self, needle, similarity):
""" Finds all matches above ``similarity`` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester
"""
positions = []
# Use findBestMatch to get the best ma... | csn |
// WriteOrdererConfig serializes the provided configuration as the specified
// orderer's orderer.yaml document. | func (n *Network) WriteOrdererConfig(o *Orderer, config *fabricconfig.Orderer) {
ordererBytes, err := yaml.Marshal(config)
Expect(err).NotTo(HaveOccurred())
err = ioutil.WriteFile(n.OrdererConfigPath(o), ordererBytes, 0644)
Expect(err).NotTo(HaveOccurred())
} | csn |
Delete the values of the attributes associated to the currently loaded collection version.
@param int[] $retainAKIDs a list of attribute key IDs to keep (their values won't be deleted) | public function clearCollectionAttributes($retainAKIDs = [])
{
$db = Loader::db();
if (count($retainAKIDs) > 0) {
$cleanAKIDs = [];
foreach ($retainAKIDs as $akID) {
$cleanAKIDs[] = (int) $akID;
}
$akIDStr = implode(',', $cleanAKIDs);
... | csn |
import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
from paddle import nn
from paddle.nn import functional as F
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
num_hiddens = 256
rnn_layer = nn.SimpleRNN(len(vocab), num_hidden... | import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
num_hiddens = 256
rnn_layer = nn.RNN(len(vocab), num_hiddens)
state = torch.zeros((1, batch_size, num_hiddens))
state.s... | codetrans_dl |
public function fetchAll($mode = null, $complement_info = null, array $ctor_args = array()) {
$fetchmode = is_null($mode) ? $this->fetchMode : new FetchMode($mode, $complement_info, $ctor_args);
/* @var $fetchmode FetchMode */
$rows = array();
foreach($this->prefetched as $row) {
... |
} elseif($fetchmode->hasMode(DB::FETCHALL_UNIQUE)) {
$rows[array_shift($row)] = $this->parseFetched($rows, $fetchmode);
} else {
$rows[] = $this->parseFetched($rows, $fetchmode);
}
}
return $rows;
} | csn_ccr |
// GoogleToken is like Token but assumes the Google AuthURL and TokenURL,
// so that only the client ID and secret and desired scope must be specified. | func GoogleToken(file, clientID, clientSecret, scope string) (*oauth.Transport, error) {
cfg := &oauth.Config{
ClientId: clientID,
ClientSecret: clientSecret,
Scope: scope,
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
re... | csn |
public function registerSubscriptions(EventDispatcher $dispatcher)
{
if ($this->registered) {
throw new \RuntimeException('Cannot register debug toolbar subscriptions when already registered.');
}
foreach ($this->toolbar->getExtensions() as $extension) {
| if ( ! $extension instanceof EventSubscriberInterface) {
continue;
}
$dispatcher->addSubscriber($extension);
}
$this->registered = true;
} | csn_ccr |
def descriptor(obj, path=''):
"""Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned.
"""
if isinstance(obj, dict):
# Current object is hydrated, so we need to get descriptor from
# dict representation.
desc = obj['__descrip... | else:
desc = obj.descriptor
resp = dict_dot(desc, path)
if isinstance(resp, list) or isinstance(resp, dict):
return json.dumps(resp)
return resp | csn_ccr |
Computes the result of evaluating the comparator with a given left-hand side.
@param lhs the left-hand side
@return {@code true} if the comparator evaluates to true, {@code false} otherwise | private boolean evaluateComparator(final int lhs) {
switch (this.comparator) {
case EQ:
return lhs == this.rhs;
case LE:
return lhs <= this.rhs;
case LT:
return lhs < this.rhs;
case GE:
return lhs >= this.rhs;
case GT:
return lhs > this.rhs;
... | csn |
Get a required property by base property and property name
@param base
base property
@param property
property
@return property value | public static String getProperty(String base, String property) {
return getProperty(base, property, true);
} | csn |
Initialize the service with a context
@param context the servlet context to initialize the profile. | public void init(ServletContext context) {
if (profiles != null) {
for (IDiagramProfile profile : profiles) {
profile.init(context);
_registry.put(profile.getName(),
profile);
}
}
} | csn |
python histogram get data with in bin | def get_bin_indices(self, values):
"""Returns index tuple in histogram of bin which contains value"""
return tuple([self.get_axis_bin_index(values[ax_i], ax_i)
for ax_i in range(self.dimensions)]) | cosqa |
Create a formatted "dump" of a sequence of bytes
@param frame the byte array containing the bytes to be formatted
@param offset the offset of the first byte to format
@param length the number of bytes to format
@return a String containing the formatted dump. | public static String dumpString(byte[] frame, int offset, int length) {
return dumpString(frame, offset, length, false);
} | csn |
private static function response(ContainerInterface $container): ResponseInterface
{
if (!$container->has(ResponseInterface::class)) {
throw new InvalidArgumentException('Moon received an | invalid response instance from the container');
}
return $container->get(ResponseInterface::class);
} | csn_ccr |
func (p *Plan) GetSpace() int {
if p == | nil || p.Space == nil {
return 0
}
return *p.Space
} | csn_ccr |
public function microServicesListAction()
{
$view = new ViewModel();
$translator = $this->getServiceLocator()->get('translator');
$apiKey = trim($this->params()->fromRoute('api_key', ''));
$userExists = false;
$microservice = array();
$userApiData ... | $container['melis-lang-locale'] = $langData->lang_locale;
}
//Exclude array 'conf' key
if(array_key_exists('conf',$microservice)){
unset($microservice['conf']);
}
$userExists = true;
}else{
... | csn_ccr |
Register Core Services used by this Service.
@return void | protected function registerCore()
{
// Bind the Entity Identifier aggregate.
$this->app->singleton(IdentifierServiceProvider::getProviderKey(), function($app)
{
return new IdentifierService(IdentifierServiceProvider::getProviderKey(), new IdentifierDataSource(new IdentifierModel([], $this->getConnect... | csn |
list into dictionary in python | def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic | cosqa |
Find out the maximum sub-array of non negative numbers from an array.
The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid.
Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is... | for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
s=0
l=[]
for i in range(n):
if (a[i]<0):
e=i
ss=sum(a[s:e])
l.append((ss,e-s,n-s))
s=i+1
e=n
ss=sum(a[s:e])
l.append((ss,e-s,n-s))
x=max(l)
s=n-x[2]
e=x[1]+s
for i in range(s,e):
print(a[i], end=' ')
print("") | apps |
Return information about table columns
@return array | public static function getMeta(): array
{
$self = static::getInstance();
if (empty($self->meta)) {
$cacheKey = "db.table.{$self->name}";
$meta = Cache::get($cacheKey);
if (!$meta) {
$schema = DbProxy::getOption('connect', 'name');
... | csn |
Supply a sentence or fragment and recieve a confidence interval | def is_participle_clause_fragment(sentence):
"""Supply a sentence or fragment and recieve a confidence interval"""
# short circuit if sentence or fragment doesn't start with a participle
# past participles can sometimes look like adjectives -- ie, Tired
if not _begins_with_one_of(sentence, ['VBG', 'VBN'... | csn |
Returns the raw instance or, creates a new one if it doesn't exists yet and returns it.
@param string $userName
@param Auth $auth
@return Raw instance | private static function getInstance(
string $userName,
Auth $auth
) : RawEndpoint {
return new RawEndpoint(
$userName,
$auth,
new Client()
);
} | csn |
@POST
@Path("/bulk/classification")
@Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
@Produces(Servlets.JSON_MEDIA_TYPE)
public void addClassification(ClassificationAssociateRequest request) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (... | null || StringUtils.isEmpty(classification.getTypeName())) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "no classification");
}
if (CollectionUtils.isEmpty(entityGuids)) {
throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "empt... | csn_ccr |
public function draw($name)
{
$this->bstall->load($name);
$pixels = Input::get('pixels');
foreach($pixels as $p) {
if(isset($p['x'])
&& isset($p['y'])
&& isset($p['c'])) {
| $this->bstall->write($p['x'], $p['y'], $p['c']);
}
}
$this->bstall->save($name);
return Response::json(["success" => true]);
} | csn_ccr |
public function setMessagingId(int $nb_messaging_id) : CNabuDataObject
{
if ($nb_messaging_id === null) {
throw new ENabuCoreException(
ENabuCoreException::ERROR_NULL_VALUE_NOT_ALLOWED_IN,
| array("\$nb_messaging_id")
);
}
$this->setValue('nb_messaging_id', $nb_messaging_id);
return $this;
} | csn_ccr |
// Validate returns an error if the mode is unrecognized. | func (p ParanoidMode) Validate() error {
switch p {
case NotParanoid, CheckPresence, CheckIntegrity:
return nil
default:
return fmt.Errorf("unrecognized paranoid mode %q", p)
}
} | csn |
def add_data(self, data):
"""Add data to the node value sets
Parameters
----------
data: numpy.ndarray
one or more node value sets. It must either be 1D or 2D, with the
first dimension the number of parameter sets (K), and the second
the number of ele... | else:
raise Exception(
'Number of values does not match the number of ' +
'nodes in the grid {0} grid nodes vs {1} data'.format(
self.grid.nr_of_nodes, subdata.shape,
)
)
return_ids = []
... | csn_ccr |
returns the handle to the property manager
@return PropertyManager | public static PropertyManager getInstance() {
if (instance == null) {
try {
initializePropertyManager();
}
catch (StartupException e) {
// should not reach here, as the property manager should be
// initialized by now
... | csn |
Calculate the remaining height of this component on this page.
This is used to calculate a smart page break that does not split a control
between pages.
@return The remaining height of this component on this page. | public int calcComponentPageHeight()
{
remainingComponentHeight = remainingComponentHeight + this.checkComponentHeight();
if (remainingComponentHeight <= remainingPageHeight)
return remainingComponentHeight;
if (currentComponent == null)
return 0; // Never
i... | csn |
// DefaultConfig returns a default configuration specifying basic key
// usage and a 1 year expiration time. The key usages chosen are
// signing, key encipherment, client auth and server auth. | func DefaultConfig() *SigningProfile {
d := helpers.OneYear
return &SigningProfile{
Usage: []string{"signing", "key encipherment", "server auth", "client auth"},
Expiry: d,
ExpiryString: "8760h",
}
} | csn |
public function generate($basePath, $pretty)
{
$fileReflectorRegister = new ReflectorRegister();
$rootPath = $this->executionPath;
foreach ($this->files as $file) {
$currentFileArr = $this->isComponent
? explode("/$basePath/", $file)
: explode("$r... | $this->isComponent
);
} else {
$content = file_get_contents($file);
$parser = new MarkdownParser($currentFile, $content, $id);
}
$document = $parser->parse();
if ($document) {
$writer = new Writer... | csn_ccr |
def display_db_info(self):
"""Displays some basic info about the GnuCash book"""
with self.open_book() | as book:
default_currency = book.default_currency
print("Default currency is ", default_currency.mnemonic) | csn_ccr |
def get_active_schedulings(self):
"""Return EighthScheduledActivity's of this activity since the beginning of the year."""
blocks = EighthBlock.objects.get_blocks_this_year()
scheduled_activities | = EighthScheduledActivity.objects.filter(activity=self)
scheduled_activities = scheduled_activities.filter(block__in=blocks)
return scheduled_activities | csn_ccr |
Add a pointer to the key value pair with the provided parameters. | final void addPointer(int keyPos, int keySize, int valuePos, int valueSize) {
assert keyPos + keySize == valuePos;
int start = memoryBuffer.limit() - POINTER_SIZE_BYTES;
memoryBuffer.putInt(start, keyPos);
memoryBuffer.putInt(start + 4, valuePos);
memoryBuffer.putInt(start + 8, valueSize);
memor... | csn |
Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation. | def stop_instance(self):
"""Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation.
"""
stop_url = self._get_url('stop_path')
res = self.rest_client.session.put(stop_url, json={})
_handle_http_erro... | csn |
Delete single item from SingleBlockManager.
Ensures that self.blocks doesn't become empty. | def delete(self, item):
"""
Delete single item from SingleBlockManager.
Ensures that self.blocks doesn't become empty.
"""
loc = self.items.get_loc(item)
self._block.delete(loc)
self.axes[0] = self.axes[0].delete(loc) | csn |
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String sOpDirectory) {
logger.entering(new Object[] { xmlSuites, suites, sOpDirectory });
if (ListenerManager.isCurrentMethodSkipped(this)) {
logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG);
return;
... | try {
Path opDirectory = Paths.get(sOpDirectory);
if (!Files.exists(opDirectory)) {
Files.createDirectories(Paths.get(sOpDirectory));
}
FileOutputStream fOut = new FileOutputStream(p.toFile());
wb.write(fOut);
fOut.flush();
... | csn_ccr |
public function remove($key) {
$key = $this->formatKey($key); |
array_remove($this->headers, $key);
} | csn_ccr |
@Override
public <N extends SpatialComparable> List<List<N>> partition(List<N> spatialObjects, int minEntries, int maxEntries) {
List<List<N>> partitions = new ArrayList<>();
List<N> objects = new ArrayList<>(spatialObjects);
while (!objects.isEmpty()) {
StringBuilder msg = new StringBuilder();
... | for (int i = 0; i < splitPoint; i++) {
N o = objects.remove(0);
partition1.add(o);
}
partitions.add(partition1);
// copy array
if (LOG.isDebugging()) {
msg.append("\ncurrent partition ").append(partition1);
msg.append("\nremaining objects # ").append(object... | csn_ccr |
Iterates over all existing user identities that can be used with Vidyo | def iter_user_identities(user):
"""Iterates over all existing user identities that can be used with Vidyo"""
from indico_vc_vidyo.plugin import VidyoPlugin
providers = authenticators_re.split(VidyoPlugin.settings.get('authenticators'))
done = set()
for provider in providers:
for _, identifie... | csn |
Called by the GMS when a VIEW is received.
@param view The view to be installed
@param digest If view is a MergeView, the digest contains the seqnos of all members and has to be set by GMS | public void handleViewChange(View view, Digest digest) {
if(gms.isLeaving() && !view.containsMember(gms.local_addr))
return;
View prev_view=gms.view();
gms.installView(view, digest);
Address prev_coord=prev_view != null? prev_view.getCoord() : null, curr_coord=view.getCoord()... | csn |
// Interfaces returns a list of interfaces. | func (b *BigIP) Interfaces() (*Interfaces, error) {
var interfaces Interfaces
err, _ := b.getForEntity(&interfaces, uriNet, uriInterface)
if err != nil {
return nil, err
}
return &interfaces, nil
} | csn |
def find_bin(self, value):
"""Index of bin corresponding to a value.
Parameters
----------
value: float
Value to be searched for.
Returns
-------
int
index of bin to which value belongs
(-1=underflow, N=overflow, None=not foun... | value <= self.bin_right_edges[-1]:
return ixbin - 1
else:
return self.bin_count
elif value < self.bin_right_edges[ixbin - 1]:
return ixbin - 1
elif ixbin == self.bin_count:
return self.bin_count
else:
return None | csn_ccr |
Adds a cookie for a cURL transfer
Examples:
$curl->addCookie('user', 'admin');
$curl->addCookie(array('user'=>'admin', 'test'=>1));
@param string|array $name Name of cookie or array of cookies (name=>value)
@param string $value Value of cookie | public function addCookie($name, $value = null)
{
if (is_array($name)) {
$this->cookies = $name + $this->cookies;
} else {
$this->cookies[$name] = $value;
}
} | csn |
// AddProgressBar will create a new ProgressBar, register it with this
// ProgressBarPrinter, and return it. This must be called at least once before
// PrintAndWait is called. | func (pbp *ProgressBarPrinter) AddProgressBar() *ProgressBar {
pb := &ProgressBar{}
pbp.lock.Lock()
pbp.progressBars = append(pbp.progressBars, pb)
pbp.lock.Unlock()
return pb
} | csn |
//getService is an internal method that returns a Service without filling in all related service data like address assignments
//and modified config files | func (f *Facade) getService(ctx datastore.Context, id string) (service.Service, error) {
glog.V(3).Infof("Facade.getService: id=%s", id)
store := f.serviceStore
svc, err := store.Get(ctx, id)
if err != nil || svc == nil {
return service.Service{}, err
}
return *svc, err
} | csn |
public function getLookupResults($type, $filter = '', $limit = 10) |
{
return $this->getRepository()->getValueList($type, $filter, $limit);
} | csn_ccr |
func (c *Container) Inspect(ctx context.Context) (*enginetypes.VirtualizationInfo, error) {
if c.Engine == nil {
return nil, ErrNilEngine
}
inspectCtx, | cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return c.Engine.VirtualizationInspect(inspectCtx, c.ID)
} | csn_ccr |
def dispatch(self, request, *args, **kwargs):
"""
Overrides Django's default dispatch to provide caching.
If the should_cache method returns True, this will call
two functions get_cache_version and get_cache_prefix
the results of those two functions are combined and passed to
... | if self.should_cache():
prefix = "%s:%s" % (self.get_cache_version(),
self.get_cache_prefix())
# Using middleware here since that is what the decorator uses
# internally and it avoids making this code all complicated with
# all sorts o... | csn_ccr |
Combines multiple records into one. Error level of the combined record
will be the highest level from the given records. Datetime will be taken
from the first record. | private function combineRecords(array $records): array
{
$batchRecord = null;
$batchRecords = [];
$messages = [];
$formattedMessages = [];
$level = 0;
$levelName = null;
$datetime = null;
foreach ($records as $record) {
$record = $this->pr... | csn |
def run_dict_method(self, request):
"""Execute a method on the state ``dict`` and reply with the result."""
state_method_name, args, kwargs = (
request[Msgs.info],
request[Msgs.args],
request[Msgs.kwargs],
| )
# print(method_name, args, kwargs)
with self.mutate_safely():
self.reply(getattr(self.state, state_method_name)(*args, **kwargs)) | csn_ccr |
def _get_basic_info(ca_name, cert, ca_dir=None):
'''
Get basic info to write out to the index.txt
'''
if ca_dir is None:
ca_dir = '{0}/{1}'.format(_cert_base_path(), ca_name)
index_file = "{0}/index.txt".format(ca_dir)
cert = _read_cert(cert)
expire_date = _four_digit_year_to_two_d... | add the rest of the subject
subject += '/'.join(
['{0}={1}'.format(
x, y
) for x, y in cert.get_subject().get_components()]
)
subject += '\n'
return (index_file, expire_date, serial_number, subject) | csn_ccr |
Cherry has a string S$S$ consisting of lowercase English letters. Using this string, he formed a pyramid of infinite length with certain rules:
- N$N$-th row of pyramid contains N$N$ characters.
- Each row of pyramid begins with the first character of the string.
- The subsequent characters of the row are appended to t... | def search(arr, lenl, val):
s = 0
l = lenl - 1
total = 0
while (s <= l):
m = int((s + l) / 2)
if (arr[m] <= val):
total = m + 1
s = m + 1
else:
l = m - 1
return total
def kmpsearch(string, lps):
lis = []
... | apps |
// ShowAccount returns the account details for the account with the given
// subscription ID. If the subscription is empty then the default Azure
// CLI account is returned. | func (a AzureCLI) ShowAccount(subscription string) (*Account, error) {
cmd := []string{"account", "show"}
if subscription != "" {
cmd = append(cmd, "--subscription", subscription)
}
var acc showAccount
if err := a.run(&acc, cmd...); err != nil {
return nil, errors.Trace(err)
}
if acc.Account.CloudName == "" ... | csn |
finc uniqe values in list of list python | def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq | cosqa |
// Reset clears the metrics store. | func (s *Store) Reset() {
s.mu.Lock()
s.metrics = make(map[string][]time.Duration)
s.mu.Unlock()
s.diffmu.Lock()
s.diffs = make(map[string]*diff)
s.diffmu.Unlock()
} | csn |
function isChrome14OrHigher() {
return (qq.chrome() || qq.opera()) &&
| navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
} | csn_ccr |
Processes the Emoji data to emoticon regex | private static void processEmoticonsToRegex() {
List<String> emoticons=new ArrayList<String>();
for(Emoji e: emojiData) {
if(e.getEmoticons()!=null) {
emoticons.addAll(e.getEmoticons());
}
}
//List of emotions should be pre-processed to handle instances of subtrings like :-) :-
//Without th... | csn |
public ImageDescriptor forStaticConstructor() {
return getDecorated(
getMethodImageDescriptor(false, toFlags(JvmVisibility.PUBLIC)),
| JavaElementImageDescriptor.CONSTRUCTOR | JavaElementImageDescriptor.STATIC);
} | csn_ccr |
Unmarshall a DOMElement object corresponding to a DrawingInteraction element.
@param \DOMElement $element A DOMElement object.
@return \qtism\data\QtiComponent A DrawingInteraction object.
@throws \qtism\data\storage\xml\marshalling\UnmarshallingException | protected function unmarshall(DOMElement $element)
{
if (($responseIdentifier = $this->getDOMElementAttributeAs($element, 'responseIdentifier')) !== null) {
$objectElts = $this->getChildElementsByTagName($element, 'object');
if (count($objectElts) > 0) {
$objectElt =... | csn |
def plot_quadpole_evolution(dataobj, quadpole, cols, threshold=5,
rolling=False, ax=None):
"""Visualize time-lapse evolution of a single quadropole.
Parameters
----------
dataobj : :py:class:`pandas.DataFrame`
DataFrame containing the data. Please refer to the docume... | fig = ax.get_figure()
else:
fig, ax = plt.subplots(1, 1, figsize=(20 / 2.54, 7 / 2.54))
ax.plot(
subquery['timestep'],
subquery[cols],
'.',
color='blue',
label='valid data',
)
if rolling:
# rolling mean
rolling_m = subquery.rolling(3,... | csn_ccr |
Clean WebServer Class Logs Messages
@return bool | public function cleanLog()
{
if (isset($this->err)) {
$this->err = array();
}
if (isset($this->war)) {
$this->war = array();
}
if (isset($this->msg)) {
$this->msg = array();
}
if (isset($this->deb)) {
$this->deb ... | csn |
func (config *DirectClientConfig) Namespace() (string, bool, error) {
if config.overrides != nil && config.overrides.Context.Namespace != "" {
// In the event we have an empty config but we do have a namespace override, we should return
// the namespace override instead of having config.ConfirmUsable() return an e... | if err := config.ConfirmUsable(); err != nil {
return "", false, err
}
configContext, err := config.getContext()
if err != nil {
return "", false, err
}
if len(configContext.Namespace) == 0 {
return "default", false, nil
}
return configContext.Namespace, false, nil
} | csn_ccr |
public static Object[] objects(Object first, Object second, Object third) {
| return new Object[] { first, second, third };
} | csn_ccr |
function GetLabelArray($val_prop, $label_prop)
{
// check the cache
// $cachekey = md5($this->_sql . " VAL=".$val_prop." LABEL=" . $label_prop);
$cachekey = $this->_sql . " VAL=".$val_prop." LABEL=" . $label_prop;
$arr = $this->GetDelayedCache($cachekey);
// if no cache, go to the db
if ($arr... | $this->UnableToCache = false;
while ($object = $this->Next())
{
$arr[$object->$val_prop] = $object->$label_prop;
}
$this->_phreezer->SetValueCache($cachekey, $arr, $this->_cache_timeout);
$this->UnlockCache($cachekey);
}
return $arr;
} | csn_ccr |
// failOrder marks an order as failed by setting the problem details field of
// the order & persisting it through the SA. If an error occurs doing this we
// log it and return the order as-is. There aren't any alternatives if we can't
// add the error to the order. | func (ra *RegistrationAuthorityImpl) failOrder(
ctx context.Context,
order *corepb.Order,
prob *probs.ProblemDetails) *corepb.Order {
// Convert the problem to a protobuf problem for the *corepb.Order field
pbProb, err := bgrpc.ProblemDetailsToPB(prob)
if err != nil {
ra.log.AuditErrf("Could not convert order ... | csn |
func (yfast *YFastTrie) Predecessor(key uint64) Entry {
entry := yfast.predecessor(key)
| if entry == nil {
return nil
}
return entry
} | csn_ccr |
public function delete($hashValue = null, $rangeValue = null)
{
$this->setQueryClass(DeleteItem::class);
if ($hashValue !== null) {
| $this->setPrimaryKey($hashValue, $rangeValue);
}
return $this;
} | csn_ccr |
Internal to find a counter in a group.
@param counterName the name of the counter
@param displayName the display name of the counter
@return the counter that was found or added | protected Counter findCounter(String counterName, String displayName) {
Counter result = counters.get(counterName);
if (result == null) {
result = new Counter(counterName, displayName);
counters.put(counterName, result);
}
return result;
} | csn |
public E password(String password) {
Misc.checkNotNull(password, "password");
this.password = password;
| //noinspection unchecked
return (E) this;
} | csn_ccr |
// ParseDERSignature parses a signature in DER format for the curve type
// `curve` into a Signature type. If parsing according to the less strict
// BER format is needed, use ParseSignature. | func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
return parseSig(sigStr, curve, true)
} | csn |
region Service Operation | public void start() throws Exception {
Exceptions.checkNotClosed(this.closed, this);
log.info("Initializing metrics provider ...");
MetricsProvider.initialize(builderConfig.getConfig(MetricsConfig::builder));
statsProvider = MetricsProvider.getMetricsProvider();
statsProvider.st... | csn |
func (wi WorkItemStorage) Equal(u convert.Equaler) bool {
other, ok := u.(WorkItemStorage)
if !ok {
return false
}
if !convert.CascadeEqual(wi.Lifecycle, other.Lifecycle) {
return false
}
if wi.Number != other.Number {
return false
}
if wi.Type != other.Type {
return false
}
if wi.ID != other.ID {
r... |
}
if wi.Number != other.Number {
return false
}
if wi.SpaceID != other.SpaceID {
return false
}
if !reflect.DeepEqual(wi.RelationShipsChangedAt, other.RelationShipsChangedAt) {
return false
}
return convert.CascadeEqual(wi.Fields, other.Fields)
} | csn_ccr |
def invitations():
"""List and manage received invitations.
"""
with Session() as session:
try:
result = session.VFolder.invitations()
invitations = result.get('invitations', [])
if len(invitations) < 1:
print('No invitations.')
ret... | manage: ')
if selection.isdigit():
selection = int(selection) - 1
else:
return
if 0 <= selection < len(invitations):
while True:
action = input('Choose action. (a)ccept, (r)eject, (c)ancel: ')
if... | csn_ccr |
Interprets positional and keyword arguments related to
framers.
:param args: A tuple of positional arguments. The first such
argument will be interpreted as a framer object,
and the second will be interpreted as a framer
state.
:pa... | def _interpret_framer(self, args, kwargs):
"""
Interprets positional and keyword arguments related to
framers.
:param args: A tuple of positional arguments. The first such
argument will be interpreted as a framer object,
and the second will be ... | csn |
public function removeValue($key)
{
if (!$this->isValid()) {
throw new \LogicException('Session is in an invalid state.');
}
if ($this->storage->hasValue($key)) {
| $this->storage->removeValue($key);
return true;
}
return false;
} | csn_ccr |
public void commit(boolean force) {
if (checkSession()) {
return;
}
if (log.isDebugEnabled()) {
ToStringBuilder tsb = new ToStringBuilder(String.format("Committing transactional %s@%x",
| sqlSession.getClass().getSimpleName(),sqlSession.hashCode()));
tsb.append("force", force);
log.debug(tsb.toString());
}
sqlSession.commit(force);
} | csn_ccr |
Get command to pass it into the process.
The method will append the input file path argument to the end, like
described in the `drafter --help` output.
@return string | private function getProcessCommand()
{
$options = $this->transformOptions();
$options[] = escapeshellarg($this->input);
$command = $this->binary . ' ' . implode(' ', $options);
return $command;
} | csn |
Return a YAML defined array of select field value options.
@param Bag $field
@return array | private function getYamlValues(Bag $field)
{
$values = array_slice($field->get('values', []), 0, $field->get('limit', self::DEFAULT_LIMIT), true);
if ($field->get('sortable')) {
asort($values, SORT_REGULAR);
}
return $values;
} | csn |
Escape the specified user.
@param user
The user name to correct.
@return The escaped user. | private static String correctUser(String user) {
if (user != null && user.trim().length() > 0
&& (false || user.indexOf('%') == -1)) {
String escaped = escapeSpecialAsciiAndNonAscii(user);
StringBuilder totalEscaped = new StringBuilder();
for (int i = 0; i < escaped.length(); i++) {
... | csn |
public function content()
{
$arguments = func_get_args();
$count = count($arguments);
if ($count > 0) {
$this->setText($arguments[0]);
}
if ($count > 1) {
if (is_bool($arguments[1])) {
| $this->setMarkdown($arguments[1]);
if ($count > 2) {
$this->setNotification($arguments[2]);
}
} else {
call_user_func_array([$this, 'addAttachment'], array_slice($arguments, 1));
}
}
return $this;... | csn_ccr |
Copy map data from `source` to `dest`.
.. deprecated:: 4.5
Use Python's copy module, or see :any:`tcod.map.Map` and assign between
array attributes manually. | def map_copy(source: tcod.map.Map, dest: tcod.map.Map) -> None:
"""Copy map data from `source` to `dest`.
.. deprecated:: 4.5
Use Python's copy module, or see :any:`tcod.map.Map` and assign between
array attributes manually.
"""
if source.width != dest.width or source.height != dest.hei... | csn |
def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None,
xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, kde_shade=True, gridsize=None, ax=None,
despine=False, **kwargs):
"""
Retur... | ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
ax.tick_params(labelbottom="off", labelleft="off")
ax.set_title(title, fontsize=18)
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
if kind == "scatter":
ax.scatter(x, y, c=color, **kwargs)
elif kind ==... | csn_ccr |
def _cleanup_pods(namespace, labels):
""" Remove all pods with these labels in this namespace """
api = kubernetes.client.CoreV1Api()
pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels))
for pod in pods.items:
try:
api.delete_namespaced_pod(pod.metadata.nam... | logger.info('Deleted pod: %s', pod.metadata.name)
except kubernetes.client.rest.ApiException as e:
# ignore error if pod is already removed
if e.status != 404:
raise | csn_ccr |
public synchronized CheckBoxList<V> addItem(V object, boolean checkedState) {
| itemStatus.add(checkedState);
return super.addItem(object);
} | csn_ccr |
You are given two binary strings $S$ and $P$, each with length $N$. A binary string contains only characters '0' and '1'. For each valid $i$, let's denote the $i$-th character of $S$ by $S_i$.
You have to convert the string $S$ into $P$ using zero or more operations. In one operation, you should choose two indices $i$ ... |
def solve(s, p):
diffs = 0
for x, y in zip(s, p):
if x == y:
continue
if x == '0':
if diffs < 1:
return "No"
diffs -= 1
else:
diffs += 1
return "Yes" if diffs == 0 else "No"
for _ in range(int(input())):
l = int(input())
s = input().strip()
p = input().strip()
print(solve(s, p))
| apps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.