Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
366,700 | def create_s3app(self):
utils.banner("Creating S3 App Infrastructure")
primary_region = self.configs[][]
s3obj = s3.S3Apps(app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
... | Create S3 infra for s3 applications |
366,701 | def items(cls):
items = [(value.name, key) for key, value in cls.values.items()]
return sorted(items, key=lambda x: x[1]) | :return: List of tuples consisting of every enum value in the form [('NAME', value), ...]
:rtype: list |
366,702 | def bulk_copy(self, ids):
schema = UserSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list |
366,703 | def _build_voronoi_polygons(df):
from scipy.spatial import Voronoi
geom = np.array(df.geometry.map(lambda p: [p.x, p.y]).tolist())
vor = Voronoi(geom)
polygons = []
for idx_point, _ in enumerate(vor.points):
idx_point_region = vor.point_region[idx_point]
idxs_vertices = np.arr... | Given a GeoDataFrame of point geometries and pre-computed plot extrema, build Voronoi simplexes for the given
points in the given space and returns them.
Voronoi simplexes which are located on the edges of the graph may extend into infinity in some direction. In
other words, the set of points nearest the g... |
366,704 | def chunkprocess(func):
@functools.wraps(func)
def wrapper(iterable, chunksize, *args, **kwargs):
for chunk in chunkiter(iterable, chunksize):
yield func(chunk, *args, **kwargs)
return wrapper | take a function that taks an iterable as the first argument.
return a wrapper that will break an iterable into chunks using
chunkiter and run each chunk in function, yielding the value of each
function call as an iterator. |
366,705 | def _fill_row_borders(self):
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_data)):
tmp_data.append([])
row_indices = []
... | Add the first and last rows to the data by extrapolation. |
366,706 | def create(ctx, name, integration_type, location, non_interactive, quiet, dry_run):
repo_choice = ctx.obj[]
root = resolve_path(location) if location else get_root()
path_sep = os.path.sep
integration_dir = os.path.join(root, normalize_package_name(name))
if os.path.exists(integration_dir):
... | Create scaffolding for a new integration. |
366,707 | def bare(self):
"Make a Features object with no metadata; points to the same features."
if not self.meta:
return self
elif self.stacked:
return Features(self.stacked_features, self.n_pts, copy=False)
else:
return Features(self.features, copy=False) | Make a Features object with no metadata; points to the same features. |
366,708 | def mask(self, pattern):
cairo.cairo_mask(self._pointer, pattern._pointer)
self._check_status() | A drawing operator that paints the current source
using the alpha channel of :obj:`pattern` as a mask.
(Opaque areas of :obj:`pattern` are painted with the source,
transparent areas are not painted.)
:param pattern: A :class:`Pattern` object. |
366,709 | def check(text):
err = "misc.annotations"
msg = u"Annotation left in text."
annotations = [
"FIXME",
"FIX ME",
"TODO",
"todo",
"ERASE THIS",
"FIX THIS",
]
return existence_check(
text, annotations, err, msg, ignore_case=False, join=True) | Check the text. |
366,710 | def qs_add(self, *args, **kwargs):
query = self.query.copy()
if args:
mdict = MultiDict(args[0])
for k, v in mdict.items():
query.add(k, v)
for k, v in kwargs.items():
query.add(k, v)
return self._copy(query=query) | Add value to QuerySet MultiDict |
366,711 | def _validate_validator(self, validator, field, value):
if isinstance(validator, _str_type):
validator = self.__get_rule_handler(, validator)
validator(field, value)
elif isinstance(validator, Iterable):
for v in validator:
self._validate_vali... | {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
]} |
366,712 | def client_args_for_bank(bank_info, ofx_version):
client_args = {: str(ofx_version)}
if in bank_info[]:
client_args[] = False
client_args[] = False
if in bank_info[]:
client_args[] = False
return client_args | Return the client arguments to use for a particular Institution, as found
from ofxhome. This provides us with an extension point to override or
augment ofxhome data for specific institutions, such as those that
require specific User-Agent headers (or no User-Agent header).
:param bank_info: OFXHome ban... |
366,713 | def get_builder_openshift_url(self):
key = "builder_openshift_url"
url = self._get_deprecated(key, self.conf_section, key)
if url is None:
logger.warning("%r not found, falling back to get_openshift_base_uri()", key)
url = self.get_openshift_base_uri()
re... | url of OpenShift where builder will connect |
366,714 | def standard_FPR(reference_patterns, estimated_patterns, tol=1e-5):
validate(reference_patterns, estimated_patterns)
nP = len(reference_patterns)
nQ = len(estimated_patterns)
k = 0
if _n_onset_midi(reference_patterns) == 0 or \
_n_onset_midi(estim... | Standard F1 Score, Precision and Recall.
This metric checks if the prototype patterns of the reference match
possible translated patterns in the prototype patterns of the estimations.
Since the sizes of these prototypes must be equal, this metric is quite
restictive and it tends to be 0 in most of 2013... |
366,715 | def process_data(self, file_info):
if self._exceeds_max_file_size(file_info):
self.log.info("File has a size in bytes (%d) greater than the configured limit. Will be ignored.",
file_info.path, file_info.size)
self.fire(events.FilteredFile(file_info))
... | expects FileInfo |
366,716 | async def open(self) -> :
LOGGER.debug()
try:
await pool.set_protocol_version(2)
await pool.create_pool_ledger_config(self.name, json.dumps({: str(self.genesis_txn_path)}))
except IndyError as x_indy:
if x_indy.error_code == ErrorCode.PoolLedgerCo... | Explicit entry. Opens pool as configured, for later closure via close().
For use when keeping pool open across multiple calls.
Raise any IndyError causing failure to create ledger configuration.
:return: current object |
366,717 | def url(self) -> str:
return .format(
path=os.path.join(self.results_path, ),
id=self.uuid
) | Returns the URL that will open this project results file in the browser
:return: |
366,718 | def main(configpath = None, startup = None, daemon = False, pidfile = None, fork = None):
if configpath is not None:
manager.loadfrom(configpath)
if startup is not None:
manager[] = startup
if not manager.get():
startup = []
import __main__
for k in dir(... | The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
... |
366,719 | def _expand_libs_in_libs(specs):
for lib_name, lib_spec in specs[].iteritems():
if in lib_spec and in lib_spec[]:
lib_spec[][] = _get_dependent(, lib_name, specs, ) | Expands specs.libs.depends.libs to include any indirectly required libs |
366,720 | def bind(self, sock):
if self.context is None:
self.context = self.get_context()
conn = SSLConnection(self.context, sock)
self._environ = self.get_environ()
return conn | Wrap and return the given socket. |
366,721 | def flatten(self):
def _flatten(d):
if isinstance(d, dict):
for v in d.values():
for nested_v in _flatten(v):
yield nested_v
elif isinstance(d, list):
for list_v in d:
for nested_v i... | Get a flattened list of the items in the collection.
:rtype: Collection |
366,722 | def show_type(cls, result):
if result.ok:
return .join([result.expr, result.type])
return result.value | :param TryHaskell.Result result: Parse result of JSON data.
:rtype: str|unicode |
366,723 | def generalize(self,
sr,
geometries,
maxDeviation,
deviationUnit):
url = self._url + "/generalize"
params = {
"f" : "json",
"sr" : sr,
"deviationUnit" : deviationUnit,
"ma... | The generalize operation is performed on a geometry service resource.
The generalize operation simplifies the input geometries using the
Douglas-Peucker algorithm with a specified maximum deviation distance.
The output geometries will contain a subset of the original input vertices.
... |
366,724 | def CreateChatWith(self, *Usernames):
return Chat(self, chop(self._DoCommand( % .join(Usernames)), 2)[1]) | Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers` |
366,725 | def enable_node(self, service_name, node_name):
logger.info("Enabling server %s/%s", service_name, node_name)
return self.send_command(
"enable server %s/%s" % (service_name, node_name)
) | Enables a given node name for the given service name via the
"enable server" HAProxy command. |
366,726 | def verify_notification(data):
pemfile = grab_keyfile(data[])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(data[]))
if data[] == "Notification":
hash_format = NOTIFICATION_HASH_FORMAT
else:
hash_format = SUBSCRIPTION_HASH_FO... | Function to verify notification came from a trusted source
Returns True if verfied, False if not verified |
366,727 | def get_characteristic_from_uuid(self, uuid):
if uuid in self.uuid_chars:
logger.debug(.format(uuid))
return self.uuid_chars[uuid]
for service in self.services.values():
char = service.get_characteristic_by_uuid(uuid)
if char is not None:
... | Given a characteristic UUID, return a :class:`Characteristic` object
containing information about that characteristic
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, otherwise a :class:`Characteristic` object |
366,728 | def plot_reaction_scheme(df, temperature, pressure, potential, pH, e_lim=None):
ncols = int((df.shape[0]/20)) +1
fig_width = ncols + 1.5*len(df[][0])
figsize = (fig_width, 6)
fig, ax = plt.subplots(figsize=figsize)
if pressure == None:
pressure_label =
else:
pressure_label... | Returns a matplotlib object with the plotted reaction path.
Parameters
----------
df : Pandas DataFrame generated by reaction_network
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
pH : PH in bulk solution
potential : Electric potential vs. SHE in ... |
366,729 | def create_calc_dh_dv(estimator):
dh_dv = diags(np.ones(estimator.design.shape[0]), 0, format=)
calc_dh_dv = partial(_uneven_transform_deriv_v, output_array=dh_dv)
return calc_dh_dv | Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the index.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
Should contain a `design` attribute th... |
366,730 | def get_product_version(path: typing.Union[str, Path]) -> VersionInfo:
path = Path(path).absolute()
pe_info = pefile.PE(str(path))
try:
for file_info in pe_info.FileInfo:
if isinstance(file_info, list):
result = _parse_file_info(file_info)
if resul... | Get version info from executable
Args:
path: path to the executable
Returns: VersionInfo |
366,731 | def indicator_associations(self, params=None):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if params is None:
params = {}
for ia in self.tc_requests.indicator_associations(
self.api_type, self.api_sub_type, self.unique_id, ow... | Gets the indicator association from a Indicator/Group/Victim
Yields: Indicator Association |
366,732 | def get_celery_app(name=None, **kwargs):
from celery import Celery
prepare_environment(**kwargs)
name = name or os.getenv("VST_PROJECT")
celery_app = Celery(name)
celery_app.config_from_object(, namespace=)
celery_app.autodiscover_tasks()
return celery_app | Function to return celery-app. Works only if celery installed.
:param name: Application name
:param kwargs: overrided env-settings
:return: Celery-app object |
366,733 | def to_dict(self):
param = {
"n_folds": self._n_folds,
"n_rows": self._n_rows,
"use_stored_folds": self._use_stored_folds
}
if self._concise_global_model is None:
trained_global_model = None
else:
trained_global_model ... | Returns:
dict: ConciseCV represented as a dictionary. |
366,734 | def get_wildcard(self):
return _convert(self._ip, notation=NM_WILDCARD,
inotation=IP_DOT, _check=False, _isnm=self._isnm) | Return the wildcard bits notation of the netmask. |
366,735 | def dump(self, fh, value, context=None):
value = self.dumps(value)
fh.write(value)
return len(value) | Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written. |
366,736 | def GetCoinAssets(self):
assets = set()
for coin in self.GetCoins():
assets.add(coin.Output.AssetId)
return list(assets) | Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's. |
366,737 | def nonver_name(self):
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r, , self.name)
return nv | Return the non versioned name |
366,738 | def deprecatedMessage(msg, key=None, printStack=False):
if __deprecatedMessagesEnabled is False:
return
if not _alreadyWarned:
sys.stderr.write()
if key is None:
from .compat_str import tobytes
key = md5(tobytes(msg)).hexdigest()
if key not in _alreadyWarned:
_alreadyWarned[key] = True
sys.stderr.... | deprecatedMessage - Print a deprecated messsage (unless they are toggled off). Will print a message only once (based on "key")
@param msg <str> - Deprecated message to possibly print
@param key <anything> - A key that is specific to this message.
If None is provided (default), one will be generated from the... |
366,739 | def _get_updated_environment(self, env_dict=None):
if env_dict is None:
env_dict = {: self}
env = globals().copy()
env.update(env_dict)
return env | Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value |
366,740 | def print_menuconfig(kconf):
print("\n======== {} ========\n".format(kconf.mainmenu_text))
print_menuconfig_nodes(kconf.top_node.list, 0)
print("") | Prints all menu entries for the configuration. |
366,741 | def get_low_battery_warning_level(self):
all_energy_full = []
all_energy_now = []
all_power_now = []
try:
type = self.power_source_type()
if type == common.POWER_TYPE_AC:
if self.is_ac_online():
return common.LOW_BATTER... | Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE.
Otherwise determines total percentage and time remaining across all attached batteries. |
366,742 | def get_async_response(response_id):
response = DYNAMODB_CLIENT.get_item(
TableName=ASYNC_RESPONSE_TABLE,
Key={: {: str(response_id)}}
)
if not in response:
return None
return {
: response[][][],
: json.loads(response[][][]),
} | Get the response from the async table |
366,743 | def _get_force_constants_disps(force_constants,
supercell,
dataset,
symmetry,
atom_list=None):
symprec = symmetry.get_symmetry_tolerance()
disp_atom_list = np.unique([x[] for x in da... | Calculate force constants Phi = -F / d
Force constants are obtained by one of the following algorithm.
Parameters
----------
force_constants: ndarray
Force constants
shape=(len(atom_list),n_satom,3,3)
dtype=double
supercell: Supercell
Supercell
dataset: dict
... |
366,744 | def make_position_choices(self):
choices = []
for pos in self.get_available_positions():
choices.append({
"ResultValue": pos,
"ResultText": pos,
})
return choices | Create choices for available positions |
366,745 | def formatFunctionNode(node,path,stack):
node.weight = calcFnWeight(node)
node.path = path
node.pclass = getCurrentClass(stack)
return node | Add some helpful attributes to node. |
366,746 | def _empty_except_predicates(xast, node, context):
node_c = deepcopy(node)
_remove_predicates(xast, node_c, context)
return bool(len(node_c) == 0 and len(node_c.attrib) == 0) | Check if a node is empty (no child nodes or attributes) except
for any predicates defined in the specified xpath.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element to check
:param context: any context required for the xpath (e.g.,
namespace ... |
366,747 | def worker_collectionfinish(self, node, ids):
if self.shuttingdown:
return
self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids)
self._session.testscollected = len(ids)
self.sched.add_node_collection(node, ids)
if self.t... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
... |
366,748 | def delete_token():
username = get_admin()[0]
admins = get_couchdb_admins()
if username in admins:
print .format(username)
delete_couchdb_admin(username)
if os.path.isfile(LOGIN_FILENAME):
print .format(LOGIN_FILENAME)
os.remove(LOGIN_FILENAME) | Delete current token, file & CouchDB admin user |
366,749 | def command(
self,
mark_success=False,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... | Returns a command that can be executed anywhere where airflow is
installed. This command is part of the message sent to executors by
the orchestrator. |
366,750 | def configure(self, options, config):
self.attribs = []
if compat_24 and options.eval_attr:
eval_attr = tolist(options.eval_attr)
for attr in eval_attr:
def eval_in_context(expr, obj, cls):
r... | Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must match for the rule to
match. |
366,751 | def read_reaction(self, root):
folder_name = os.path.basename(root)
self.reaction, self.sites = ase_tools.get_reaction_from_folder(
folder_name)
self.stdout.write(
.format(.join(self.reaction[]),
.join(self.reaction[])))
self.... | Create empty dictionaries |
366,752 | def contains_vasp_input(dir_name):
for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]:
if not os.path.exists(os.path.join(dir_name, f)) and \
not os.path.exists(os.path.join(dir_name, f + ".orig")):
return False
return True | Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR). |
366,753 | def update_feature_flag(self, state, name, user_email=None, check_feature_exists=None, set_at_application_level_also=None):
route_values = {}
if name is not None:
route_values[] = self._serialize.url(, name, )
query_parameters = {}
if user_email is not None:
... | UpdateFeatureFlag.
[Preview API] Change the state of an individual feature flag for a name
:param :class:`<FeatureFlagPatch> <azure.devops.v5_0.feature_availability.models.FeatureFlagPatch>` state: State that should be set
:param str name: The name of the feature to change
:param str use... |
366,754 | def vcsmode_vcs_mode(self, **kwargs):
config = ET.Element("config")
vcsmode = ET.SubElement(config, "vcsmode", xmlns="urn:brocade.com:mgmt:brocade-vcs")
vcs_mode = ET.SubElement(vcsmode, "vcs-mode")
vcs_mode.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
... | Auto Generated Code |
366,755 | def trim_docstring(docstring):
if not docstring or not docstring.strip():
return ""
lines = docstring.expandtabs().splitlines()
indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip())
trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]... | Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation |
366,756 | def wait_for_ajax_calls_to_complete(self, timeout=5):
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(self.driver, timeout).until(lambda s: s.execute_script("return jQuery.active === 0")) | Waits until there are no active or pending ajax requests.
Raises TimeoutException should silence not be had.
:param timeout: time to wait for silence (default: 5 seconds)
:return: None |
366,757 | def apply_gravity(repulsion, nodes, gravity, scaling_ratio):
for i in range(0, len(nodes)):
repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio) | Iterate through the nodes or edges and apply the gravity directly to the node objects. |
366,758 | def run_process(path: Union[Path, str], target: Callable, *,
args: Tuple=(),
kwargs: Dict[str, Any]=None,
callback: Callable[[Set[Tuple[Change, str]]], None]=None,
watcher_cls: Type[AllWatcher]=PythonWatcher,
debounce=400,
m... | Run a function in a subprocess using multiprocessing.Process, restart it whenever files change in path. |
366,759 | def average_loss(lc):
losses, poes = (lc[], lc[]) if lc.dtype.names else lc
return -pairwise_diff(losses) @ pairwise_mean(poes) | Given a loss curve array with `poe` and `loss` fields,
computes the average loss on a period of time.
:note: As the loss curve is supposed to be piecewise linear as it
is a result of a linear interpolation, we compute an exact
integral by using the trapeizodal rule with the width given by... |
366,760 | def past_active_subjunctive(self):
subjunctive_root = self.sfg3et[:-1] if self.sng[-1] == "a" else self.sfg3et
forms = []
if self.subclass in [1, 2]:
forms.append(subjunctive_root + "a")
subjunctive_root = subjunctive_root[:-1] if subjunctive_root[-1] == "j" els... | Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active_subjunctive()
['kallaða', 'kallaðir', 'kallaði', 'kallaðim', 'kallaðið', 'kallaði']
II
>>> verb = WeakOldNorseVerb()
>>> verb.set... |
366,761 | def parse_args():
def exclusive_group(group, name, default, help):
destname = name.replace(, )
subgroup = group.add_mutually_exclusive_group(required=False)
subgroup.add_argument(f, dest=f,
action=,
help=f--no-{name}\)
... | Parse commandline arguments. |
366,762 | def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0,
random_state=None):
generator = check_random_state(random_state)
X = generator.randn(n_samples, n_features)
y = func(*X.T) + bias
if noise > 0.0:
y += generator.normal(scale=noise, size=y.... | Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape
(100, 1)
>>> y.shape
(100,)
>>> X[:5].round(2)
array([[ 1.62],
[-0.61],
[-0.53],
... |
366,763 | def hessian(self, x, y, kappa_ext, ra_0=0, dec_0=0):
gamma1 = 0
gamma2 = 0
kappa = kappa_ext
f_xx = kappa + gamma1
f_yy = kappa - gamma1
f_xy = gamma2
return f_xx, f_yy, f_xy | Hessian matrix
:param x: x-coordinate
:param y: y-coordinate
:param kappa_ext: external convergence
:return: second order derivatives f_xx, f_yy, f_xy |
366,764 | def find_file(name, directory):
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exists(check_file):
return abspath(check_fil... | Searches up from a directory looking for a file |
366,765 | def removeSheet(self, vs):
self.rows = [r for r in self.rows if r.sheet != vs.name]
status( % vs.name) | Remove all traces of sheets named vs.name from the cmdlog. |
366,766 | def calculate_cycles(self):
element_size = self.kernel.datatypes_size[self.kernel.datatype]
elements_per_cacheline = float(self.machine[]) // element_size
iterations_per_cacheline = (sympy.Integer(self.machine[]) /
sympy.Integer(self.kernel.bytes_per_... | Calculate performance model cycles from cache stats.
calculate_cache_access() needs to have been execute before. |
366,767 | def extract_diff_sla_from_config_file(obj, options_file):
rule_strings = {}
config_obj = ConfigParser.ConfigParser()
config_obj.optionxform = str
config_obj.read(options_file)
for section in config_obj.sections():
rule_strings, kwargs = get_rule_strings(config_obj, section)
for (key, val) in rule_s... | Helper function to parse diff config file, which contains SLA rules for diff comparisons |
366,768 | def rename(name, new_name):
*
current_info = info(name)
if not current_info:
raise CommandExecutionError({0}\.format(name))
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
{0}\.format(new_name)
)
cmd = [, , new_name, name]
__salt__[](cm... | Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name |
366,769 | def create_args(args, root):
extension_args = {}
for arg in args:
parse_extension_arg(arg, extension_args)
for name in sorted(extension_args, key=len):
path = name.split()
update_namespace(root, path, extension_args[name]) | Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A list of strings representing arguments i... |
366,770 | def add_toolbars_to_menu(self, menu_title, actions):
view_menu = self.menus[6]
if actions == self.toolbars and view_menu:
toolbars = []
for toolbar in self.toolbars:
action = toolbar.toggleViewAction()
toolbars.app... | Add toolbars to a menu. |
366,771 | def set_burnstages_upgrade_massive(self):
burn_info=[]
burn_mini=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
burn_info.append(sefiles.burnstage_upgrade())
mini=sefiles.get()
burn_mini.app... | Outputs burnign stages as done in burningstages_upgrade (nugridse) |
366,772 | def as_matrix(self, columns=None):
warnings.warn("Method .as_matrix will be removed in a future version. "
"Use .values instead.", FutureWarning, stacklevel=2)
self._consolidate_inplace()
return self._data.as_array(transpose=self._AXIS_REVERSED,
... | Convert the frame to its Numpy-array representation.
.. deprecated:: 0.23.0
Use :meth:`DataFrame.values` instead.
Parameters
----------
columns : list, optional, default:None
If None, return all columns, otherwise, returns specified columns.
Returns
... |
366,773 | def confd_state_webui_listen_tcp_ip(self, **kwargs):
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
webui = ET.SubElement(confd_state, "webui")
listen = ET.SubElement(webui, "listen")
tcp ... | Auto Generated Code |
366,774 | def _build_message_body(self, body_size):
body = bytes()
while len(body) < body_size:
if not self._inbound:
self.check_for_errors()
sleep(IDLE_WAIT)
continue
body_piece = self._inbound.pop(0)
if not body_piece.v... | Build the Message body from the inbound queue.
:rtype: str |
366,775 | def format(self, clip=0, grand=None):
if self.number > 1:
a, p = int(self.total / self.number),
else:
a, p = self.total,
o = self.objref
if self.weak:
return _kwds(avg=_SI2(a), high=_SI2(self.high),
lengstr=_leng... | Return format dict. |
366,776 | def get_connection(self, command_name, *keys, **options):
connection = None
try:
connection = self.pool.get(block=True, timeout=self.timeout)
except Empty:
raise ConnectionError("No connection available.")
... | Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existing connections
(having been returned to the pool after the initial ``N... |
366,777 | def add_wikipage(self, slug, content, **attrs):
return WikiPages(self.requester).create(
self.id, slug, content, **attrs
) | Add a Wiki page to the project and returns a :class:`WikiPage` object.
:param name: name of the :class:`WikiPage`
:param attrs: optional attributes for :class:`WikiPage` |
366,778 | def calculate_new_length(gene_split, gene_results, hit):
first = 1
for split in gene_split[hit[]]:
new_start = int(gene_results[split][])
new_end = int(gene_results[split][])
if first == 1:
new_length = int(gene_results[split][])
old_start = new_start
... | Function for calcualting new length if the gene is split on several
contigs |
366,779 | def run(self):
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0) | Keep running this thread until it's stopped |
366,780 | def build_parser(self, options=None, permissive=False, **override_kwargs):
kwargs = copy.copy(self._parser_kwargs)
kwargs.setdefault(,
argparse.ArgumentDefaultsHelpFormatter)
kwargs.update(override_kwargs)
if not in kwargs:
kwargs[] =
... | Construct an argparser from supplied options.
:keyword override_kwargs: keyword arguments to override when calling
parser constructor.
:keyword permissive: when true, build a parser that does not validate
required arguments. |
366,781 | def endElement(self, name, value, connection):
if name == :
self.next_record_name = value
elif name == :
self.next_record_type = value
else:
return ResultSet.endElement(self, name, value, connection) | Overwritten to also add the NextRecordName and
NextRecordType to the base object |
366,782 | def get_userid_from_botid(self, botid):
botinfo = self.slack_client.api_call(, bot=botid)
if botinfo[] is True:
return botinfo[].get()
else:
return botid | Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value |
366,783 | def getArgNames(function):
argCount = function.__code__.co_argcount
argNames = function.__code__.co_varnames[:argCount]
return argNames | Returns a list of strings naming all of the arguments for the passed function.
Parameters
----------
function : function
A function whose argument names are wanted.
Returns
-------
argNames : [string]
The names of the arguments of function. |
366,784 | def _get_result_paths(self, data):
result = {}
result[] = ResultPath(Path=self.Parameters[].Value,
IsWritten=True)
if not isfile(result[].Path):
otumap_f = open(result[].Path, )
otumap_f... | Set the result paths |
366,785 | def new_worker_redirected_log_file(self, worker_id):
worker_stdout_file, worker_stderr_file = (self.new_log_files(
"worker-" + ray.utils.binary_to_hex(worker_id), True))
return worker_stdout_file, worker_stderr_file | Create new logging files for workers to redirect its output. |
366,786 | def upload_object(self, object_name, file_obj):
return self._client.upload_object(
self._instance, self.name, object_name, file_obj) | Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
This is mainly useful when accessing an o... |
366,787 | def _compute_cell_extents_grid(bounding_rect=(0.03, 0.03, 0.97, 0.97),
num_rows=2, num_cols=6,
axis_pad=0.01):
left, bottom, width, height = bounding_rect
height_padding = axis_pad * (num_rows + 1)
width_padding = ax... | Produces array of num_rows*num_cols elements each containing the rectangular extents of
the corresponding cell the grid, whose position is within bounding_rect. |
366,788 | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
if self._cryptogr... | Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... |
366,789 | def padded_grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):
regular_padded_grid = PaddedRegularGrid.padded_grid_from_shape_psf_shape_and_pixel_scale(
shape=mask.shape,
psf_shape=psf_shape,
pixel_scale=mask.pixel_scale)
su... | Setup a grid-stack of masked grid_stack from a mask, sub-grid size and psf-shape.
Parameters
-----------
mask : Mask
The mask whose masked pixels the grid-stack are setup using.
sub_grid_size : int
The size of a sub-pixels sub-grid (sub_grid_size x sub_grid_size... |
366,790 | def run_update_cat(_):
recs = MPost2Catalog.query_all().objects()
for rec in recs:
if rec.tag_kind != :
print( * 40)
print(rec.uid)
print(rec.tag_id)
print(rec.par_id)
MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + "00") | Update the catagery. |
366,791 | def match_regex_list(patterns, string):
for p in patterns:
if re.findall(p, string):
return True
return False | Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list. |
366,792 | def _is_valid_relpath(
relpath,
maxdepth=None):
sep, pardir = posixpath.sep, posixpath.pardir
if sep + pardir + sep in sep + relpath + sep:
return False
if maxdepth is not None:
path_depth = relpath.strip(sep).count(sep)
if path_depth > maxdepth:
... | Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it does not exceed a stated maximum depth (if specified). |
366,793 | def system_drop_keyspace(self, keyspace):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_keyspace(keyspace)
return d | drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace |
366,794 | def delete(self, key, cas=0):
returns = []
for server in self.servers:
returns.append(server.delete(key, cas))
return any(returns) | Delete a key/value from server. If key does not exist, it returns True.
:param key: Key's name to be deleted
:param cas: CAS of the key
:return: True in case o success and False in case of failure. |
366,795 | def get_entity_by_query(self, uuid=None, path=None, metadata=None):
content_typeplain/textcreated_by303447created_on2017-03-13T10:52:23.275087Zdescriptionentity_typefilemodified_by303447modified_on2017-03-13T10:52:23.275126Znamemyfileparent3abd8742-d069-44cf-a66b-2370df74a682uuide2c25c1b-f6a9-4cf6-b8d2-271e628a... | Retrieve entity by query param which can be either uuid/path/metadata.
Args:
uuid (str): The UUID of the requested entity.
path (str): The path of the requested entity.
metadata (dict): A dictionary of one metadata {key: value} of the
requested entitity.
... |
366,796 | def get_value(self, name):
value = self.shellwidget.get_value(name)
self.shellwidget._kernel_value = None
return value | Get the value of a variable |
366,797 | def delete(ctx, schema, uuid, object_filter, yes):
database = ctx.obj[]
if schema is None:
log(, lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
count = model.count({: uuid})
obj = model.find({: uuid})
elif object_filter:
count = model... | Delete stored objects (CAUTION!) |
366,798 | def write_graph(self, outfile, manifest):
out_graph = _updated_graph(self.graph, manifest)
nx.write_gpickle(out_graph, outfile) | Write the graph to a gpickle file. Before doing so, serialize and
include all nodes in their corresponding graph entries. |
366,799 | def write_headers(self, fp, headers, mute=None):
if headers:
if not mute:
mute = []
fmt = % (max(len(k) for k in headers) + 1)
for key in sorted(headers):
if key in mute:
continue
fp.write(fmt % (ke... | Convenience function to output headers in a formatted fashion
to a file-like fp, optionally muting any headers in the mute
list. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.