query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
public function GetTotalDiscountValue()
{
$iCurrentPosition = $this->getItemPointer();
$this->GoToStart();
$dTotalDiscountValue = 0;
while ($oItem = &$this->Next()) {
| $dTotalDiscountValue += ($oItem->dPriceTotal - $oItem->dPriceTotalAfterDiscount);
}
$this->setItemPointer($iCurrentPosition);
return $dTotalDiscountValue;
} | csn_ccr |
Part of Series 2/3
This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-for-real).
In this kata you have to write a Morse code decoder for w... | def decodeBits(bits):
import re
# remove trailing and leading 0's
bits = bits.strip('0')
# find the least amount of occurrences of either a 0 or 1, and that is the time hop
time_unit = min(len(m) for m in re.findall(r'1+|0+', bits))
# hop through the bits and translate to morse
... | apps |
public function fetchResult($result)
{
$fetchMode = $this->fetchMode;
switch ($fetchMode) {
case PDO::FETCH_ASSOC:
return $result->result_array();
case PDO::FETCH_OBJ:
| return $result->result();
}
throw new \BadMethodCallException("Unsupported fetch mode '$fetchMode'.");
} | csn_ccr |
public function add($element) {
if (!in_array($element, $this->collection, true)) {
| $this->collection[$this->size()] = $element;
}
return $this;
} | csn_ccr |
Alice likes prime numbers. According to Alice, only those strings are nice whose sum of character values at a prime position is prime. She has a string $S$. Now, she has to count the number of nice strings which come before string $S$( including $S$) in the dictionary and are of the same length as $S$.
Strings are zer... | import sys
from collections import defaultdict
from copy import copy
MOD = 10**9 + 7
R = lambda t = int: t(input())
RL = lambda t = int: [t(x) for x in input().split()]
RLL = lambda n, t = int: [RL(t) for _ in range(n)]
# primes up to n
def primes(n):
P = []
n = int(n)
U = [1] * (n+1)
p = 2
... | apps |
Loads context environment readers.
@param ContainerBuilder $container | private function loadEnvironmentReader(ContainerBuilder $container)
{
$definition = new Definition('Behat\Behat\Context\Environment\Reader\ContextEnvironmentReader');
$definition->addTag(EnvironmentExtension::READER_TAG, array('priority' => 50));
$container->setDefinition(self::getEnvironmen... | csn |
Push package to the device and install it.
Args:
option:
-l: forward lock application
-r: replace existing application
-t: allow test packages
-s: install application on sdcard
-d: allow version code downgrade (debuggab... | def install(self, package: str, option: str = '-r') -> None:
'''Push package to the device and install it.
Args:
option:
-l: forward lock application
-r: replace existing application
-t: allow test packages
-s: install applicat... | csn |
// ConnectWithUnixSocket makes a OVSDB Connection via a Unix Socket | func ConnectWithUnixSocket(socketFile string) (*OvsdbClient, error) {
if _, err := os.Stat(socketFile); os.IsNotExist(err) {
return nil, errors.New("Invalid socket file")
}
return ConnectUsingProtocol("unix", socketFile)
} | csn |
Get the path of current request.
@return string
@since 3.6.1 | public function getPath()
{
if ($this->requestTarget === null) {
return $this->uri->getPath();
}
list($path) = explode('?', $this->requestTarget);
return $path;
} | csn |
Renders a user enrolment action
@param user_enrolment_action $icon
@return string | protected function render_user_enrolment_action(user_enrolment_action $icon) {
return html_writer::link($icon->get_url(), $this->output->render($icon->get_icon()), $icon->get_attributes());
} | csn |
function addAddedFileInnScript(key, path, dot_path){
dot_path = dot_path || path;
// checking if same file imported twice for same Class.
if(!dot_path) return;
| var script = scriptArr[scriptArr.length - 1];
if( !script ){
return;
}
var arr = script[key] || (script[key] = []);
if( arr.indexOf(dot_path) === -1 ) {
arr.push(dot_path);
}
return true;
} | csn_ccr |
def get_process_output(process, encoding=None):
"""Get the output from the process."""
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = locale.getpreferredencoding()
|
if returncode != 0:
raise RuntimeError("Runtime Error: %s" % (output[0].rstrip().decode(encoding, errors='replace')))
return output[0].decode(encoding, errors='replace') | csn_ccr |
private static <T> void swapReferences( T[] arr, int idx1, int idx2 )
{
T tmp = arr[idx1]; |
arr[idx1] = arr[idx2];
arr[idx2] = tmp;
} | csn_ccr |
def character_delta(self, char, *, store=True):
"""Return a dictionary of changes to ``char`` since previous call."""
ret = self.character_stat_delta(char, store=store)
nodes = self.character_nodes_delta(char, store=store)
chara = self._real.character[char]
if nodes:
... | if orig not in chara.portal:
continue
portals = chara.portal[orig]
for dest, rb in dests.items():
if dest not in portals:
continue
ret.setdefault('edge_val', {}).setdefault(orig, {}).setdefaul... | csn_ccr |
Given an Interval or IntervalIndex, return the corresponding interval with
closed bounds. | def _get_interval_closed_bounds(interval):
"""
Given an Interval or IntervalIndex, return the corresponding interval with
closed bounds.
"""
left, right = interval.left, interval.right
if interval.open_left:
left = _get_next_label(left)
if interval.open_right:
right = _get_pr... | csn |
public void updateServiceInstanceInternalStatus(String serviceName, String instanceId, OperationalStatus status, final RegistrationCallback cb, Object context){
ProtocolHeader header = new ProtocolHeader();
header.setType(ProtocolType.UpdateServiceInstanceInternalStatus);
UpdateServiceInstanceI... | public void call(boolean result, Response response,
ErrorCode error, Object ctx) {
cb.call(result, error, ctx);
}
};
connection.submitCallbackRequest(header, protocol, pcb, context);
} | csn_ccr |
// ApproxEqual performs an element-wise approximate equality test between two matrices,
// as if FloatEqual had been used. | func (m1 Mat4x2) ApproxEqual(m2 Mat4x2) bool {
for i := range m1 {
if !FloatEqual(m1[i], m2[i]) {
return false
}
}
return true
} | csn |
def get_truetype(value):
"""Convert a string to a pythonized parameter."""
if value in ["true", "True", "y", "Y", "yes"]:
return True
if value in | ["false", "False", "n", "N", "no"]:
return False
if value.isdigit():
return int(value)
return str(value) | csn_ccr |
Is the given data multibase encoded?
@param {Buffer|string} bufOrString
@returns {boolean}
@memberof Multibase | function isEncoded (bufOrString) {
if (Buffer.isBuffer(bufOrString)) {
bufOrString = bufOrString.toString()
}
// Ensure bufOrString is a string
if (Object.prototype.toString.call(bufOrString) !== '[object String]') {
return false
}
const code = bufOrString.substring(0, 1)
try {
const base = ... | csn |
func NewCRLFromDB(certs []certdb.CertificateRecord, issuerCert *x509.Certificate, key crypto.Signer, expiryTime time.Duration) ([]byte, error) {
var revokedCerts []pkix.RevokedCertificate
newExpiryTime := time.Now().Add(expiryTime)
// For every record, create a new | revokedCertificate and add it to slice
for _, certRecord := range certs {
serialInt := new(big.Int)
serialInt.SetString(certRecord.Serial, 10)
tempCert := pkix.RevokedCertificate{
SerialNumber: serialInt,
RevocationTime: certRecord.RevokedAt,
}
revokedCerts = append(revokedCerts, tempCert)
}
retu... | csn_ccr |
This sets the unique ID associated with this machine. This will
persist this ID so that in the future Vagrant will be able to find
this machine again. The unique ID must be absolutely unique to the
virtual machine, and can be used by providers for finding the
actual machine associated with this instance.
**WARNIN... | def id=(value)
@logger.info("New machine ID: #{value.inspect}")
id_file = nil
if @data_dir
# The file that will store the id if we have one. This allows the
# ID to persist across Vagrant runs. Also, store the UUID for the
# machine index.
id_file = @data_dir.join("id"... | csn |
Return the text and html contents of the Template
@param string $id
@return array | public function getDetailContent($id)
{
$response = $this->mailjet->get(Resources::$TemplateDetailcontent,
['id' => $id]);
if (!$response->success()) {
$this->throwError("TemplateService:getDetailContent failed",
$response);
}
return $response... | csn |
// retrievePowerlessTickets fetches missed or expired tickets sorted by
// revocation status. | func retrievePowerlessTickets(ctx context.Context, db *sql.DB) (*apitypes.PowerlessTickets, error) {
rows, err := db.QueryContext(ctx, internal.SelectTicketSpendTypeByBlock, -1)
if err != nil {
return nil, err
}
defer closeRows(rows)
unspentType := int16(dbtypes.TicketUnspent)
revokedType := int16(dbtypes.Tick... | csn |
Create a Category
@return \AvoRed\Framework\Models\Database\Categoy | public function create($data)
{
if (Session::has('multi_language_enabled')) {
$languageId = $data['language_id'];
$languaModel = Language::find($languageId);
if ($languaModel->is_default) {
return Category::create($data);
} else {
... | csn |
public static List<String> get(BeanFactory beanFactory) {
try {
return beanFactory.getBean(BEAN, BasePackages.class).get();
}
catch (NoSuchBeanDefinitionException ex) { |
throw new IllegalStateException(
"Unable to retrieve @EnableAutoConfiguration base packages");
}
} | csn_ccr |
public function getACHBankAccount( CustomerVault\Profile $profile, CustomerVault\ACHBankaccounts $bankDetails )
{
$profile->setRequiredFields(array('id'));
$profile->checkRequiredFields();
$bankDetails->setRequiredFields(array('id'));
$bankDetails->checkRequiredFields();
$req... | 'uri' => $this->prepareURI("/profiles/" . $profile->id . "/achbankaccounts/" . $bankDetails->id),
'body' => $profile
));
print_r($request);
$response = $this->client->processRequest($request);
print_r($response);
return new CustomerVault\ACHBankaccounts($response)... | csn_ccr |
Get Monzo access token via OAuth2 `authorization code` grant type.
Official docs:
https://monzo.com/docs/#acquire-an-access-token
:returns: OAuth 2 access token
:rtype: dict | def _get_oauth_token(self):
"""
Get Monzo access token via OAuth2 `authorization code` grant type.
Official docs:
https://monzo.com/docs/#acquire-an-access-token
:returns: OAuth 2 access token
:rtype: dict
"""
url = urljoin(self.api_url, '/oauth2/tok... | csn |
python json loads enforce ascii | def json(body, charset='utf-8', **kwargs):
"""Takes JSON formatted data, converting it into native Python objects"""
return json_converter.loads(text(body, charset=charset)) | cosqa |
protected List<ModuleBuildFuture> collectFutures(ModuleList moduleList, HttpServletRequest request)
throws IOException {
final String sourceMethod = "collectFutures"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(sourceClass, sourceMethod... | the browser.
if (options.isDevelopmentMode() || options.isDebugMode()) {
try {
nonErrorMessages.add(future.get().getErrorMessage());
} catch (Exception ex) {
// Sholdn't ever happen as this is a CompletedFuture
throw new RuntimeException(ex);
}
}
if (isTra... | csn_ccr |
public function buildPostRequest($uri, $query, $param, $headers = [], $isAsync = false)
{
$query_param = array_merge(['xh' => $this->stu_id], $query);
$post = [
'query' => $query_param,
'headers' => $headers,
| 'form_params' => $param,
];
//If opened cookie cache
if ($this->cacheCookie) {
$post['cookies'] = $this->getCookie();
}
//If use getAll(), use the Async request.
return $isAsync
? $this->client->postAsync($uri, $post)
: $this... | csn_ccr |
// Returns a visualization of the string. | func (s StringObject) String() string {
return fmt.Sprintf("StringObject{Key: %s, Value: '%s'}", DataToString(s.Key), DataToString(s.Value))
} | csn |
public function setType($parameterIndex, ObjectTypeInterface $type)
{
| $this->setParameter($parameterIndex, $this->escape($type->getQueryName()));
} | csn_ccr |
Get outdated packages with their current and latest version.
@param array $excluded
@return array | public function getOutdatedPackages(array $excluded = [])
{
// Get all installed and required packages.
$installed = $this->composer->getInstalledPackages();
$required = $this->composer->getRequiredPackages();
$outdated = [];
// Get the installed version number of the requi... | csn |
public function constructWith($arguments = []): self
{
if ($this->callParentConstructorMethod) {
if (!$arguments instanceof Arguments) {
$arguments = new Arguments($arguments);
}
|
$this->callParentConstructorMethod->invoke($this->mock, $arguments);
}
return $this;
} | csn_ccr |
Check whether snapshots already exists for a given name.
@param snapshotName the user supplied snapshot name
@return true if the snapshot exists | public boolean snapshotExists(String snapshotName)
{
assert snapshotName != null;
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
{
if (cfStore.snapshotExists(snapshotName))
return true;
}
return false;
} | csn |
python datetime now utc | def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now() | cosqa |
def iterate(self, max_iter=None):
"""Yields items from the mux, and handles stream exhaustion and
replacement.
"""
if max_iter is None:
max_iter = np.inf
# Calls Streamer's __enter__, which calls activate()
with self as active_mux:
# Main sampling... | n += 1
active_mux.stream_counts_[idx] += 1
except StopIteration:
# Oops, this stream is exhausted.
# Call child-class exhausted-stream behavior
active_mux._on_stream_exhausted(idx)
# Setup a new... | csn_ccr |
def trim_N_nucleotides(prefix, suffix):
"""
Drop all occurrences of 'N' from prefix and suffix nucleotide strings
by trimming.
"""
if 'N' in prefix:
# trim prefix to exclude all occurrences of N
rightmost_index = prefix.rfind('N')
logger.debug(
| "Trimming %d nucleotides from read prefix '%s'",
rightmost_index + 1, prefix)
prefix = prefix[rightmost_index + 1:]
if 'N' in suffix:
leftmost_index = suffix.find('N')
logger.debug(
"Trimming %d nucleotides from read suffix '%s'",
len(suffix) - l... | csn_ccr |
def provide(prompt, options = {})
options.reverse_merge! required: true, default: nil
required = options[:required] && !options[:default]
prompt = "#{defaulted_prompt(prompt, options[:default])}: "
if Stairs.configuration.use_defaults && options[:default]
| options[:default]
else
Stairs::Util::CLI.collect(prompt.blue, required: required) ||
options[:default]
end
end | csn_ccr |
returns a copy of the array with all false values removed
@param {Array} array - array
@param {Function} fn - predicate function for cluster rule | function compact(array) {
const aResult = [];
for (let idx = 0, len = array.length; idx < len; idx++) {
if (array[idx]) { aResult.push(array[idx]); }
}
return aResult;
} | csn |
func (s *Sling) Base(rawURL string) | *Sling {
s.rawURL = rawURL
return s
} | csn_ccr |
public function getModuleFullPath($sModuleId = null)
{
if (!$sModuleId) {
$sModuleId = $this->getId();
}
if ($sModuleDir = $this->getModulePath($sModuleId)) {
| return \OxidEsales\Eshop\Core\Registry::getConfig()->getModulesDir() . $sModuleDir;
}
return false;
} | csn_ccr |
func WithLevels(levels ...logrus.Level) OptionFunc {
return func(h | *Hook) {
h.triggers = levels
}
} | csn_ccr |
func ConcatenateBytes(data ...[]byte) []byte {
finalLength := 0
for _, slice := range data {
finalLength += len(slice)
}
result := make([]byte, finalLength)
last := 0
for _, slice := range data | {
for i := range slice {
result[i+last] = slice[i]
}
last += len(slice)
}
return result
} | csn_ccr |
// EnsureLoadBalancerDeleted deletes the specified load balancer if it exists, returning
// nil if the load balancer specified either didn't exist or was successfully deleted. | func (cs *CSCloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *v1.Service) error {
klog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v, %v)", clusterName, service.Namespace, service.Name)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if er... | csn |
Function used to overwrite the input argument from a schema file
Can also be used to overwrite an argument hardcoded in the Twig file.
Use `setCustomFormData` to set any other tag.
@param string $inputName The input name where the argument will be added
@param string $property The argument name. Example "data-color"
... | public function setInputArgument($inputName, $property, $data)
{
if ($this->schema->has($inputName)) {
// Get the element and force set the property
$element = $this->schema->get($inputName);
$element['form'][$property] = $data;
// Push back the modifyed elem... | csn |
Returns the menu with the specified label, or creates one if it does not exist.
@param parent The parent component under which to search. May be a Toolbar or a Menupopup
component.
@param label Label of menu to search.
@param insertBefore If not null, the new menu is inserted before this one. If null, the menu
is appe... | public static BaseMenuComponent findMenu(BaseComponent parent, String label, BaseComponent insertBefore) {
for (BaseMenuComponent child : parent.getChildren(BaseMenuComponent.class)) {
if (label.equalsIgnoreCase(child.getLabel())) {
return child;
}
}
Bas... | csn |
Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
size : int | 'lines'; default: null
... | def chunks(stream, size=None):
'''
Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
... | csn |
def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If an... | devices = list(map(lambda device: device[0], devices))
yield self.__deleteInactiveDevices(bare_jid, devices)
if not global_max == None:
all_inactive_devices = []
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(ba... | csn_ccr |
Returns configuration entry from the cache
@param string $module
@param string $name
@param mixed $default
@return mixed | public function get($module, $name, $default = false)
{
$this->initializeOnDemand();
return $this->arrayConfig->get($module, $name, $default);
} | csn |
Return a Pandas dataframe. | def pandas(self):
"""Return a Pandas dataframe."""
if self._pandas is None:
self._pandas = pd.DataFrame().from_records(self.list_of_dicts)
return self._pandas | csn |
public function hydrate(HydrationEvent $event, $eventName, $eventDispatcher)
{
// Possibility to load serialized cache
$eventDispatcher->dispatch(TmdbEvents::BEFORE_HYDRATION, $event);
if ($event->isPropagationStopped()) {
return $event->getSubject();
}
$subject... |
$event->setSubject($subject);
// Possibility to cache the data
$eventDispatcher->dispatch(TmdbEvents::AFTER_HYDRATION, $event);
return $event->getSubject();
} | csn_ccr |
Visualize water bridges. | def show_wbridges(self):
"""Visualize water bridges."""
for bridge in self.plcomplex.waterbridges:
if bridge.protisdon:
cmd.select('HBondDonor-P', 'HBondDonor-P or (id %i & %s)' % (bridge.don_id, self.protname))
cmd.select('HBondAccept-L', 'HBondAccept-L or (i... | csn |
function(property, value) {
var values = [];
for (var i in this._nodes) {
if (this._nodes.hasOwnProperty(i)) {
var n = this._nodes[i];
if ((property in n && n[property] == value) || (n.data && value == n.data[property])) {
| values.push(n);
}
}
}
return (values.length) ? values : null;
} | csn_ccr |
def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it e... | inv_square_root = self.R_square_root[ind]
else:
(U, S, Vh) = sp.linalg.svd(R, full_matrices=False,
compute_uv=True,
overwrite_a=False,
... | csn_ccr |
public function codeList($conditions = []) {
$conditions += ['status' => 1];
$res = $this->find('all', ['conditions' => | $conditions, 'fields' => ['code', 'name']]);
$ret = [];
foreach ($res as $language) {
$ret[$language['code']] = $language['name'];
}
return $ret;
} | csn_ccr |
func RetryAfter(attempts int, callback func() error, d time.Duration) (err error) {
m := MultiError{}
for i := 0; i < attempts; i++ {
if i > 0 {
glog.V(1).Infof("retry loop %d", i)
}
err = callback()
if err == nil {
return nil
}
m.Collect(err)
if _, ok := err.(*RetriableError); !ok {
| glog.Infof("non-retriable error: %v", err)
return m.ToError()
}
glog.V(2).Infof("error: %v - sleeping %s", err, d)
time.Sleep(d)
}
return m.ToError()
} | csn_ccr |
public ServerList filterOutObservers()
{
Iterable<ServerSpec> filtered = Iterables.filter
(
specs,
new Predicate<ServerSpec>()
{
@Override
public boolean apply(ServerSpec spec)
{
| return spec.getServerType() != ServerType.OBSERVER;
}
}
);
return new ServerList(Lists.newArrayList(filtered));
} | csn_ccr |
This is another problem about Indraneel's library. His library has one long shelf. His books are numbered and he identifies the books by their number. Each book has a distinct number.
He has lost many books, since many of his friends borrow his books and never bother to return them. He does not want to lose any more bo... | def bookList():
numBooks=int(input())
bookNum=[int(x) for x in input().split()]
takenBooks=int(input())
for i in range(takenBooks):
takenBookPos=(int(input()))
a=bookNum[takenBookPos-1]
print(a)
bookNum.remove(a)
bookList()
| apps |
public function onComponentAddedOrRemoved(Kwf_Component_Event_Component_Abstract $event)
{
$cacheId = 'procI-'.$event->component->getPageOrRoot()->componentId;
Kwf_Cache_Simple::delete($cacheId);
$log = Kwf_Events_Log::getInstance();
if ($log) {
| $log->log("processInput cache clear componentId=".$event->component->getPageOrRoot()->componentId, Zend_Log::INFO);
}
} | csn_ccr |
// Size is the number of m stored. | func (it *Resolver) Size() (int64, bool) {
return int64(len(it.order)), true
} | csn |
Updates an existing project wiki page. The user must have permission to change an existing wiki page.
<pre><code>GitLab Endpoint: PUT /projects/:id/wikis/:slug</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param slug the slug of the project's wiki pa... | public WikiPage updatePage(Object projectIdOrPath, String slug, String title, String content) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title)
.withParam("slug", slug, true)
.withParam("content", content);
... | csn |
Search through the record list for one matching the provided path.
@param string $path
@param \Illuminate\Database\Eloquent\Collection $existing_media
@return \Plank\Mediable\Media|null | protected function getRecordForFile($path, $existing_media)
{
$directory = File::cleanDirname($path);
$filename = pathinfo($path, PATHINFO_FILENAME);
$extension = pathinfo($path, PATHINFO_EXTENSION);
return $existing_media->filter(function (Media $media) use ($directory, $filename, ... | csn |
private final ValueNode registerFinalValue(int value) {
// We always register final values because while ADDING
// we do not know yet whether we will build fast or small.
lookupFinalValueNode.setFinalValue(value);
Node oldNode=nodes.get(lookupFinalValueNode);
if(oldNode!=null) {
... | ValueNode newNode=new ValueNode(value);
// If put() returns a non-null value from an equivalent, previously
// registered node, then get() failed to find that and we will leak newNode.
oldNode=nodes.put(newNode, newNode);
assert(oldNode==null);
return newNode;
} | csn_ccr |
// ByLastmod sorts the Pages by the last modification date and returns a copy.
//
// Adjacent invocations on the same receiver will return a cached result.
//
// This may safely be executed in parallel. | func (p Pages) ByLastmod() Pages {
const key = "pageSort.ByLastmod"
date := func(p1, p2 Page) bool {
return p1.Lastmod().Unix() < p2.Lastmod().Unix()
}
pages, _ := spc.get(key, pageBy(date).Sort, p)
return pages
} | csn |
Apply the product operator to a set of variables.
This uses the python itertools.product iterator to combine multiple variables
such that all possible combinations are generated. This is the default iterator
however this is a method of manually specifying the option.
Args:
variables: The varia... | def iterator_product(variables: VarType, parent: str = None) -> Iterable[VarMatrix]:
"""Apply the product operator to a set of variables.
This uses the python itertools.product iterator to combine multiple variables
such that all possible combinations are generated. This is the default iterator
however... | csn |
python how to modify all field names | def es_field_sort(fld_name):
""" Used with lambda to sort fields """
parts = fld_name.split(".")
if "_" not in parts[-1]:
parts[-1] = "_" + parts[-1]
return ".".join(parts) | cosqa |
If the resource has ordered child types, those child types will be stored in the attachment. If there are no
ordered child types, this method is a no-op.
@param resourceAddress the address of the resource
@param resource the resource which may or may not have ordered children. | public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {
Set<String> orderedChildTypes = resource.getOrderedChildTypes();
if (orderedChildTypes.size() > 0) {
orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());
}
} | csn |
public static function isValid($slot)
{
switch (strtolower($slot)) {
case self::STAGING:
case self::PRODUCTION:
| return true;
default:
return false;
}
} | csn_ccr |
func NewMultiPointFlat(layout Layout, flatCoords []float64) *MultiPoint {
g := new(MultiPoint)
g.layout = layout
| g.stride = layout.Stride()
g.flatCoords = flatCoords
return g
} | csn_ccr |
protected function prepareOrderComponentsCheckout($calculated)
{
$component_types = $this->order->getComponentTypes();
$components = array();
foreach ($calculated['components'] as $type => $component) {
$components[$type] = array(
'price' => $component['price'],... | 'price_formatted' => $this->price->format($component['price'], $calculated['currency'])
);
if (empty($component['rule'])) {
$components[$type]['name'] = $component_types[$type];
continue;
}
$components[$type]['rule'] = $co... | csn_ccr |
Parse a RFC822-formatted datetime string and return a datetime object.
Use dateutil's parser if possible.
https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime | def from_rfc(datestring, use_dateutil=True):
"""Parse a RFC822-formatted datetime string and return a datetime object.
Use dateutil's parser if possible.
https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime
"""
# Use dateutil's parser if possible
... | csn |
Return the count of new notifications.
@return string | protected function _actionGetcount(AnCommandContext $context)
{
$count = $this->actor->numOfNewNotifications();
return $this->getView()->newNotifications($count)->display();
} | csn |
public function getInTableColumns($postType)
{
$inTableColumnsSlugs = [];
$fields = PostType::getFields($postType);
// default columns
foreach(Post::$defaultListColumns as $key => $label){
if(substr($label, 0, 2) == '__') {
$label = __(substr($label, 2));... | }
// custom events columns
$customListColumms = Event::fire('post:table_list_columns', [$postType]);
foreach($customListColumms as $customList){
if(is_array($customList)) {
foreach ($customList as $key => $value) {
$inTableColumnsSlugs[$key] = ... | csn_ccr |
public static Map<String, String> tags(Tags tags) {
return tags.stream()
.map(WavefrontStrings::createTagEntry)
.flatMap(opt -> opt.map(Stream::of).orElseGet(Stream::empty))
| .map(WavefrontStrings::maybeTruncateTagEntry)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} | csn_ccr |
func (c *Client) Packages() ([]Package, error) {
stdout, stderr, err := c.execNpm("list", "--json", "--depth=0")
if err != nil {
return nil, errors.New(stderr)
}
var response map[string]map[string]Package
if err := json.Unmarshal([]byte(stdout), &response); err != nil {
return nil, errors.New(stderr)
}
| packages := make([]Package, 0, len(response["dependencies"]))
for name, p := range response["dependencies"] {
p.Name = name
packages = append(packages, p)
}
return packages, nil
} | csn_ccr |
func ParseDistanceUnit(u string) (float64, error) {
for _, unit := range distanceUnits {
for _, unitSuffix := | range unit.suffixes {
if u == unitSuffix {
return unit.conv, nil
}
}
}
return 0, fmt.Errorf("unknown distance unit: %s", u)
} | csn_ccr |
def to_xml_string(str = '')
super(str) do
str << '<c:pie3DChart>'
str << ('<c:varyColors val="' << vary_colors.to_s << '"/>')
@series.each { |ser| ser.to_xml_string(str) }
| d_lbls.to_xml_string(str) if @d_lbls
str << '</c:pie3DChart>'
end
end | csn_ccr |
def filter_decimal(string, default=None, lower=None, upper=None):
"""Return the input decimal number, or the default."""
try:
d = decimal.Decimal(string)
if lower is not None and d < lower:
raise InvalidInputError("value too small")
if upper is not None and d >= upper:
... | return d
except decimal.InvalidOperation:
if not string and default is not None:
# empty string, default was given
return default
else:
raise InvalidInputError("invalid decimal number") | csn_ccr |
Get an array attribute or return an empty array if it is not set.
@param string $key
@return array | protected function getArrayAttributeByKey($key)
{
return isset($this->attributes[$key]) ?
$this->fromJson($this->attributes[$key]) : [];
} | csn |
# Task
Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case.
# Input/Output
`[input]` string `s`
String of odd length consisting of English letters.
3 ≤ inputString.length ≤ 99.
`[output]` a string
The resulting... | def case_unification(s):
return s.lower() if sum(1 for i in s if i.islower()) > sum(1 for i in s if i.isupper()) else s.upper() | apps |
Send message method.
@param string $subject
@param string $content
@param string|array $to
@param string $fromName
@param string $fromEmail
@return array | public function send($subject, $content, $to, $fromName = '', $fromEmail = '')
{
$mail = new CakeEmail();
$fromName = ($fromName !== '') ? $fromName : $this->_fromName;
$fromEmail = ($fromEmail !== '') ? $fromEmail : $this->_fromEmail;
$transport = new MailTransport();
... | csn |
Asks for a list of all subscribed accounts and devices, along with their statuses. | def list_subscriptions(self, service):
"""Asks for a list of all subscribed accounts and devices, along with their statuses."""
data = {
'service': service,
}
return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header) | csn |
public function getReportId($i = 0){
if (!isset($this->reportList)){
return false;
| }
if (is_int($i)){
return $this->reportList[$i]['ReportId'];
} else {
return false;
}
} | csn_ccr |
// ifaceFlushVLANs removes all VLAN interfaces from the given physical
// interface. | func ifaceFlushVLANs(iface *net.Interface) error {
if err := validateInterface(iface); err != nil {
return err
}
vlanIfaces, err := vlanInterfaces(iface)
if err != nil {
return err
}
for _, vlanIface := range vlanIfaces {
if err := ipRunIface(vlanIface, "link del dev %s", vlanIface.Name); err != nil {
re... | csn |
Get self with given issuer.
@param Name $issuer
@return self | public function withIssuer(Name $issuer): self
{
$obj = clone $this;
$obj->_issuer = $issuer;
return $obj;
} | csn |
// Deletes traffic type of a physical network | func (s *UsageService) DeleteTrafficType(p *DeleteTrafficTypeParams) (*DeleteTrafficTypeResponse, error) {
resp, err := s.cs.newRequest("deleteTrafficType", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteTrafficTypeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
... | csn |
how to determine the index of a specific value in python | def get_list_index(lst, index_or_name):
"""
Return the index of an element in the list.
Args:
lst (list): The list.
index_or_name (int or str): The value of the reference element, or directly its numeric index.
Returns:
(int) The index of the element in the list.
"""
if... | cosqa |
final public int[] readInputRegisters(int serverAddress, int startAddress, int quantity) throws
ModbusProtocolException, ModbusNumberException, ModbusIOException {
| ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadInputRegisters(serverAddress, startAddress, quantity);
ReadHoldingRegistersResponse response = (ReadInputRegistersResponse) processRequest(request);
return response.getRegisters();
} | csn_ccr |
// GetMetadata returns a single metadata entry associated with an instance. | func (c *InstancesClient) GetMetadata(ctx context.Context, input *GetMetadataInput) (string, error) {
if input.Key == "" {
return "", fmt.Errorf("Missing metadata Key from input: %s", input.Key)
}
fullPath := path.Join("/", c.client.AccountName, "machines", input.ID, "metadata", input.Key)
reqInputs := client.Re... | csn |
get a reference to the Zend_Amf_response instance
@return Zend_Amf_Server_Response | public function getResponse()
{
if (null === ($response = $this->_response)) {
require_once 'Zend/Amf/Response/Http.php';
$this->setResponse(new Zend_Amf_Response_Http());
}
return $this->_response;
} | csn |
public function currentPath()
{
$requestURI = $this->serverVar('REQUEST_URI');
$sciptName = $this->serverVar('SCRIPT_NAME');
| return rtrim(parse_url($requestURI? : $sciptName, PHP_URL_PATH), '/');
} | csn_ccr |
Sorts by date. | function compare(a, b) {
var date1 = new Date(a.date);
var date2 = new Date(b.date);
if (date1 < date2) {
return -1;
}
if (date1 > date2) {
return 1;
}
return 0;
} | csn |
public function deleteProfile( CustomerVault\Profile $profile )
{
$profile->setRequiredFields(array('id'));
$profile->checkRequiredFields();
$request = new Request(array(
'method' => Request::DELETE,
| 'uri' => $this->prepareURI("/profiles/" . $profile->id)
));
$this->client->processRequest($request);
return true;
} | csn_ccr |
protected File createTempDir(String namePrefix) {
final File tempDir = new File(getTempDirectory(), namePrefix);
cleanFolder(tempDir, ACCEPT_ALL_FILTER, true, true);
if (!tempDir.mkdirs()) {
| throw new RuntimeException(MessageFormat.format(Messages.SarlBatchCompiler_8, tempDir.getAbsolutePath()));
}
this.tempFolders.add(tempDir);
return tempDir;
} | csn_ccr |
Finds a particular node in the open sections
@param *array $open The open nodes
@param string $name The last name of the node we are looking for
@return int The index where the section is found | protected function findSection(array $open, $name = self::LAST_OPEN)
{
foreach ($open as $i => $item) {
$item = explode(' ', $item['value']);
if ($item[0] === $name) {
return $i;
}
}
if ($name == self::LAST_OPEN) {
return $i;
... | csn |
early stopping use keras lstm in python | def lmx_h1k_f64k():
"""HParams for training languagemodel_lm1b32k_packed. 880M Params."""
hparams = lmx_base()
hparams.hidden_size = 1024
hparams.filter_size = 65536
hparams.batch_size = 2048
return hparams | cosqa |
def IsRegistryStatEntry(self, original_result):
"""Checks if given RDFValue is | a registry StatEntry."""
return (original_result.pathspec.pathtype ==
rdf_paths.PathSpec.PathType.REGISTRY) | csn_ccr |
public Object setConnectionProperty(String name, String value) {
| return connProperties.setProperty(name, value);
} | csn_ccr |
use product of one funtion in another python | def multiply(traj):
"""Sophisticated simulation of multiplication"""
z=traj.x*traj.y
traj.f_add_result('z',z=z, comment='I am the product of two reals!') | cosqa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.