query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Render the second factor forms for displaying at the frontend
@param HTTPRequest $request
@return array
@throws \Exception | public function secondFactor(HTTPRequest $request)
{
$memberID = $request->getSession()->get(BootstrapMFAAuthenticator::SESSION_KEY . '.MemberID');
/** @var Member|MemberExtension $member */
$member = Member::get()->byID($memberID);
if (!$member) {
// Assume the session ... | csn |
// Paragraph generates a paragraph between 2 and 10 sentences. | func (g *Generator) Paragraph() string {
count := g.Int(2, 10)
sentences := make([]string, count)
for i := 0; i < count; i++ {
sentences[i] = g.Sentence()
}
return strings.Join(sentences, " ")
} | csn |
Normalizes feature text.
* **value** must be a :ref:`type-string`.
* Returned value will be an unencoded ``unicode`` string. | def normalizeFeatureText(value):
"""
Normalizes feature text.
* **value** must be a :ref:`type-string`.
* Returned value will be an unencoded ``unicode`` string.
"""
if not isinstance(value, basestring):
raise TypeError("Feature text must be a string, not %s."
% ... | csn |
// This wraps the Close call and ensures we both close the database connection
// and kill the plugin. | func (dc *DatabasePluginClient) Close() error {
err := dc.Database.Close()
dc.client.Kill()
return err
} | csn |
Slot called when user has defined a custom analysis extent.
.. versionadded: 2.2.0
:param extent: Extent of the user's preferred analysis area.
:type extent: QgsRectangle
:param crs: Coordinate reference system for user defined analysis
extent.
:type crs: QgsCoordi... | def define_user_analysis_extent(self, extent, crs):
"""Slot called when user has defined a custom analysis extent.
.. versionadded: 2.2.0
:param extent: Extent of the user's preferred analysis area.
:type extent: QgsRectangle
:param crs: Coordinate reference system for user de... | csn |
Replies the default value of the parameter.
@return the default value builder. | @Pure
public IExpressionBuilder getDefaultValue() {
if (this.defaultValue == null) {
this.defaultValue = this.expressionProvider.get();
this.defaultValue.eInit(this.parameter, new Procedures.Procedure1<XExpression>() {
public void apply(XExpression it) {
getSarlFormalParameter().setDefaultValue(it);... | csn |
!!! The steps in here are sequence dependent !!! | function () {
// 1. call overridden init (calls createContent)
UIComponent.prototype.init.apply(this, arguments);
// 2. nav to initial pages
var router = this.getRouter();
if (!Device.system.phone) {
router.myNavToWithoutHash("sap.ui.demokit.explored.view.master", "XML", true);
router.myNavToWi... | csn |
Saves main Voucherserie parameters changes.
@return mixed | public function save()
{
parent::save();
// Parameter Processing
$soxId = $this->getEditObjectId();
$aSerieParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval");
// Voucher Serie Processing
$oVoucherSerie = oxNew(\OxidEsales\Eshop\App... | csn |
A decorator that marks transform pipes that should be called to create the real transform | def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | csn |
Lists Histories for a given Project.
The histories are sorted by modification time in descending order. The
history_id key will be used to order the history with the same modification
time.
May return any of the following canonical error codes:
- PERMISSION_DENIED - if the user is not authorized to read project -
IN... | public function listProjectsHistories($projectId, $optParams = array())
{
$params = array('projectId' => $projectId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_ToolResults_ListHistoriesResponse");
} | csn |
Returns an optional JobDefinition matching the given jobType.
@param jobType case insensitive {@link JobDefinition#jobType() job type}
@return optional JobDefinition | public Optional<JobDefinition> getJobDefinition(final String jobType) {
return jobDefinitions
.stream()
.filter((j) -> j.jobType().equalsIgnoreCase(jobType))
.findAny();
} | csn |
Build an html form select element.
@param string $name The select's name.
@param bool $multiple Option for multiple selection.
@param string $id The select's id attribute.
@param string $class The select's class attribute.
@param array $options An array of value -> title optio... | public function buildSelect($name = '', $multiple = false, $id = '', $class = '', $options = [], $selectedValue = '', $required = false, $attributes = [])
{
// Create select form input
$id = $id ?: 'fs' . mt_rand();
$element = new FormSelect($this->getHTMLDocument(), $this, $name, $id, $clas... | csn |
check if the method was called with the exact arguments
@param args Arguments that should have been sent to the method
@return [Boolean] | def has_been_called_with?(*args)
raise NeverHookedError unless @was_hooked
match = block_given? ? Proc.new : proc { |call| call.args == args }
calls.any?(&match)
end | csn |
Best practice build pipeline. This only only chains up the various build steps.
@param {Object} config Content of polymer.json
@return | function build(config) {
return lazypipe()
.pipe(() => polymerBuild(config))
.pipe(() => addCspCompliance())
.pipe(() => addCacheBusting())
.pipe(() => optimizeAssets())
.pipe(() => injectCustomElementsEs5Adapter());
} | csn |
get data by where clause.
@param string $column
@param string $relation
@param string $value
@return array | public static function where($column, $relation, $value)
{
$self = self::instance();
$key = $self->_keyName;
$data = \Query::from($self->_table)->select($key)->where($column, $relation, $value)->get();
$rows = [];
if (!is_null($data)) {
foreach ($data as $item) {... | csn |
adds price to a price-group
@param $price
@param $item
@param $groupPrices
@param $groupedItems
@internal param $itemPriceGroup | protected function addPriceToPriceGroup($price, $item, &$groupPrices, &$groupedItems)
{
$itemPriceGroup = $item->getCalcPriceGroup();
if ($itemPriceGroup === null) {
$itemPriceGroup = 'undefined';
}
if (!isset($groupPrices[$itemPriceGroup])) {
$groupPrices[$... | csn |
Override the makeHttpRequest function so we can implement caching.
If caching is enabled then we try and retrieve a matching request for the
object name and range from memcache.
If we find a result in memcache, and optimistic caching is enabled then
we return that result immediately without checking if the object has
c... | protected function makeHttpRequest($url, $method, $headers, $body = null) {
if (!$this->context_options['enable_cache']) {
return parent::makeHttpRequest($url, $method, $headers, $body);
}
$cache_key = static::getReadMemcacheKey($url, $headers['Range']);
$cache_obj = $this->memcache_client->get($... | csn |
// addHTTPSRules - Add rules to 443 access given the presence of a loadbalancer or not | func (b *FirewallModelBuilder) addHTTPSRules(c *fi.ModelBuilderContext, sgMap map[string]*openstacktasks.SecurityGroup) error {
masterName := b.SecurityGroupName(kops.InstanceGroupRoleMaster)
nodeName := b.SecurityGroupName(kops.InstanceGroupRoleNode)
lbSGName := b.Cluster.Spec.MasterPublicName
lbSG := sgMap[lbSGN... | csn |
OpenST Utility Contract constructor
@constructor
@augments OwnedKlass
@param {string} contractAddress - address on Utility Chain where Contract has been deployed | function (contractAddress) {
// Helpful while deployement, since ENV variables are not set at that time
contractAddress = contractAddress || openSTUtilityContractAddr;
const oThis = this;
oThis.contractAddress = contractAddress;
openSTUtilityContractObj.options.address = contractAddress;
//openSTUtilityC... | csn |
Returns results as a JSON encodable Python value.
This calls :meth:`SearchEngine.recommendations` and converts
the results returned into JSON encodable values. Namely,
feature collections are slimmed down to only features that
are useful to an end-user. | def results(self):
'''Returns results as a JSON encodable Python value.
This calls :meth:`SearchEngine.recommendations` and converts
the results returned into JSON encodable values. Namely,
feature collections are slimmed down to only features that
are useful to an end-user.
... | csn |
Adds a submit button that triggers the form logic on submit
@param name The button name; if omitted, a name is generated by bundle and module name
@param label The visible button label; if omitted, a label is generated
@return Submit Returns the added submit button | protected function AddSubmit($name = '', $label = '')
{
$defaultLabel = $this->Label('Submit');
if (!$name)
{
//html attributes better without dot
$name = str_replace('.', '-', $defaultLabel);
}
if (!$label)
{
$label = Worder::Repla... | csn |
// replaceKeyAt replaces the key at index i with the provided id. This does
// not do any bounds checking. | func (n *Node) replaceKeyAt(key *Key, i int) {
n.ChildKeys[i] = key
} | csn |
Ingest the configuration object into the click context. | def ingest_config_obj(ctx, *, silent=True):
""" Ingest the configuration object into the click context. """
try:
ctx.obj['config'] = Config.from_file(ctx.obj['config_path'])
except ConfigLoadError as err:
click.echo(_style(ctx.obj['show_color'], str(err), fg='red', bold=True))
if not... | csn |
Removes any indentation that is common to all of the given lines. | def unindent(self, lines):
"""Removes any indentation that is common to all of the given lines."""
indent = min(
len(self.re.match(r'^ *', line).group()) for line in lines)
return [line[indent:].rstrip() for line in lines] | csn |
Attempt to remove the EighthSignup if the user has permission to do so. | def remove_signup(self, user=None, force=False, dont_run_waitlist=False):
"""Attempt to remove the EighthSignup if the user has permission to do so."""
exception = eighth_exceptions.SignupException()
if user is not None:
if user != self.user and not user.is_eighth_admin:
... | csn |
List Order Items By Next Token
If ListOrderItems cannot return all the order items in one go, it will
provide a nextToken. That nextToken can be used with this operation to
retrive the next batch of items for that order.
@param mixed $request array of parameters for MarketplaceWebServiceOrders_Model_ListOrderItemsByNe... | public function listOrderItemsByNextToken($request)
{
if (!($request instanceof MarketplaceWebServiceOrders_Model_ListOrderItemsByNextTokenRequest)) {
// // require_once (dirname(__FILE__) . '/Model/ListOrderItemsByNextTokenRequest.php');
$request = new MarketplaceWebServiceOrders_Mo... | csn |
Set the value as provided.
@param value the serial date value as JSON string. | public final void setValue(String value) {
if ((null == value) || value.isEmpty()) {
setDefaultValue();
} else {
try {
tryToSetParsedValue(value);
} catch (@SuppressWarnings("unused") Exception e) {
CmsDebugLog.consoleLog("Could not se... | csn |
// configureDaemon is called prior to Start to allow system-specific setup. | func configureDaemon(cmd *exec.Cmd) {
// Start it in a new sessions (and hence process group) so that killing agent
// (even with Ctrl-C) won't kill proxy.
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
} | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceColumnDefinition. | func (in *CustomResourceColumnDefinition) DeepCopy() *CustomResourceColumnDefinition {
if in == nil {
return nil
}
out := new(CustomResourceColumnDefinition)
in.DeepCopyInto(out)
return out
} | csn |
Generate create table.
@param array $output
@param array $table
@param bool $forceSave (false)
@return array | protected function getCreateTable($output, $table, $tableName, $forceSave = false)
{
$output[] = $this->getTableVariable($table, $tableName);
$alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table);
if (empty($alternatePrimaryKeys) || $forceSave) {
$output[] = sprintf("%s... | csn |
Parse PresentationNotes object
@param file [String] file to parse
@return [PresentationNotes] result of parsing | def parse(file)
node = parse_xml(file)
node.xpath('p:notes/*').each do |node_child|
case node_child.name
when 'cSld'
@common_slide_data = CommonSlideData.new(parent: self).parse(node_child)
end
end
self
end | csn |
append a single item to the array, growing the wrapped numpy array
if necessary | def append(self, item):
"""
append a single item to the array, growing the wrapped numpy array
if necessary
"""
try:
self._data[self._position] = item
except IndexError:
self._grow()
self._data[self._position] = item
self._posit... | csn |
Add Header Rows, call from header_callback | public function addHeader($add, $dca)
{
$catId = $add['id'];
unset($add['id']); //delete the helper
$sql = 'SELECT CAST(`banner_published` AS UNSIGNED INTEGER) AS published
,count(id) AS numbers
FROM `tl_banner`
WHERE `pid`=?
... | csn |
// CopyToContainer copies content into the container filesystem.
// Note that `content` must be a Reader for a TAR archive | 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 ... | csn |
Returns a time field
@param string|null
@param scalar|null
@return Eden\Block\Field\Datetime | public function time($name = null, $value = null)
{
Argument::i()
->test(1, 'string', 'null')
->test(2, 'scalar', 'null');
$field = Datetime::i()
->setOptions('pickDate', false)
->setOptions('format', 'HH:mm PP');
if(!is_null($name)) {
$field->setName($name);
}
if(!is_null($value)) ... | csn |
Creates a new directory instance. | public static function make(string $path, FormatInterface $format): Directory
{
return new static(new Filesystem(new Local($path)), '', $format);
} | csn |
Get storage containers
REST: GET /cloud/project/{serviceName}/storage
@param serviceName [required] Service name | public ArrayList<OvhContainer> project_serviceName_storage_GET(String serviceName) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t5);
} | csn |
// IsPattern returns true if the string is a pattern. | func IsPattern(str string) bool {
for i := 0; i < len(str); i++ {
if str[i] == '*' || str[i] == '?' {
return true
}
}
return false
} | csn |
//
// Command line helper functions
// | func die(printHelp bool, format string, args ...interface{}) {
if printHelp {
fmt.Print(HELP)
}
fmt.Printf(format, args...)
fmt.Println("")
os.Exit(1)
} | csn |
Gets the access token for the app given the code
Parameters:
- code - the response code | def get_access_token(self, code):
""" Gets the access token for the app given the code
Parameters:
- code - the response code
"""
payload = {'redirect_uri': self.redirect_uri,
'code': code,
'grant_type': 'authorization_code'}
... | csn |
command registry has command
@param string $command
@return boolean | public static function hasCommand($command)
{
if (!is_string($command) || strlen($command) < 1) {
throw new BadMethodCallException('Parameter command is not a valid string');
}
$instance = self::getInstance();
return isset($instance->commands[$command]);
} | csn |
Compares all differences with the referenceSequence in order to reduce the stored sequence.
Also adds sequence for deletion differences.
@param alignment The Alignment
@param referenceSequence Reference sequence
@param referenceSequenceStart Reference sequence start
@throws org.opencb.biodata.models.alignment.exceptio... | public static void completeDifferencesFromReference(Alignment alignment, String referenceSequence, long referenceSequenceStart) throws ShortReferenceSequenceException {
int offset = (int) (alignment.getUnclippedStart() - referenceSequenceStart);
String subRef;
String subRead;
if ((align... | csn |
Returns a new relationship aggregate for the given relationship.
:param relationship: Instance of
:class:`everest.entities.relationship.DomainRelationship`. | def make_relationship_aggregate(self, relationship):
"""
Returns a new relationship aggregate for the given relationship.
:param relationship: Instance of
:class:`everest.entities.relationship.DomainRelationship`.
"""
if not self._session.IS_MANAGING_BACKREFERENCES:
... | csn |
Extracts the URL from an image element on the page. | def get_image_url(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Extracts the URL from an image element on the page. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return ... | csn |
Delete filtered load balancers
@param filter load balancer filter
@return OperationFuture wrapper for load balancer list | public OperationFuture<List<LoadBalancer>> delete(LoadBalancerFilter filter) {
List<LoadBalancer> loadBalancerList = findLazy(filter)
.map(metadata -> LoadBalancer.refById(
metadata.getId(),
DataCenter.refById(metadata.getDataCenterId()))
)... | csn |
parse command line options and run commands. | def main_hrun():
""" parse command line options and run commands."""
parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.")
parser.add_argument(
'--log-level', default='INFO',
help="Specify logging level, default is INFO.")
p... | csn |
Log the relative time remaining for this est_complete datetime object. | def log_est_complete(est_complete):
"""
Log the relative time remaining for this est_complete datetime object.
"""
if not est_complete:
print('could not determine an estimated completion time')
return
remaining = est_complete - datetime.utcnow()
message = 'this task should be com... | csn |
Do a binary earch for a given value within a character string array.
Return the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html
:param value: Key value to be found in array.
:type value: str
:p... | def bsrchc(value, ndim, lenvals, array):
"""
Do a binary earch for a given value within a character string array.
Return the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html
:param value: Key va... | csn |
Open the input stream of the WebSocket connection.
The stream is used by the reading thread. | private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
{
try
{
// Get the input stream of the raw socket through which
// this client receives data from the server.
return new WebSocketInputStream(
new BufferedInputSt... | csn |
convenience function that takes in a
nested structure of lists and dictionaries
and converts everything to its base objects.
This is useful for dupming a file to yaml.
(a) numpy arrays into python lists
>>> type(tolist(np.asarray(123))) == int
True
>... | def tolist(x):
""" convenience function that takes in a
nested structure of lists and dictionaries
and converts everything to its base objects.
This is useful for dupming a file to yaml.
(a) numpy arrays into python lists
>>> type(tolist(np.asarray(123))) == int
... | csn |
Write an integer as an unsigned 8-bit value.
@param $n
@return Writer
@throws \InvalidArgumentException | public function writeOctet($n)
{
if ($n < 0 || $n > 255) {
throw new \InvalidArgumentException('Octet out of range 0..255');
}
$this->flushBits();
$this->out .= chr($n);
return $this;
} | csn |
Once processed with a position, height, and width, HelloSign will
estimate the number of lines a custom field can contain, along with the
number of characters per line. This method will return the estimated
average number of lines of text this field can hold.
@return Integer or null if not set | public Integer getEstimatedTextLines() {
if (!dataObj.has(CUSTOM_FIELD_AVG_TEXT_LENGTH)) {
return null;
}
Integer numLines = null;
try {
JSONObject obj = dataObj.getJSONObject(CUSTOM_FIELD_AVG_TEXT_LENGTH);
numLines = obj.getInt(CUSTOM_FIELD_NUM_LINES)... | csn |
Decodes a constructor parameter value
@param ReflectionParameter $constructorParam The constructor parameter to decode
@param mixed $constructorParamValue The encoded constructor parameter value
@param ReflectionClass $reflectionClass The reflection class we're trying to instantiate
@param string $normalizedHashProper... | private function decodeConstructorParamValue(
ReflectionParameter $constructorParam,
$constructorParamValue,
ReflectionClass $reflectionClass,
string $normalizedHashPropertyName,
EncodingContext $context
) {
if ($constructorParam->hasType() && !$constructorParam->isAr... | csn |
// Subnets returns all the subnets associated with the Space. | func (s *Space) Subnets() (results []*Subnet, err error) {
defer errors.DeferredAnnotatef(&err, "cannot fetch subnets")
name := s.Name()
subnetsCollection, closer := s.st.db().GetCollection(subnetsC)
defer closer()
var doc subnetDoc
// We ignore space-name field for FAN subnets...
iter := subnetsCollection.Fin... | csn |
Expands a dot notation array into a full multi-dimensional array
@param array $dotNotationArray
@return array | public function undot(array $dotNotationArray)
{
$array = [];
foreach ($dotNotationArray as $key => $value) {
$this->set($array, $key, $value);
}
return $array;
} | csn |
Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
:py:func:`enoslib.infra.provider.Provider.init` | def _to_enos_networks(networks):
"""Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
:py:func:`enoslib.infra.provider.Provider.init`
"""
nets = []
for roles, network in networks:
nets.append(network.to_enos(roles))
logger.debug... | csn |
Refresh node data using existing connection-objects. | def get_data(conn_objs, providers):
"""Refresh node data using existing connection-objects."""
cld_svc_map = {"aws": nodes_aws,
"azure": nodes_az,
"gcp": nodes_gcp,
"alicloud": nodes_ali}
sys.stdout.write("\rCollecting Info: ")
sys.stdout.flush()... | csn |
Get php doc and return_type for method by name
@param string $name The name of the method to grab the docs for
@return Object with return_type and phpdoc property | protected function getPhpdoc($method)
{
$reflect = false;
foreach($this->served_classes as $class){
if (\method_exists($class, $method)) {
$reflect = new \ReflectionMethod($class, $method);
break;
}
}
... | csn |
JdbcTemplateTool supports mulitiple catalog query. You can put a placeholder before your table name, JdbcTemplateTool will change this placeholder to real catalog name with the catalog stored in catalogContext.
@param sql
@return | public static String changeCatalog(String sql){
CatalogContext catalogContext = catalogContextHolder.get();
if(catalogContext != null && catalogContext.getCatalog() != null && catalogContext.getPlaceHolder() != null){
sql = sql.replace(catalogContext.getPlaceHolder(), catalogContext.getCatalog());
}
logger.d... | csn |
Creates mapping df based on ann_label_table and self.custom_labels.
Table composed of entire WFDB standard annotation table, overwritten/appended
with custom_labels if any. Sets __label_map__ attribute, or returns value. | def create_label_map(self, inplace=True):
"""
Creates mapping df based on ann_label_table and self.custom_labels.
Table composed of entire WFDB standard annotation table, overwritten/appended
with custom_labels if any. Sets __label_map__ attribute, or returns value.
"""
... | csn |
Draws the bars along the x axis
@param {D3Selection} layersSelection Selection of layers
@return {void} | function drawHorizontalBars(layersSelection) {
let layerJoin = layersSelection
.data(layers);
layerElements = layerJoin
.enter()
.append('g')
.attr('transform', ({key}) => `translate(0,${yScale(key)})`)
.c... | csn |
// Get a value descriptor based on the query | func (mc MongoClient) getValueDescriptor(q bson.M) (models.ValueDescriptor, error) {
s := mc.getSessionCopy()
defer s.Close()
var m models.ValueDescriptor
if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).One(&m); err != nil {
return models.ValueDescriptor{}, errorMap(err)
}
return m, ni... | csn |
Let each slot know which section it is part of. | protected function link_sections_and_slots() {
foreach ($this->sections as $i => $section) {
if (isset($this->sections[$i + 1])) {
$section->lastslot = $this->sections[$i + 1]->firstslot - 1;
} else {
$section->lastslot = count($this->slots);
}... | csn |
// SetInstanceClass sets the InstanceClass field's value. | func (s *ESInstanceDetails) SetInstanceClass(v string) *ESInstanceDetails {
s.InstanceClass = &v
return s
} | csn |
Determines whether the supplied string is a valid URL.
@param urlAsString the URL, as a String
@return true if the URL is valid, false otherwise | public static boolean isUrl(String urlAsString) {
if (urlAsString != null && urlAsString.trim().length() > 0) {
try {
new URL(urlAsString);
return true;
} catch (MalformedURLException murle) {
return false;
}
}
... | csn |
Given a list of records of the same priority, chooses a random one
from among them, favoring those with higher weights.
@param [[Resolv::DNS::Resource::IN::SRV]] records a list of records
of the same priority
@return [Resolv::DNS::Resource::IN:SRV] the chosen record | def find_weighted_server(records)
return nil if records.nil? || records.empty?
return records.first if records.size == 1
# Calculate the sum of all weights in the list of resource records,
# This is used to then select hosts until the weight exceeds what
# random number we selected. For ... | csn |
Stop the Extension Timer for 1xx. | public void cancel1xxTimer() {
if (proxy1xxTimeoutTask != null && proxyBranch1xxTimerStarted) {
proxy1xxTimeoutTask.cancel();
proxy1xxTimeoutTask = null;
proxyBranch1xxTimerStarted = false;
}
} | csn |
// FillStroke first fills the paths and than strokes them | func (rgc *RasterGraphicContext) FillStroke(paths ...*Path) {
paths = append(paths, rgc.current.Path)
rgc.fillRasterizer.UseNonZeroWinding = rgc.current.FillRule == FillRuleWinding
rgc.strokeRasterizer.UseNonZeroWinding = true
flattener := Transformer{Tr: rgc.current.Tr, Flattener: FtLineBuilder{Adder: rgc.fillRas... | csn |
Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))} | def parse_registries(filesystem, registries):
"""Returns a dictionary with the content of the given registry hives.
{"\\Registry\\Key\\", (("ValueKey", "ValueType", ValueValue))}
"""
results = {}
for path in registries:
with NamedTemporaryFile(buffering=0) as tempfile:
filesys... | csn |
Adds a service as event subscriber
@param string $serviceId The service ID of the subscriber service
@param string $class The service's class name (which must implement EventSubscriberInterface) | public function addSubscriberService($serviceId, $class)
{
$rfc = new \ReflectionClass($class);
if (!$rfc->implementsInterface('Symfony\Component\EventDispatcher\EventSubscriberInterface')) {
throw new \InvalidArgumentException(
"$class must implement Symfony\Component\Ev... | csn |
Create new instance for type based SPI.
@param type SPI type
@param props SPI properties
@return SPI instance | public final T newService(final String type, final Properties props) {
Collection<T> typeBasedServices = loadTypeBasedServices(type);
if (typeBasedServices.isEmpty()) {
throw new ShardingConfigurationException("Invalid `%s` SPI type `%s`.", classType.getName(), type);
}
T res... | csn |
Yellow text with current time
@param string $s | public static function dbgTime($s)
{
if (getenv('DEBUG') == '1') {
self::printMessage('<' . Carbon::now()->toTimeString() . '> ' . self::withCallsite($s), 'comment');
}
} | csn |
This will push the master branch to the remote named `remote_name`
using the mirroring strategy to cut down on locking of the working repo.
`doc_id` is used to determine which shard should be pushed.
if `doc_id` is None, all shards are pushed. | def push_doc_to_remote(self, remote_name, doc_id=None):
"""This will push the master branch to the remote named `remote_name`
using the mirroring strategy to cut down on locking of the working repo.
`doc_id` is used to determine which shard should be pushed.
if `doc_id` is None, all sha... | csn |
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式 | def ajax_list_catalog(self, catid):
'''
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
'''
out_arr = {}
for catinfo in MPost2Catalog.query_postinfo_by_cat(catid):
out_arr[catinfo.uid] = catinfo.title
json.dump(out_arr, ... | csn |
sign up in background.
@return | public Observable<AVUser> signUpInBackground() {
JSONObject paramData = generateChangedParam();
logger.d("signup param: " + paramData.toJSONString());
return PaasClient.getStorageClient().signUp(paramData).map(new Function<AVUser, AVUser>() {
@Override
public AVUser apply(AVUser avUser) throws E... | csn |
// findMatch returns the offset of src where the block starting at tgtOffset
// is and the length of the match. A length of 0 means there was no match. A
// length of -1 means the src length is lower than the blksz and whatever
// other positive length is the length of the match in bytes. | func (idx *deltaIndex) findMatch(src, tgt []byte, tgtOffset int) (srcOffset, l int) {
if len(tgt) < tgtOffset+s {
return 0, len(tgt) - tgtOffset
}
if len(src) < blksz {
return 0, -1
}
if len(tgt) >= tgtOffset+s && len(src) >= blksz {
h := hashBlock(tgt, tgtOffset)
tIdx := h & idx.mask
eIdx := idx.table... | csn |
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template` | def get_context_data(self, **kwargs):
"""
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template`
... | csn |
Converts this size to another system.
@param string $system system to convert to
@return Size this size | public function to($system)
{
$this->value = $this->lookup($system);
$this->system = $system;
return $this;
} | csn |
Confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the server generated
a queue name, this fie... | def _queue_declare_ok(self, args):
"""Confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the server ge... | csn |
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no action is taken. This has the
following advantages:
... | def write_two_phases(filename, data, io):
"""
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no actio... | csn |
Return the default value for the requested parameter.
@return string A stringified version of the default value. | public function getDefault()
{
if ($this->reflection->isDefaultValueAvailable()
and $default = $this->reflection->getDefaultValue()
) {
if (is_scalar($default)) {
return $default;
} else {
return $this->tostring($default);
... | csn |
Launch ad hoc scans against each group of assets per site.
@param [Connection] connection Connection to console where asset group
is configured.
@return [Hash] Hash of site ID to Scan launch information for each scan. | def rescan_assets(connection)
scans = {}
sites_ids = @assets.map(&:site_id).uniq
sites_ids.each do |site_id|
to_scan = @assets.select { |d| d.site_id == site_id }
scans[site_id] = connection.scan_devices(to_scan)
end
scans
end | csn |
Download, prepare and executes a compressed tar file from S3 or provided directory as an user
entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command
arguments.
If the entry point is:
- A Python package: executes the packages as >>> env_vars python -m mo... | def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
"""Download, prepa... | csn |
Update the unparsed node dictionary and build the basis for an
intermediate ParsedNode that will be passed into the renderer | def _build_intermediate_node_dict(self, config, node_dict, node_path,
package_project_config, tags, fqn,
agate_table, archive_config,
column_name):
"""Update the unparsed node dictionary and build t... | csn |
Initialize filler rule definition.
@param fillerRuleDefinitionEntity filler rule definition entity | @SuppressWarnings("unchecked")
@SneakyThrows
public void init(final FillerRuleDefinitionEntity fillerRuleDefinitionEntity) {
for (FillerRuleEntity each : fillerRuleDefinitionEntity.getRules()) {
rules.put((Class<? extends SQLSegment>) Class.forName(each.getSqlSegmentClass()), (SQLSegmentFill... | csn |
// Init initializes the decoder with bytes to read from. | func (d *TimeDecoder) Init(b []byte) {
d.v = 0
d.i = 0
d.ts = d.ts[:0]
d.err = nil
if len(b) > 0 {
// Encoding type is stored in the 4 high bits of the first byte
d.encoding = b[0] >> 4
}
d.decode(b)
} | csn |
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
... | def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icing... | csn |
Get language list from repo
@return array | public function getLangRepoList()
{
$data = json_decode(
$this->getRemoteContents($this->translationsInfoUrl)
);
$content = $data->encoding === 'base64' ? base64_decode($data->content) : [];
return json_decode($content);
} | csn |
Sets the system field.
@param system sets the system property.
@param <T> resource type to be returned.
@return this, as casted to a resource, for the ease of chaining. | @SuppressWarnings("unchecked")
public <T extends CMAResource> T setSystem(CMASystem system) {
this.system = system;
return (T) this;
} | csn |
// Logout issues a REIN FTP command to logout the current user. | func (c *ServerConn) Logout() error {
_, _, err := c.cmd(StatusReady, "REIN")
return err
} | csn |
// NewStopwords returns an instance of a stop words detector | func NewStopwords() StopWords {
cachedStopWords := make(map[string]*set.Set)
for lang, stopwords := range sw {
lines := strings.Split(stopwords, "\n")
cachedStopWords[lang] = set.New(set.ThreadSafe).(*set.Set)
for _, line := range lines {
if strings.HasPrefix(line, "#") {
continue
}
line = strings.... | csn |
// Encode takes the given MessageSigner and returns a string encoding this
// invoice signed by the node key of the signer. | func (invoice *Invoice) Encode(signer MessageSigner) (string, error) {
// First check that this invoice is valid before starting the encoding.
if err := validateInvoice(invoice); err != nil {
return "", err
}
// The buffer will encoded the invoice data using 5-bit groups (base32).
var bufferBase32 bytes.Buffer
... | csn |
Depicts the requested molecules with NGLViewer in a Python notebook.
This method does not require a headless Chimera build, however.
Parameters
----------
molecules : tuple of chimera.Molecule
Molecules to display. If none is given, all present molecules
in Chimera canvas will be displa... | def chimera_view(*molecules):
"""
Depicts the requested molecules with NGLViewer in a Python notebook.
This method does not require a headless Chimera build, however.
Parameters
----------
molecules : tuple of chimera.Molecule
Molecules to display. If none is given, all present molecule... | csn |
Extracts a raw WHERE clause string from a QueryBuilder instance.
Note that this is practically identical to the original Listify.
@param QueryBuilder $query A Query Builder instance
@return string | protected function getConditionStringFromQueryBuilder(QueryBuilder $query)
{
$initialQueryChunks = explode('where ', $query->toSql());
if (count($initialQueryChunks) == 1) {
throw new InvalidArgumentException(
'The query builder instance must have a where clause to build... | csn |
Maps each tuple from this stream into 0 or 1 stream tuples.
For each tuple on this stream ``result = func(tuple)`` is called.
If `result` is not `None` then the result will be submitted
as a tuple on the returned stream. If `result` is `None` then
no tuple submission will occur.
... | def map(self, func=None, name=None, schema=None):
"""
Maps each tuple from this stream into 0 or 1 stream tuples.
For each tuple on this stream ``result = func(tuple)`` is called.
If `result` is not `None` then the result will be submitted
as a tuple on the returned stream. If `... | csn |
// IsValidPath returns true if importPath is structurally valid. | func IsValidPath(importPath string) bool {
return pathFlags[importPath]&packagePath != 0 ||
pathFlags["vendor/"+importPath]&packagePath != 0 ||
IsValidRemotePath(importPath)
} | csn |
Strips tags on the value of the property to work on.
@param NodeData $node
@return void | public function execute(NodeData $node)
{
$node->setProperty($this->propertyName, strip_tags($node->getProperty($this->propertyName)));
} | csn |
Admin user is allowed to be deleted only by mall admin
@return null | public function deleteEntry()
{
if ($this->_allowAdminEdit($this->getEditObjectId())) {
$this->_oList = null;
return parent::deleteEntry();
}
} | csn |
Sets data into the given path, with options to override our internal prefix, and to
force-overwrite data if it's not an array.
@param $path <str> path to set the data into.
@param $data <mixed> what to set into the given path.
@return 0 FAIL: old data doesn't match new data.
@return 1 PASS: everything lin... | public function set_data($path, $data) {
if(is_object($data)) {
throw new InvalidArgumentException("objects are not supported");
}
else {
//get the list of indices in the session that we have to traverse.
$myIndexList = $this->explode_path($path);
$retval = 0;
//Use an internal iterator to go thro... | csn |
the api only returns concatenated date instead of month and year in single fields
so we want to map them because we use the single fields for submitting. | protected function MapExpireDateFromAPI()
{
if (isset($this->aPaymentUserData['ED']) && '' !== $this->aPaymentUserData['ED']) {
$this->aPaymentUserData['ECOM_CARDINFO_EXPDATE_MONTH'] = substr($this->aPaymentUserData['ED'], 0, 2);
$this->aPaymentUserData['ECOM_CARDINFO_EXPDATE_YEAR'] ... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.