comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Process the directory of JSON files using the collected pattern ids
@param string[] $coveredIds | public function process(array $coveredIds) : void
{
$this->setCoveredPatternIds($coveredIds);
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->i... |
Gets the rdns String name
:param rdns: RDNS object
:type rdns: cryptography.x509.RelativeDistinguishedName
:return: RDNS name | def get_rdns_name(rdns):
name = ''
for rdn in rdns:
for attr in rdn._attributes:
if len(name) > 0:
name = name + ','
if attr.oid in OID_NAMES:
name = name + OID_NAMES[attr.oid]
else:
name = name + attr.oid._name
... |
// MountHealthController "mounts" a Health resource controller on the given service. | func MountHealthController(service *goa.Service, ctrl HealthController) {
initService(service)
var h goa.Handler
service.Mux.Handle("OPTIONS", "/cellar/_ah/health", ctrl.MuxHandler("preflight", handleHealthOrigin(cors.HandlePreflight()), nil))
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request... |
// SendAudioWithKeyboardHide send a audio with explicit Keyboard Hide. | func (bot TgBot) SendAudioWithKeyboardHide(cid int, audio string, duration *int, performer *string, title *string, rmi *int, rm ReplyKeyboardHide) ResultWithMessage {
var rkm ReplyMarkupInt = rm
return bot.SendAudio(cid, audio, duration, performer, title, rmi, &rkm)
} |
<p>
set data-* attribute
</p>
<pre>
Div div = new Div();
div.setData("foo", "bar");
// you get <div data-foo="bar"></div>
</pre>
@param key
data-"key" | public void setData(String key, String value) {
QName qn = new QName("data-" + key);
this.getOtherAttributes().put(qn, value);
} |
Unserialize an embedded collection
Return a collection of serialized objects (arrays)
@param MapperInterface $mapper
@param array $data
@return array | protected function unserializeEmbeddedCollection(MapperInterface $mapper, array $data)
{
$collection = array();
foreach ($data as $document) {
$collection[] = $mapper->unserialize($document);
}
return $collection;
} |
stops the timer with a given name.
:param name: the name of the timer
:type name: string | def stop(cls, name):
cls.timer_end[name] = time.time()
if cls.debug:
print("Timer", name, "stopped ...") |
Gets an object using a from clause.
@param type The type of the desired object.
@param clause The WHERE clause.
@param args The arguments for the WHERE clause.
@param <T> The type of the object.
@return The object or {@code null} | public static <T> T objectFromClause(Class<T> type, String clause, Object... args)
{
return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args));
} |
pickedPage można podać wcześniej przy konstruktorze
@param int $pickedPage
@return SqlPaginateParams | public function getSqlPaginateParams($pickedPage = false) {
$p = new SqlPaginateParams();
if ($pickedPage) {
$this->pickedPage = $pickedPage;
}
if ($this->pages == 0) {
$p->setOffset(0);
$p->setLimit(20);
return $p;
}
... |
Query for intersections of terms in two lists
Return a list of intersection result objects with keys:
- x : term from x
- y : term from y
- c : count of intersection
- j : jaccard score | def query_intersections(self, x_terms=None, y_terms=None, symmetric=False):
if x_terms is None:
x_terms = []
if y_terms is None:
y_terms = []
xset = set(x_terms)
yset = set(y_terms)
zset = xset.union(yset)
# first built map of gene->termC... |
readFile fs promise wrapped
@param {string} path
@param {string} fileName | function readFile(path, fileName) {
return new Promise((resolve, reject) => {
fs.readFile(`${path}/${fileName}`, 'utf8', (err, content) => {
if (err) {
return reject(err)
}
return resolve(content)
})
})
} |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitBuildSource. | func (in *GitBuildSource) DeepCopy() *GitBuildSource {
if in == nil {
return nil
}
out := new(GitBuildSource)
in.DeepCopyInto(out)
return out
} |
:sockets:: socket list
:clean:: clean UTF8 strings or provide block to run on every read string
:pool:: ActionPool to use
Creates a new watcher for sockets
start the watcher | def start
if(@sockets.size < 0)
raise 'No sockets available for listening'
elsif(!@runner.nil? && @runner.alive?)
raise AlreadyRunning.new
else
@stop = false
@runner = Thread.new{watch}
end
end |
Registers action aliases for current task
@param array $map Alias-to-filename hash array | public function register_action_map($map)
{
if (is_array($map)) {
foreach ($map as $idx => $val) {
$this->action_map[$idx] = $val;
}
}
} |
Create permission request
The call is idempotent; that is, if one posts the same pos_id and
pos_tid twice, only one Permission request is created. | def create_permission_request(self, customer, pos_id, pos_tid, scope,
ledger=None, text=None, callback_uri=None,
expires_in=None):
arguments = {'customer': customer,
'pos_id': pos_id,
'pos_tid'... |
// readv returns the tokens starting from the current position until the first
// match of t. A match is made only of t.typ and t.val are equal to the examined
// token. | func (p *parser) readv(t token) ([]token, error) {
var tokens []token
for {
read, err := p.readt(t.typ)
tokens = append(tokens, read...)
if err != nil {
return tokens, err
}
if len(read) > 0 && read[len(read)-1].val == t.val {
break
}
}
return tokens, nil
} |
Retrieve the pattern for the given package.
@param \Composer\Package\PackageInterface $package
@return string | public function getPattern(PackageInterface $package)
{
if (isset($this->packages[$package->getName()])) {
return $this->packages[$package->getName()];
} elseif (isset($this->packages[$package->getPrettyName()])) {
return $this->packages[$package->getPrettyName()];
} ... |
Add all the components to this calendar panel.
@param dateTarget This date needs to be in the calendar. | public void layoutCalendar(Date timeTarget)
{
calendar.setTime(timeTarget);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
String[] array = new String[24 * 2];
calendar.set(Calendar.HOUR_OF_DAY, 0);
... |
/* [MS-OSHARED] 2.3.3.1.4 Lpstr | function parse_lpstr(blob, type, pad) {
var start = blob.l;
var str = blob.read_shift(0, 'lpstr-cp');
if(pad) while((blob.l - start) & 3) ++blob.l;
return str;
} |
Validate this measurement and update its 'outcome' field. | def validate(self):
""""""
# PASS if all our validators return True, otherwise FAIL.
try:
if all(v(self.measured_value.value) for v in self.validators):
self.outcome = Outcome.PASS
else:
self.outcome = Outcome.FAIL
return self
except Exception as e: # pylint: disable=b... |
This method gets the singleton instance of this {@link CollectionReflectionUtilImpl}. <br>
<b>ATTENTION:</b><br>
Please prefer dependency-injection instead of using this method.
@return the singleton instance. | public static CollectionReflectionUtilImpl getInstance() {
if (instance == null) {
synchronized (CollectionReflectionUtilImpl.class) {
if (instance == null) {
CollectionReflectionUtilImpl util = new CollectionReflectionUtilImpl();
util.initialize();
instance = util;
... |
Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request.
@param server a RestExpress server instance. | private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController)
{
RouteBuilder rb;
for (String pattern : methodsByPattern.keySet())
{
rb = server.uri(pattern, corsOptionsController)
.action("options", HttpMethod.OPTIONS)
.noSerializ... |
/*
String[] validTypes = new String[]
{ "application/xhtml+xml",
"application/x-dtbncx+xml", "text/css" }; | void buildCSSTypesDictionary()
{
String description;
String value;
TextSearchDictionaryEntry de;
//search eval() expression
description = "text/css";
value = "text/css";
de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009);
v.add(de);
} |
// TODO: This is hacky. Look into using a library like gojsonpointer[1] instead.
//
// [1] https://github.com/xeipuuv/gojsonpointer | func (s *Schema) refToSchema(str string, rootSchema Schema, loadExternal bool) (*Schema, error) {
parentURL, err := url.Parse(s.parentId)
if err == nil && parentURL.IsAbs() {
sURL, err := url.Parse(str)
if err == nil && !sURL.IsAbs() && !strings.HasPrefix(str, "#") {
str = parentURL.ResolveReference(sURL).Stri... |
// Load loads data from Dump. If the input is not the same as the output from Dump() then it will return a error. | func (s *AtomicSequence) Load(data []byte) error {
if s.initialized {
return errors.New("cannot load into an initialized sequence")
}
vals := make(map[string]uint64)
if err := json.Unmarshal(data, &vals); err != nil {
return err
}
if val, ok := vals["current"]; !ok {
return errors.New("improperly formatte... |
Exports one instance of custom field data
@param data_controller $data
@param array $subcontext subcontext to pass to content_writer::export_data | public static function export_customfield_data(data_controller $data, array $subcontext) {
$context = $data->get_context();
$exportdata = $data->to_record();
$exportdata->fieldtype = $data->get_field()->get('type');
$exportdata->fieldshortname = $data->get_field()->get('shortname');
... |
Unlock the account.
:param account: Account
:return: | def unlock_account(account):
return Web3Provider.get_web3().personal.unlockAccount(account.address, account.password) |
Set button as HTML link object <a href="">.
@param string $page
@param array $args
@return $this | public function link($page, $args = array())
{
$this->setElement('a');
$this->setAttr('href', $this->app->url($page, $args));
return $this;
} |
// connect connects to the SSH server, unless a AuthMethod was set with
// SetAuth method, by default uses an auth method based on PublicKeysCallback,
// it connects to a SSH agent, using the address stored in the SSH_AUTH_SOCK
// environment var. | func (c *command) connect() error {
if c.connected {
return transport.ErrAlreadyConnected
}
if c.auth == nil {
if err := c.setAuthFromEndpoint(); err != nil {
return err
}
}
var err error
config, err := c.auth.ClientConfig()
if err != nil {
return err
}
overrideConfig(c.config, config)
c.client... |
Helper method to actually perform the subdoc get count operation. | private Observable<DocumentFragment<Lookup>> getCountIn(final String id, final LookupSpec spec,
final long timeout, final TimeUnit timeUnit) {
return Observable.defer(new Func0<Observable<DocumentFragment<Lookup>>>() {
@Override
public Observable<DocumentFragment<Lookup>> call() ... |
The method prints the structure of all meta_signal-notifications as log-messages. | def observe_meta_signal_changes(self, changed_model, prop_name, info):
"
self.logger.info(NotificationOverview(info)) |
Clear element ID list in cache | protected function clearIDList()
{
$arCacheTags = $this->getCacheTagList();
$sCacheKey = $this->getCacheKey();
CCache::clear($arCacheTags, $sCacheKey);
} |
Gets a Site Role by his Id.
@param mixed $nb_site_role A CNabuDataObject containing a field named nb_role_id or a valid Id.
@return CNabuSiteRole|bool Returns the Site Role instance if exists or false if not. | public function getSiteRole($nb_site_role)
{
if (is_numeric($nb_role_id = nb_getMixedValue($nb_site_role, NABU_ROLE_FIELD_ID))) {
$retval = $this->getSiteRoles()->getItem($nb_role_id);
} else {
$retval = false;
}
return $retval;
} |
Move partition to under-loaded replication-group if possible. | def move_partition_replica(self, under_loaded_rg, eligible_partition):
""""""
# Evaluate possible source and destination-broker
source_broker, dest_broker = self._get_eligible_broker_pair(
under_loaded_rg,
eligible_partition,
)
if source_broker and dest_br... |
Set the value of Hash / hash
@param $value string
@return User | public function setHash(string $value) : User
{
if ($this->data['hash'] !== $value) {
$this->data['hash'] = $value;
$this->setModified('hash');
}
return $this;
} |
// Create the next block to propose and return it.
// We really only need to return the parts, but the block
// is returned for convenience so we can log the proposal block.
// Returns nil block upon error.
// NOTE: keep it side-effect free for clarity. | func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
var commit *types.Commit
if cs.Height == 1 {
// We're creating a proposal for the first block.
// The commit is empty, but not nil.
commit = types.NewCommit(types.BlockID{}, nil)
} else if cs.LastCommit.HasTwoThir... |
Write an item to the cache for a given number of minutes.
@param string $key
@param mixed $value
@param int $minutes | public function put($key, $value, $minutes)
{
$this->forever($key, $value);
$this->redis->expire($key, $minutes * 60);
} |
Component factory. Delegates the creation of components to a createComponent<Name> method.
@param string $name | protected function createComponent($name): ?IComponent
{
$method = 'createComponent'.ucfirst($name);
if (method_exists($this, $method)) {
$this->checkRequirements(self::getReflection()->getMethod($method));
}
return parent::createComponent($name);
} |
get schema info
@param Request $request request
@return Response | public function schemaAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint']));
$schema = $t... |
// Run all jobs with delay seconds | func (s *Scheduler) RunAllwithDelay(d int) {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
time.Sleep(time.Duration(d))
}
} |
Get the string representation of the full path name
@param parent the parent path
@return the full path in string | final public String getFullName(final String parent) {
if (isEmptyLocalName()) {
return parent;
}
StringBuilder fullName = new StringBuilder(parent);
if (!parent.endsWith(Path.SEPARATOR)) {
fullName.append(Path.SEPARATOR);
}
fullName.append(getLocalName());
return fullName.t... |
Extracts all files from the "master" language and takes them as translation groups.
@param string $lang
@return void | private function getTranslationGroups($lang = 'en'): void
{
$dir = resource_path('lang/'. $lang . '/');
$files = array_diff(scandir($dir), array('..', '.'));
foreach($files as $index => $filename){
$groupname = str_replace(".php", "", $filename);
$this->updateTransla... |
Check if a route is localized in a given language
@param string $name
@param string $lang
@return bool | function isLocalized($name,$lang=NULL) {
if (!isset($lang))
$lang=$this->current;
return !$this->isGlobal($name) && array_key_exists($name,$this->_aliases) &&
(!isset($this->rules[$lang][$name]) || $this->rules[$lang][$name]!==FALSE);
} |
Apply the include and exclude filters to those files in *unmatched*,
moving those that are included, but not excluded, into the *matched*
set.
Both *matched* and *unmatched* are sets of unqualified file names. | def match_files(self, matched, unmatched):
""""""
for pattern in self.iter():
pattern.match_files(matched, unmatched)
if not unmatched:
# Optimization: If we have matched all files already
# simply return at this point - nothing else to do
... |
// NewOTP takes a new key, a starting time, a step, the number of
// digits of output (typically 6 or 8) and the hash algorithm to
// use, and builds a new OTP. | func NewTOTP(key []byte, start uint64, step uint64, digits int, algo crypto.Hash) *TOTP {
h := hashFromAlgo(algo)
if h == nil {
return nil
}
return &TOTP{
OATH: &OATH{
key: key,
counter: start,
size: digits,
hash: h,
algo: algo,
},
step: step,
}
} |
返回对应的termin root path(不依赖对应的config信息) | public static String getTerminRoot(Long channelId, Long pipelineId) {
// 根据channelId , pipelineId构造path
return MessageFormat.format(ArbitrateConstants.NODE_TERMIN_ROOT,
String.valueOf(channelId),
String.valueOf(pipelineId));
} |
Parses a Disgenet file ad the one that can be downloaded from
http://www.disgenet.org/ds/DisGeNET/results/all_gene_disease_associations.tar.gz and writes corresponding json
objects. | public void parse() {
Map<String, Disgenet> disgenetMap = new HashMap<>();
BufferedReader reader;
try {
// Disgenet file is usually downloaded as a .tar.gz file
if (disgenetFilePath.toFile().getName().endsWith("tar.gz")) {
TarArchiveInputStream tarInput =... |
@param $postId
@param bool $form
@return Response | public function addCommentFormAction($postId, $form = false)
{
$action = $this->container->get(CreateCommentFormAction::class);
return $action($postId, $form);
} |
// State returns the monitor status. | func (nm *NodeMonitor) State() *models.MonitorStatus {
nm.Mutex.RLock()
state := nm.state
nm.Mutex.RUnlock()
return state
} |
Solve A*X = b
@param b A column vector with as many rows as A.
@return X so that L*L^T*X = b
@exception IllegalArgumentException Matrix row dimensions must agree.
@exception RuntimeException Matrix is not symmetric positive definite. | public double[] solve(double[] b) {
if(b.length != L.length) {
throw new IllegalArgumentException(ERR_MATRIX_DIMENSIONS);
}
if(!isspd) {
throw new ArithmeticException(ERR_MATRIX_NOT_SPD);
}
// Work on a copy!
return solveLtransposed(solveLInplace(copy(b)));
} |
Get all running (unfinished) flows from database. {@inheritDoc} | @Override
public List<ExecutableFlow> getRunningFlows() {
final ArrayList<ExecutableFlow> flows = new ArrayList<>();
try {
getFlowsHelper(flows, this.executorLoader.fetchUnfinishedFlows().values());
} catch (final ExecutorManagerException e) {
logger.error("Failed to get running flows.", e);
... |
Checks whether there is already an existing pending/in-progress data request for a user for a given request type.
@param int $userid The user ID.
@param int $type The request type.
@return bool
@throws coding_exception
@throws dml_exception | public static function has_ongoing_request($userid, $type) {
global $DB;
// Check if the user already has an incomplete data request of the same type.
$nonpendingstatuses = [
self::DATAREQUEST_STATUS_COMPLETE,
self::DATAREQUEST_STATUS_CANCELLED,
self::DATAREQ... |
// Prev returns the previous Page relative to the given Page in
// this weighted page set. | func (wp WeightedPages) Prev(cur Page) Page {
for x, c := range wp {
if c.Page == cur {
if x == 0 {
return wp[len(wp)-1].Page
}
return wp[x-1].Page
}
}
return nil
} |
Get available locales
@param string|null|true $domain If provided, locales for the given domain will be returned.
If true, then the current state domain will be used (if in domain mode).
@return ArrayList | public static function getLocales($domain = null)
{
// Optionally filter by domain
$domainObj = Domain::getByDomain($domain);
if ($domainObj) {
return $domainObj->getLocales();
}
return Locale::getCached();
} |
>>> p = Preso()
>>> z = p.to_file('/tmp/foo.odp')
>>> sorted(z.ls('/'))
['META-INF/manifest.xml', 'content.xml', 'meta.xml', 'mimetype', 'settings.xml', 'styles.xml'] | def to_file(self, filename=None, write_style=True):
out = zipwrap.Zippier(filename, "w")
out.write("mimetype", self.mime_type)
for p in self._pictures:
out.write("Pictures/%s" % p.internal_name, p.get_data())
out.write("content.xml", self.to_xml())
if write_s... |
TODO
@param $config
@return bool | public function save($config)
{
if (!file_put_contents($this->filename, Yaml::dump($config))) {
return false;
}
return true;
} |
A decorator for flags classes to forbid declaring flags with overlapping bits. | def unique_bits(flags_class):
flags_class = unique(flags_class)
other_bits = 0
for name, member in flags_class.__members_without_aliases__.items():
bits = int(member)
if other_bits & bits:
for other_name, other_member in flags_class.__members_without_aliases__.items():
... |
Handles the optional labelling of the plot with relevant quantities
Args:
plt (plt): Plot of the locpot vs c axis
label_fontsize (float): Fontsize of labels
Returns Labelled plt | def get_labels(self, plt, label_fontsize=10):
# center of vacuum and bulk region
if len(self.slab_regions) > 1:
label_in_vac = (self.slab_regions[0][1] + self.slab_regions[1][0])/2
if abs(self.slab_regions[0][0]-self.slab_regions[0][1]) > \
abs(self.... |
is the host any of the registered URLs for this website? | public static function isHostKnownAliasHost($urlHost, $idSite)
{
$websiteData = Cache::getCacheWebsiteAttributes($idSite);
if (isset($websiteData['hosts'])) {
$canonicalHosts = array();
foreach ($websiteData['hosts'] as $host) {
$canonicalHosts[] = self::toCa... |
List server id and scripts file name | function list(scriptModule, agent, msg, cb) {
const servers = [];
const scripts = [];
const idMap = agent.idMap;
for (const sid in idMap) {
if (idMap.hasOwnProperty(sid)) {
servers.push(sid);
}
}
fs.readdir(scriptModule.root, (err, filenames) => {
if (err) {... |
Updates the commerce wish list item in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
@param commerceWishListItem the commerce wish list item
@return the commerce wish list item that was updated | public static com.liferay.commerce.wish.list.model.CommerceWishListItem updateCommerceWishListItem(
com.liferay.commerce.wish.list.model.CommerceWishListItem commerceWishListItem) {
return getService().updateCommerceWishListItem(commerceWishListItem);
} |
*
This method is used to clear KeyStore configurations when the entire config
is being reloaded.
* | public void clearKSMap() {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Clearing keystore maps");
synchronized (keyStoreMap) {
keyStoreMap.clear();
}
} |
// List runs the list action. | func (c *SpaceController) List(ctx *app.ListSpaceContext) error {
_, err := login.ContextIdentity(ctx)
if err != nil {
return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error()))
}
offset, limit := computePagingLimits(ctx.PageOffset, ctx.PageLimit)
var response app.SpaceList
txnErr := application.T... |
// add inserts or updates "r" in the cache for the replica with the key "r.Key". | func (c *replicationLagCache) add(r replicationLagRecord) {
if !r.Up {
// Tablet is down. Do no longer track it.
delete(c.entries, r.Key)
delete(c.ignoredSlowReplicasInARow, r.Key)
return
}
entry, ok := c.entries[r.Key]
if !ok {
entry = newReplicationLagHistory(c.historyCapacityPerReplica)
c.entries[r.... |
Run any git command, like "status" or "checkout -b mybranch origin/mybranch"
@throws RuntimeException
@param string $commandString
@return string $output | public function git($commandString)
{
// clean commands that begin with "git "
$commandString = preg_replace('/^git\s/', '', $commandString);
$commandString = $this->options['git_executable'].' '.$commandString;
$command = new $this->options['command_class']($this->dir, $commandStr... |
can lead to classcastexception if comparator is not of the right type | @SuppressWarnings("unchecked")
public <T> void sort(Arr arr, Comparator<T> c) {
int l = arr.getLength();
Object[] objs = new Object[l];
for (int i=0; i<l; i++) {
objs[i] = arr.get(i);
}
Arrays.sort((T[])objs, c);
for (int i=0; i<l; i++) {
arr.put(i, objs[i]);
}
} |
Create a new cell at the specified coordinate
@param string $pCoordinate Coordinate of the cell
@return PHPExcel_Cell Cell that was created | private function _createNewCell($pCoordinate)
{
$cell = $this->_cellCollection->addCacheData(
$pCoordinate,
new PHPExcel_Cell(
NULL,
PHPExcel_Cell_DataType::TYPE_NULL,
$this
)
);
$this->_cellCollectionIsSorted = false;
// Coordinates
$aCoordinates = PHPExcel_Cell::co... |
Determine if the browser is among the custom browser rules or not. Rules are checked in the order they were
added.
@access protected
@return boolean Returns true if we found the browser we were looking for in the custom rules, false otherwise. | protected function checkBrowserCustom()
{
foreach ($this->_customBrowserDetection as $browserName => $customBrowser) {
$uaNameToLookFor = $customBrowser['uaNameToLookFor'];
$isMobile = $customBrowser['isMobile'];
$isRobot = $customBrowser['isRobot'];
$separato... |
Find related object on the database and updates it with attributes in self, if it didn't
find it on database it creates a new one. | def convert(attribute="id")
klass = persistence_class
object = klass.where(attribute.to_sym => self.send(attribute)).first
object ||= persistence_class.new
attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) }
attributes.delete... |
Finish establishing section
Wrap up title node, but stick in the section node. Add the section names
based on all the text nodes added to the title. | def depart_heading(self, _):
assert isinstance(self.current_node, nodes.title)
# The title node has a tree of text nodes, use the whole thing to
# determine the section id and names
text = self.current_node.astext()
if self.translate_section_name:
text = self... |
верификация номер телефона
@return bool
@throws Exception | public function verifyPhone(): bool
{
$phone = new UserMetaPhone($this->notification_phone);
$phone->verifyPhone();
$this->notification_phone = $phone;
return $this->updateModel();
} |
Expert users can override this method for more complete control over the
execution of the Mapper.
@param context
@throws IOException | public void run(Context context) throws IOException, InterruptedException {
setup(context);
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
cleanup(context);
} |
Add a response to the list.
@param int $key
@param array|null $response | public function addResponse($key, array $response)
{
$originalRequest = isset($this->request[$key]) ? $this->request[$key] : null;
$responseBody = isset($response['body']) ? $response['body'] : null;
$responseError = isset($response['error']) ? $response['error'] : null;
$responseMet... |
Copy temporary project data to persistent storage.
@param string[] $with
@throws ReadException | private function updateStorage($with = [])
{
$data = array_merge($this->data, $with);
$this->fs->create($this->fsPath, json_encode($data));
} |
// drawCondFmtCellIs provides a function to create conditional formatting rule
// for cell value (include between, not between, equal, not equal, greater
// than and less than) by given priority, criteria type and format settings. | func drawCondFmtCellIs(p int, ct string, format *formatConditional) *xlsxCfRule {
c := &xlsxCfRule{
Priority: p + 1,
Type: validType[format.Type],
Operator: ct,
DxfID: &format.Format,
}
// "between" and "not between" criteria require 2 values.
_, ok := map[string]bool{"between": true, "notBetween": t... |
Trims every string in the specified strings array.
@param strings the specified strings array, returns {@code null} if the
specified strings is {@code null}
@return a trimmed strings array | public static String[] trimAll(final String[] strings) {
if (null == strings) {
return null;
}
return Arrays.stream(strings).map(StringUtils::trim).toArray(size -> new String[size]);
} |
Sobel method to generate bump map from a height map
@param input - A height map
@return bump map | @Override
public ImageSource apply(ImageSource input) {
int w = input.getWidth();
int h = input.getHeight();
MatrixSource output = new MatrixSource(input);
Vector3 n = new Vector3(0, 0, 1);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
... |
Modify the inner parameters of the Kepler propagator in order to place
the spacecraft in the right Sphere of Influence | def _change_soi(self, body):
if body == self.central:
self.bodies = [self.central]
self.step = self.central_step
self.active = self.central.name
self.frame = self.central.name
else:
soi = self.SOI[body.name]
self.bodies = ... |
Creates the signed license at the defined output path
@throws BuildException
@return void | protected function generateLicense()
{
$command = $this->prepareSignCommand() . ' 2>&1';
$this->log('Creating license at ' . $this->outputFile);
$this->log('Running: ' . $command, Project::MSG_VERBOSE);
$tmp = exec($command, $output, $return_var);
// Check for exit value 1... |
Indicates whether activity is for compensation.
@return true if this activity is for compensation. | public boolean isCompensationHandler() {
Boolean isForCompensation = (Boolean) getProperty(BpmnParse.PROPERTYNAME_IS_FOR_COMPENSATION);
return Boolean.TRUE.equals(isForCompensation);
} |
@param array $elements
@return \marvin255\serviform\interfaces\HasChildren | public function setElements(array $elements)
{
$this->elements = [];
foreach ($elements as $name => $element) {
$this->setElement($name, $element);
}
return $this;
} |
Sets which partial view script to use for rendering tweets
@param string|array $partial
@return \UthandoTwitter\View\TweetFeed | public function setPartial($partial)
{
if (null === $partial || is_string($partial) || is_array($partial)) {
$this->partial = $partial;
}
return $this;
} |
Add migrations to be applied.
Args:
migrations: a list of migrations to add of the form [(app, migration_name), ...]
Raises:
MigrationSessionError if called on a closed MigrationSession | def add_migrations(self, migrations):
if self.__closed:
raise MigrationSessionError("Can't change applied session")
self._to_apply.extend(migrations) |
Returns base basket price for payment cost calculations. Price depends on
payment setup (payment administration)
@param \OxidEsales\Eshop\Application\Model\Basket $oBasket oxBasket object
@return double | public function getBaseBasketPriceForPaymentCostCalc($oBasket)
{
$dBasketPrice = 0;
$iRules = $this->oxpayments__oxaddsumrules->value;
// products brutto price
if (!$iRules || ($iRules & self::PAYMENT_ADDSUMRULE_ALLGOODS)) {
$dBasketPrice += $oBasket->getProductsPrice()-... |
*********************************************************************************** | @Override
public boolean removeArc(int x, int y, ICause cause) throws ContradictionException {
assert cause != null;
if (LB.arcExists(x, y)) {
this.contradiction(cause, "remove mandatory arc " + x + "->" + y);
return false;
}
if (UB.removeArc(x, y)) {
if (reactOnModification) {
delta.add(x, GraphD... |
// GetAvatarURL gets the user's avatar URL. See http://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-client-r0-profile-userid-avatar-url | func (cli *Client) GetAvatarURL() (url string, err error) {
urlPath := cli.BuildURL("profile", cli.UserID, "avatar_url")
s := struct {
AvatarURL string `json:"avatar_url"`
}{}
_, err = cli.MakeRequest("GET", urlPath, nil, &s)
if err != nil {
return "", err
}
return s.AvatarURL, nil
} |
// ParseToRawMap takes the filename as a string and returns a RawMap. | func ParseToRawMap(fileName string) (cfg RawMap, err error) {
var file *os.File
cfg = make(RawMap, 0)
file, err = os.Open(fileName)
if err != nil {
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
var currentSection string
for scanner.Scan() {
line := scanner.Text()
if commentLine.MatchSt... |
Loops through the output buffer, flushing each, before emitting
the response.
@param int|null $maxBufferLevel Flush up to this buffer level.
@return void | protected function flush($maxBufferLevel = null)
{
if (null === $maxBufferLevel) {
$maxBufferLevel = ob_get_level();
}
while (ob_get_level() > $maxBufferLevel) {
ob_end_flush();
}
} |
Scalar multiplies each item with c
@param c | public void scalarMultiply(double c)
{
int m = rows;
int n = cols;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
consumer.set(i, j, c * supplier.get(i, j));
}
}
} |
allocateSpace(). | private void freeAllocatedSpace(java.util.Collection sortedFreeSpaceList)
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"freeAllocatedSpace",
new Object[] { new Integer(sortedFreeSp... |
Aligns the structures, duplicating ca2 regardless of
{@link CECPParameters.getDuplicationHint() param.getDuplicationHint}.
@param ca1
@param ca2
@param cpparams
@return
@throws StructureException | private AFPChain alignRight(Atom[] ca1, Atom[] ca2, CECPParameters cpparams)
throws StructureException {
long startTime = System.currentTimeMillis();
Atom[] ca2m = StructureTools.duplicateCA2(ca2);
if(debug) {
System.out.format("Duplicating ca2 took %s ms\n",System.currentTimeMillis()-startTime);
start... |
Checks if discount should be skipped for this article in basket. Returns true if yes.
@return bool | public function skipDiscounts()
{
// already loaded skip discounts config
if ($this->_blSkipDiscounts !== null) {
return $this->_blSkipDiscounts;
}
if ($this->oxarticles__oxskipdiscounts->value) {
return true;
}
$this->_blSkipDiscounts = fal... |
Returns the product of each numerical column or row.
Return:
A new QueryCompiler object with the product of each numerical column or row. | def prod(self, **kwargs):
if self._is_transposed:
kwargs["axis"] = kwargs.get("axis", 0) ^ 1
return self.transpose().prod(**kwargs)
return self._process_sum_prod(
self._build_mapreduce_func(pandas.DataFrame.prod, **kwargs), **kwargs
) |
Switches the corners of the Tiles between rounded and rectangular
@param ROUNDED | public void setRoundedCorners(final boolean ROUNDED) {
if (null == roundedCorners) {
_roundedCorners = ROUNDED;
fireTileEvent(REDRAW_EVENT);
} else {
roundedCorners.set(ROUNDED);
}
} |
Generates control's HTML element.
@return Html | public function getControl()
{
$control = parent::getControl();
$control->type = $this->htmlType;
$control->addClass($this->htmlType);
list($min, $max) = $this->extractRangeRule($this->getRules());
if ($min instanceof DateTimeInterface) {
$control->min = $min->format($this->htmlFormat);
}
if ($max in... |
// SetTimeoutInMinutesOverride sets the TimeoutInMinutesOverride field's value. | func (s *StartBuildInput) SetTimeoutInMinutesOverride(v int64) *StartBuildInput {
s.TimeoutInMinutesOverride = &v
return s
} |
Marshall the given parameter object. | public void marshall(MethodSnapshot methodSnapshot, ProtocolMarshaller protocolMarshaller) {
if (methodSnapshot == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(methodSnapshot.getAuthorizationType()... |
Fetches the metric object corresponding to the given name. | def _GetMetric(self, metric_name):
""""""
if metric_name in self._counter_metrics:
return self._counter_metrics[metric_name]
elif metric_name in self._event_metrics:
return self._event_metrics[metric_name]
elif metric_name in self._gauge_metrics:
return self._gauge_metrics[metric_name]... |
Download the specified feed item
@param models\Download\Feed\DownloadFeedItem $DownloadFeedItem
@return bool
@throws \GuzzleHttp\Exception\GuzzleException
@throws \alphayax\freebox\Exception\FreeboxApiException | public function downloadFeedItem(models\Download\Feed\DownloadFeedItem $DownloadFeedItem)
{
$service = sprintf(self::API_DOWNLOAD_FEEDS_ITEMS_ITEM_DOWNLOAD, $DownloadFeedItem->getFeedId(), $DownloadFeedItem->getId());
$rest = $this->callService('POST', $service, $DownloadFeedItem);
retur... |
Perform session cleanup, since the end method should always be
called explicitely by the calling code, this works better than the
destructor.
Set close_fileobj to False so fileobj can be returned open. | def end(self, close_fileobj=True):
""""""
log.debug("in TftpContext.end - closing socket")
self.sock.close()
if close_fileobj and self.fileobj is not None and not self.fileobj.closed:
log.debug("self.fileobj is open - closing")
self.fileobj.close() |
Subsets and Splits
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.