Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
10,200 | def get_signature(self, req):
oss_url = url.URL(req.url)
oss_headers = [
"{0}:{1}\n".format(key, val)
for key, val in req.headers.lower_items()
if key.startswith(self.X_OSS_PREFIX)
]
canonicalized_headers = "".join(sorted(oss_headers))
... | calculate the signature of the oss request
Returns the signatue |
10,201 | def pydeps2reqs(deps):
reqs = defaultdict(set)
for k, v in list(deps.items()):
p = v[]
if p and not p.startswith(sys.real_prefix):
if p.startswith(sys.prefix) and in p:
if not p.endswith():
if in p.replace(, ):
... | Convert a deps instance into requirements. |
10,202 | def parse_url(url):
if url.startswith((, , )):
if url.startswith():
return urlparse.urlparse(url, scheme=)
else:
return urlparse.urlparse(url)
else:
return urlparse.urlparse(urlparse.urljoin(, url)) | Return a clean URL. Remove the prefix for the Auth URL if Found.
:param url:
:return aurl: |
10,203 | def is_valid_regex(string):
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return is_valid | Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean |
10,204 | def yaml_to_str(data: Mapping) -> str:
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) | Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str |
10,205 | def sv_variant(store, institute_id, case_name, variant_id=None, variant_obj=None, add_case=True,
get_overlapping=True):
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
if not variant_obj:
variant_obj = store.variant(variant_id)
if add_case:
... | Pre-process an SV variant entry for detail page.
Adds information to display variant
Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
case_name(str)
variant_id(str)
variant_obj(dcit)
add_case(bool): If information about case files should be added
R... |
10,206 | def z__update(self):
updates = []
for text in self._updates:
if self._AVOID_RAW_FORM:
text_repr = multiline_repr(text)
raw_char =
else:
text_repr = multiline_repr(text, RAW_MULTILINE_CHARS)
if len(text_r... | Triple quoted baseline representation.
Return string with multiple triple quoted baseline strings when
baseline had been compared multiple times against varying strings.
:returns: source file baseline replacement text
:rtype: str |
10,207 | def _set_comment(self, section, comment, key=None):
if in comment:
comment = .join(comment.split())
comment = + comment
if key:
self._comments[(section, key)] = comment
else:
self._comments[section] = comment | Set a comment for section or key
:param str section: Section to add comment to
:param str comment: Comment to add
:param str key: Key to add comment to |
10,208 | def largest_compartment_id_met(model):
candidate, second = sorted(
((c, len(metabolites_per_compartment(model, c)))
for c in model.compartments), reverse=True, key=itemgetter(1))[:2]
if candidate[1] == second[1]:
raise RuntimeError("There is a tie for the largest compartm... | Return the ID of the compartment with the most metabolites.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Returns
-------
string
Compartment ID of the compartment with the most metabolites. |
10,209 | def fit(self,
target_type,
target,
adjust_thickness=False,
adjust_site_atten=False,
adjust_source_vel=False):
density = self.profile.density
nl = len(density)
slowness = self.profile.slowness
thickness = self... | Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer
thickness (if enabled) to fit a target values. The frequency range is
specified by the input motion.
Parameters
----------
target_type: str
... |
10,210 | def name(value):
if value is None:
return
for (test, name) in TESTS:
if isinstance(value, test):
return name
return | Get the string title for a particular type.
Given a value, get an appropriate string title for the type that can
be used to re-cast the value later. |
10,211 | def is_valid_intensity_measure_types(self):
if self.ground_motion_correlation_model:
for imt in self.imtls:
if not (imt.startswith() or imt == ):
raise ValueError(
% (
self.ground_motion_correlation_mod... | If the IMTs and levels are extracted from the risk models,
they must not be set directly. Moreover, if
`intensity_measure_types_and_levels` is set directly,
`intensity_measure_types` must not be set. |
10,212 | def get_iam_policy(self):
instance_admin_client = self._client.instance_admin_client
resp = instance_admin_client.get_iam_policy(resource=self.name)
return Policy.from_pb(resp) | Gets the access control policy for an instance resource.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_get_iam_policy]
:end-before: [END bigtable_get_iam_policy]
:rtype: :class:`google.cloud.bigtable.policy.Policy`
:returns: The cur... |
10,213 | def reorder(self, indices: mx.nd.NDArray) -> None:
if self.global_avoid_states:
self.global_avoid_states = [self.global_avoid_states[x] for x in indices.asnumpy()]
if self.local_avoid_states:
self.local_avoid_states = [self.local_avoid_states[x] for x in indices.asnumpy... | Reorders the avoid list according to the selected row indices.
This can produce duplicates, but this is fixed if state changes occur in consume().
:param indices: An mx.nd.NDArray containing indices of hypotheses to select. |
10,214 | def create(container, portal_type, *args, **kwargs):
from bika.lims.utils import tmpID
if kwargs.get("title") is None:
kwargs["title"] = "New {}".format(portal_type)
tmp_id = tmpID()
types_tool = get_tool("portal_types")
fti = types_tool.getTypeInfo(portal_type)
if fti.... | Creates an object in Bika LIMS
This code uses most of the parts from the TypesTool
see: `Products.CMFCore.TypesTool._constructInstance`
:param container: container
:type container: ATContentType/DexterityContentType/CatalogBrain
:param portal_type: The portal type to create, e.g. "Client"
:typ... |
10,215 | def comments(self):
import math
from .author import Author, ANONYMOUS
from .comment import Comment
api_url = Get_Answer_Comment_URL.format(self.aid)
page = pages = 1
while page <= pages:
res = self._session.get(api_url + + str(page))
if ... | 获取答案下的所有评论.
:return: 答案下的所有评论,返回生成器
:rtype: Comments.Iterable |
10,216 | def compute_dosage(expec, alt=None):
r
if alt is None:
return expec[..., -1]
try:
return expec[:, alt]
except NotImplementedError:
alt = asarray(alt, int)
return asarray(expec, float)[:, alt] | r""" Compute dosage from allele expectation.
Parameters
----------
expec : array_like
Allele expectations encoded as a samples-by-alleles matrix.
alt : array_like, optional
Alternative allele index. If ``None``, the allele having the minor
allele frequency for the provided ``exp... |
10,217 | def normalize(self, mode="max", value=1):
if mode.lower() == "sum":
factor = np.sum(self.y, axis=0)
elif mode.lower() == "max":
factor = np.max(self.y, axis=0)
else:
raise ValueError("Unsupported normalization mode %s!" % mode)
self.y /= fact... | Normalize the spectrum with respect to the sum of intensity
Args:
mode (str): Normalization mode. Supported modes are "max" (set the
max y value to value, e.g., in XRD patterns), "sum" (set the
sum of y to a value, i.e., like a probability density).
value... |
10,218 | def get_jobs(self, project, **params):
return self._get_json_list(self.JOBS_ENDPOINT, project, **params) | Gets jobs from project, filtered by parameters
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results |
10,219 | def score_cosine(self, term1, term2, **kwargs):
t1_kde = self.kde(term1, **kwargs)
t2_kde = self.kde(term2, **kwargs)
return 1-distance.cosine(t1_kde, t2_kde) | Compute a weighting score based on the cosine distance between the
kernel density estimates of two terms.
Args:
term1 (str)
term2 (str)
Returns: float |
10,220 | def get_config_path():
if os.environ.get(BUGWARRIORRC):
return os.environ[BUGWARRIORRC]
xdg_config_home = (
os.environ.get() or os.path.expanduser())
xdg_config_dirs = (
(os.environ.get() or ).split())
paths = [
os.path.join(xdg_config_home, , ),
os.path.expa... | Determine the path to the config file. This will return, in this order of
precedence:
- the value of $BUGWARRIORRC if set
- $XDG_CONFIG_HOME/bugwarrior/bugwarriorc if exists
- ~/.bugwarriorrc if exists
- <dir>/bugwarrior/bugwarriorc if exists, for dir in $XDG_CONFIG_DIRS
- $XDG_CONFIG_HOME/bugwa... |
10,221 | def get_limits(self):
if not self.limits:
self.limits = {}
for item in [self.MAX_RRSETS_BY_ZONE,
self.MAX_VPCS_ASSOCIATED_BY_ZONE]:
self.limits[item["name"]] = AwsLimit(
item["name"],
self,
... | Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
Limits from:
docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict |
10,222 | def _pos(self, k):
if k < 2:
raise ValueError("k smaller than 2")
G = np.zeros((self.m, self.m))
for i in range(self.m):
for j in range(self.m):
if i == j:
continue
if i < k or j < k:
... | Description:
Position k breaking
Parameters:
k: position k is used for the breaking |
10,223 | def __xd_iterator_pass_on(arr, view, fun):
iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)]
passon = None
for indices in itertools.product(*iterations):
slicer = [slice(None) if idx is None else slice(idx, idx + 1) for idx in indic... | Like xd_iterator, but the fun return values are always passed on to the next and only the last returned. |
10,224 | def register_producer(cls, producer):
log.info(
.format(producer.__class__.__name__))
cls._producer = (cls._producer or producer) | Register a default producer for events to use.
:param producer: the default producer to to dispatch events on. |
10,225 | def get_trending_daily_not_starred(self):
trending_daily = self.get_trending_daily()
starred_repos = self.get_starred_repos()
repos_list = []
for repo in trending_daily:
if repo not in starred_repos:
repos_list.append(repo)
return repos_... | Gets trending repositories NOT starred by user
:return: List of daily-trending repositories which are not starred |
10,226 | def check_token(token):
user = models.User.objects(api_key=token).first()
return user or None | Verify http header token authentification |
10,227 | def loginfo(logger, msg, *args, **kwargs):
if esgfpid.defaults.LOG_INFO_TO_DEBUG:
logger.debug(msg, *args, **kwargs)
else:
logger.info(msg, *args, **kwargs) | Logs messages as INFO,
unless esgfpid.defaults.LOG_INFO_TO_DEBUG,
(then it logs messages as DEBUG). |
10,228 | def yield_figs(self, **kwargs):
yield self.plot_densities(title="PAW densities", show=False)
yield self.plot_waves(title="PAW waves", show=False)
yield self.plot_projectors(title="PAW projectors", show=False) | This function *generates* a predefined list of matplotlib figures with minimal input from the user. |
10,229 | def _get_tree_properties(root):
is_descending = True
is_ascending = True
min_node_value = root.value
max_node_value = root.value
size = 0
leaf_count = 0
min_leaf_depth = 0
max_leaf_depth = -1
is_strict = True
is_complete = True
current_nodes = [root]
non_full_node_se... | Inspect the binary tree and return its properties (e.g. height).
:param root: Root node of the binary tree.
:rtype: binarytree.Node
:return: Binary tree properties.
:rtype: dict |
10,230 | def embed(self, rel, other, wrap=False):
if other == self:
return
embedded = self.o.setdefault(EMBEDDED_KEY, {})
collected_embedded = CanonicalRels(embedded,
self.curies,
self.base_uri)
... | Embeds a document inside this document.
Arguments:
- ``rel``: a string specifying the link relationship type of the
embedded resource. ``rel`` should be a well-known link relation name
from the IANA registry
(http://www.iana.org/assignments/link-relations/link-relations.x... |
10,231 | def config(self, kw=None, **kwargs):
themebg = kwargs.pop("themebg", self._themebg)
toplevel = kwargs.pop("toplevel", self._toplevel)
theme = kwargs.pop("theme", self.current_theme)
color = self._get_bg_color()
if themebg != self._themebg:
if themebg is False... | configure redirect to support additional options |
10,232 | def CopyRecord(record, **field_overrides):
fields = field_overrides
for field in record.__slots__:
if field in field_overrides:
continue
value = getattr(record, field)
if isinstance(value, RecordClass):
new_value = CopyRecord(value)
else... | Copies a record and its fields, recurses for any field that is a Record.
For records that have nested mutable fields, use copy.deepcopy.
Args:
record: A Record instance to be copied.
**field_overrides: Fields and their values to override in the new copy.
Returns: A copy of the given r... |
10,233 | def get_child_bin_ids(self, bin_id):
if self._catalog_session is not None:
return self._catalog_session.get_child_catalog_ids(catalog_id=bin_id)
return self._hierarchy_session.get_children(id_=bin_id) | Gets the child ``Ids`` of the given bin.
arg: bin_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bin
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
raise: OperationFailed - unable to complete request... |
10,234 | def table(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
tableSources = self.sourceResults.table(
filepath=dirPath + "/" + p + "sources.ascii")
tablePhot = self.photResults.table(
filepath=dirPath + ... | *Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
- `tablePhot` -- all photometry associated with the tran... |
10,235 | def fmt_repr(obj):
items = ["%s = %r" % (k, v) for k, v in list(exclude_fields(obj).items())]
return "<%s: {%s}>" % (obj.__class__.__name__, .join(items)) | Print a orphaned string representation of an object without the
clutter of its parent object. |
10,236 | def _shape_text(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments=):
assert colsep != rowsep
out = []
text_rows = text.split(rowsep)[skiprows:]
for row in text_rows:
stripped = to_text_string(row).strip()
... | Decode the shape of the given text |
10,237 | def open_resource(self, filename, mode=):
assert self.current_run is not None, "Can only be called during a run."
return self.current_run.open_resource(filename, mode) | Open a file and also save it as a resource.
Opens a file, reports it to the observers as a resource, and returns
the opened file.
In Sacred terminology a resource is a file that the experiment needed
to access during a run. In case of a MongoObserver that means making
sure the ... |
10,238 | def argmin(self, values):
keys, minima = self.min(values)
minima = minima[self.inverse]
index = as_index((self.inverse, values == minima))
return keys, index.sorter[index.start[-self.groups:]] | return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmin : ndarray, ... |
10,239 | def _validate(self):
if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ):
raise UnpackException
return | Assure this is a valid VLAN header instance. |
10,240 | def answering_questions(self, attempt, validation_token, quiz_submission_id, access_code=None, quiz_questions=None):
path = {}
data = {}
params = {}
path["quiz_submission_id"] = quiz_submission_id
data["attempt"] = attempt
... | Answering questions.
Provide or update an answer to one or more QuizQuestions. |
10,241 | def session_from_client_config(client_config, scopes, **kwargs):
if in client_config:
config = client_config[]
elif in client_config:
config = client_config[]
else:
raise ValueError(
)
if not _REQUIRED_CONFIG_KEYS.issubset(config.keys()):
raise ValueE... | Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Google `client secrets`_ format.
scopes (Sequence[str]): The list of scopes to reque... |
10,242 | def is_checked(self) -> bool:
if not self.redis_key_checked:
return False
value = self._red.get(self.redis_key_checked)
if not value:
return False
return True | One task ran (checked). |
10,243 | def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
if service_type == ServiceTypes.ASSET_ACCESS:
name =
elif service_type == ServiceTypes.CLOUD_COMPUTE:
name =
elif service_type == ServiceTypes.FITCHAIN_COMPUTE:
name =
else:
raise ValueError(f)
... | Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str |
10,244 | def get_aside(self, aside_usage_id):
aside_type = self.id_reader.get_aside_type_from_usage(aside_usage_id)
xblock_usage = self.id_reader.get_usage_id_from_aside(aside_usage_id)
xblock_def = self.id_reader.get_definition_id(xblock_usage)
aside_def_id, aside_usage_id = self.id_gen... | Create an XBlockAside in this runtime.
The `aside_usage_id` is used to find the Aside class and data. |
10,245 | def unstash_index(self, sync=False, branch=None):
stash_list = self.git_exec([, ], no_verbose=True)
if branch is None:
branch = self.get_current_branch_name()
for stash in stash_list.splitlines():
verb = if sync else
if (
(( in ... | Returns an unstash index if one is available. |
10,246 | def flush_headers(self, sync: bool = False) -> None:
if self._headers_sent:
return
self._headers_sent = True
self.handel_default()
self.write(
b"HTTP/%s %d %s\r\n" % (
encode_str(self._version),
self._status,
... | 通过异步写入 header |
10,247 | def runSearchRnaQuantificationSets(self, request):
return self.runSearchRequest(
request, protocol.SearchRnaQuantificationSetsRequest,
protocol.SearchRnaQuantificationSetsResponse,
self.rnaQuantificationSetsGenerator) | Returns a SearchRnaQuantificationSetsResponse for the specified
SearchRnaQuantificationSetsRequest object. |
10,248 | def scaffold_hits(searches, fasta, max_hits):
scaffolds = {}
for seq in parse_fasta(fasta):
scaffold = seq[0].split()[0].split(, 1)[1].rsplit(, 1)[0]
if scaffold not in scaffolds:
scaffolds[scaffold] = 0
scaffolds[scaffold] += 1
s2rp = {s: {r[0]: []
... | get hits from each search against each RP
scaffolds[scaffold] = # ORfs
s2rp[scaffold] = {rp:[hits]} |
10,249 | def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP):
if title_prefix is None:
title_prefix = [None]
filter_dicts = []
model_list = []
if isinstance(title_prefix, basestring):
title_prefix = title_prefix.split()
elif not isinstance(title_pre... | Return a list of Querysets from a list of model numbers |
10,250 | def iodp_kly4s_lore(kly4s_file, meas_out=,
spec_infile=, spec_out=, instrument=,
actual_volume="",dir_path=, input_dir_path=):
version_num = pmag.get_version()
input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
meas_reqd_columns=[,,,,,... | Converts ascii files generated by SUFAR ver.4.0 and downloaded from the LIMS online
repository to MagIC (datamodel 3) files
Parameters
----------
kly4s_file : str
input LORE downloaded csv file, required
meas_output : str
measurement output filename, default "measurements.txt"
s... |
10,251 | def list(self):
url = "api/v0002/mgmt/custom/bundle"
r = self._apiClient.get(url)
if r.status_code == 200:
return r.json()
else:
raise ApiException(r) | List all device management extension packages |
10,252 | def sort_response(response: Dict[str, Any]) -> OrderedDict:
root_order = ["jsonrpc", "result", "error", "id"]
error_order = ["code", "message", "data"]
req = OrderedDict(sorted(response.items(), key=lambda k: root_order.index(k[0])))
if "error" in response:
req["error"] = OrderedDict(
... | Sort the keys in a JSON-RPC response object.
This has no effect other than making it nicer to read. Useful in Python 3.5 only,
dictionaries are already sorted in newer Python versions.
Example::
>>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'}))
{"jsonrpc": "2.0", "re... |
10,253 | def register_handler(self, name, handler, esc_strings):
self._handlers[name] = handler
for esc_str in esc_strings:
self._esc_handlers[esc_str] = handler | Register a handler instance by name with esc_strings. |
10,254 | def finalize(self, process_row = None):
if process_row is not None:
process_id = process_row.process_id
elif self.process is not None:
process_id = self.process.process_id
else:
raise ValueError("must supply a process row to .__init__()")
self.segment_def_table.sync_next_id()
self.segme... | Restore the LigolwSegmentList objects to the XML tables in
preparation for output. All segments from all segment
lists are inserted into the tables in time order, but this
is NOT behaviour external applications should rely on.
This is done simply in the belief that it might assist in
constructing well balanc... |
10,255 | def delete(queue, items):
con = _conn(queue)
with con:
cur = con.cursor()
if isinstance(items, six.string_types):
items = _quote_escape(items)
cmd = .format(queue, items)
log.debug(, cmd)
cur.execute(cmd)
return True
if isi... | Delete an item or items from a queue |
10,256 | def rasterize(path,
pitch,
origin,
resolution=None,
fill=True,
width=None):
pitch = float(pitch)
origin = np.asanyarray(origin, dtype=np.float64)
if resolution is None:
span = np.vstack((path.bounds,
... | Rasterize a Path2D object into a boolean image ("mode 1").
Parameters
------------
path: Path2D object
pitch: float, length in model space of a pixel edge
origin: (2,) float, origin position in model space
resolution: (2,) int, resolution in pixel space
fill: bool, if T... |
10,257 | def remove_import_statements(code):
new_code = []
for line in code.splitlines():
if not line.lstrip().startswith() and \
not line.lstrip().startswith():
new_code.append(line)
while new_code and new_code[0] == :
new_code.pop(0)
while new_code and new_code[-1] ... | Removes lines with import statements from the code.
Args:
code: The code to be stripped.
Returns:
The code without import statements. |
10,258 | def config_stop(args):
r = fapi.abort_submission(args.project, args.workspace,
args.submission_id)
fapi._check_response_code(r, 204)
return ("Aborted {0} in {1}/{2}".format(args.submission_id,
args.project,
... | Abort a task (method configuration) by submission ID in given space |
10,259 | def getprop(self, prop_name):
return self.shell(
[, prop_name],
timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode().strip() | Get a property of the device.
This is a convenience wrapper for "adb shell getprop xxx".
Args:
prop_name: A string that is the name of the property to get.
Returns:
A string that is the value of the property, or None if the property
doesn't exist. |
10,260 | def parse_if(self):
node = result = nodes.If(lineno=self.stream.expect().lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements((, ,
))
node.elif_ = []
no... | Parse an if construct. |
10,261 | def camel_to_underscore(string):
string = FIRST_CAP_RE.sub(r, string)
return ALL_CAP_RE.sub(r, string).lower() | Convert camelcase to lowercase and underscore.
Recipe from http://stackoverflow.com/a/1176023
Args:
string (str): The string to convert.
Returns:
str: The converted string. |
10,262 | def json_as_html(self):
from cspreports import utils
formatted_json = utils.format_report(self.json)
return mark_safe("<pre>\n%s</pre>" % escape(formatted_json)) | Print out self.json in a nice way. |
10,263 | def as_dict(self, verbosity=1, fmt=None, **kwargs):
if fmt == "abivars":
from pymatgen.io.abinit.abiobjects import structure_to_abivars
return structure_to_abivars(self, **kwargs)
latt_dict = self._lattice.as_dict(verbosity=verbosity)
del latt_dict[... | Dict representation of Structure.
Args:
verbosity (int): Verbosity level. Default of 1 includes both
direct and cartesian coordinates for all sites, lattice
parameters, etc. Useful for reading and for insertion into a
database. Set to 0 for an extreme... |
10,264 | def set_plugins(self, input_plugins):
header = "glances_"
for item in input_plugins:
try:
plugin = __import__(header + item)
except ImportError:
logger.error("Can not import {} plugin. Please upgrade your Glan... | Set the plugin list according to the Glances server. |
10,265 | def greenhall_sx(t, F, alpha):
if F == float():
return greenhall_sw(t, alpha+2)
a = 2*greenhall_sw(t, alpha)
b = greenhall_sw(t-1.0/float(F), alpha)
c = greenhall_sw(t+1.0/float(F), alpha)
return pow(F, 2)*(a-b-c) | Eqn (8) from Greenhall2004 |
10,266 | def _get_images_dir():
img_dir = __salt__[]()
if img_dir:
salt.utils.versions.warn_until(
,
virt.images\
virt:images\virt.images\
)
else:
img_dir = __salt__[]()
log.debug(
, img_dir)
return img_dir | Extract the images dir from the configuration. First attempts to
find legacy virt.images, then tries virt:images. |
10,267 | def configure(conf, channel=False, group=False, fm_integration=False):
conf = expanduser(conf) if conf else get_config_path()
prompt = "❯ " if not sys.platform.startswith("win32") else "> "
contact_url = "https://telegram.me/"
print("Talk with the {} on Telegram ({}), create a bot and insert the t... | Guide user to set up the bot, saves configuration at `conf`.
# Arguments
conf (str): Path where to save the configuration file. May contain `~` for
user's home.
channel (Optional[bool]): Configure a channel.
group (Optional[bool]): Configure a group.
fm_integration (Optional[bool])... |
10,268 | def gen_batch(data, batch_size, maxiter=np.inf, random_state=None):
perms = endless_permutations(_len_data(data), random_state)
it = 0
while it < maxiter:
it += 1
ind = np.array([next(perms) for _ in range(batch_size)])
yield _split_data(data, ind) | Create random batches for Stochastic gradients.
Batch index generator for SGD that will yeild random batches for a
a defined number of iterations, which can be infinite. This generator makes
consecutive passes through the data, drawing without replacement on each
pass.
Parameters
----------
... |
10,269 | def get_file(profile, branch, file_path):
branch_sha = get_branch_sha(profile, branch)
tree = get_files_in_branch(profile, branch_sha)
match = None
for item in tree:
if item.get("path") == file_path:
match = item
break
file_sha = match.get("sha")
blob = blobs... | Get a file from a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of a branch.
fi... |
10,270 | def bfs_conditional(G, source, reverse=False, keys=True, data=False,
yield_nodes=True, yield_if=None,
continue_if=None, visited_nodes=None,
yield_source=False):
if reverse and hasattr(G, ):
G = G.reverse()
if isinstance(G, nx.Graph):
... | Produce edges in a breadth-first-search starting at source, but only return
nodes that satisfiy a condition, and only iterate past a node if it
satisfies a different condition.
conditions are callables that take (G, child, edge) and return true or false
CommandLine:
python -m utool.util_graph ... |
10,271 | def set_home_location(self):
try:
latlon = self.module().click_position
except Exception:
print("No map available")
return
lat = float(latlon[0])
lon = float(latlon[1])
if self.wploader.count() == 0:
self.wploader.add_latlo... | set home location from last map click |
10,272 | def post(ctx, uri, input_file):
http_client = get_wva(ctx).get_http_client()
cli_pprint(http_client.post(uri, input_file.read())) | POST file data to a specific URI
Note that POST is not used for most web services URIs. Instead,
PUT is used for creating resources. |
10,273 | def make_password(password, salt=None, hasher=):
if password is None:
return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
hasher = bCryptPasswordHasher
if not salt:
salt = hasher.salt()
return hasher.encode(password, salt) | Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string reduces chances of gaining
access to staff or sup... |
10,274 | def deactivate(self):
remove_builtin = self.remove_builtin
for key, val in self._orig_builtins.iteritems():
remove_builtin(key, val)
self._orig_builtins.clear()
self._builtins_added = False | Remove any builtins which might have been added by add_builtins, or
restore overwritten ones to their previous values. |
10,275 | def switch_led_on(self, ids):
self._set_LED(dict(zip(ids, itertools.repeat(True)))) | Switches on the LED of the motors with the specified ids. |
10,276 | def azureContainerSAS(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["azureContainerSAS"], *args, **kwargs) | Get Shared-Access-Signature for Azure Container
Get a shared access signature (SAS) string for use with a specific Azure
Blob Storage container.
The `level` parameter can be `read-write` or `read-only` and determines
which type of credentials are returned. If level is read-write, it w... |
10,277 | def container_fs_usage_bytes(self, metric, scraper_config):
metric_name = scraper_config[] +
if metric.type not in METRIC_TYPES:
self.log.error("Metric type %s unsupported for metric %s" % (metric.type, metric.name))
return
self._process_usage_metric(metric_name... | Number of bytes that are consumed by the container on this filesystem. |
10,278 | def start(self):
self._current_session = session = self._http_client.session()
request = self.next_request()
assert request
if request.url_info.password or \
request.url_info.hostname_with_port in self._hostnames_with_auth:
self._add_basic_auth_head... | Begin fetching the next request. |
10,279 | def _fill(self):
try:
self._head = self._iterable.next()
except StopIteration:
self._head = None | Advance the iterator without returning the old head. |
10,280 | def evaluate(self, item):
try:
for match in PATH_PATTERN.finditer(self.field):
path = match.group(0)
if path[0] == "[":
try:
item = item[int(match.group(1))]
except IndexErro... | Pull the field off the item |
10,281 | def check_tag_data(data):
"Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag."
if len(data) < 10:
raise ValueError("Tag too short")
if data[0:3] != b"ID3":
raise ValueError("Missing ID3 identifier")
if data[3] >= 5 or data[4] != 0:
raise ValueError("Unknown ID3 ... | Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag. |
10,282 | def experiment_group_post_delete(sender, **kwargs):
instance = kwargs[]
auditor.record(event_type=EXPERIMENT_GROUP_DELETED, instance=instance)
remove_bookmarks(object_id=instance.id, content_type=) | Delete all group outputs. |
10,283 | def _make_resource(self):
with self._lock:
for i in self._unavailable_range():
if self._reference_queue[i] is None:
rtracker = _ResourceTracker(
self._factory(**self._factory_arguments))
self._reference_queue[i... | Returns a resource instance. |
10,284 | def get_internal_instances(self, phase=None):
if phase is None:
return [instance for instance in self.instances if not instance.is_external]
return [instance for instance in self.instances
if not instance.is_external and phase in instance.phases and
... | Get a list of internal instances (in a specific phase)
If phase is None, return all internal instances whtever the phase
:param phase: phase to filter (never used)
:type phase:
:return: internal instances list
:rtype: list |
10,285 | def _get_template_dirs():
return filter(lambda x: os.path.exists(x), [
os.path.join(os.path.expanduser(), , ),
os.path.join(, , , , ),
os.path.join(os.path.dirname(os.path.abspath(__file__)), ),
]) | existing directories where to search for jinja2 templates. The order
is important. The first found template from the first found dir wins! |
10,286 | def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) :
loc = location + "/datawraps.json"
response = urllib2.urlopen(loc)
js = json.loads(response.read())
return js | Lists all the datawraps availabe from a remote a remote location. |
10,287 | def _load_data(self, band):
df = bandpass_data_frame( + band + , )
df.resp *= df.wlen
return df | From Morrissey+ 2005, with the actual data coming from
http://www.astro.caltech.edu/~capak/filters/. According to the latter,
these are in QE units and thus need to be multiplied by the wavelength
when integrating per-energy. |
10,288 | def delete_all_objects(self, async_=False):
nms = self.list_object_names(full_listing=True)
return self.object_manager.delete_all_objects(nms, async_=async_) | Deletes all objects from this container.
By default the call will block until all objects have been deleted. By
passing True for the 'async_' parameter, this method will not block, and
instead return an object that can be used to follow the progress of the
deletion. When deletion is com... |
10,289 | def disclaim_key_flags():
globals_for_caller = sys._getframe(1).f_globals
module, _ = _helpers.get_module_object_and_name(globals_for_caller)
_helpers.disclaim_module_ids.add(id(module)) | Declares that the current module will not define any more key flags.
Normally, the module that calls the DEFINE_xxx functions claims the
flag to be its key flag. This is undesirable for modules that
define additional DEFINE_yyy functions with its own flag parsers and
serializers, since that module will accide... |
10,290 | def find_replace_string(obj, find, replace):
try:
strobj = str(obj)
newStr = string.replace(strobj, find, replace)
if newStr == strobj:
return obj
else:
return newStr
except:
line, filename, synerror = trace()
raise ArcRestHelperErro... | Performs a string.replace() on the input object.
Args:
obj (object): The object to find/replace. It will be cast to ``str``.
find (str): The string to search for.
replace (str): The string to replace with.
Returns:
str: The replaced string. |
10,291 | def _processJobsWithRunningServices(self):
while True:
jobGraph = self.serviceManager.getJobGraphWhoseServicesAreRunning(0)
if jobGraph is None:
break
logger.debug(, jobGraph.jobStoreID)
jobGraph.services = []
self.toilState.u... | Get jobs whose services have started |
10,292 | def get_random_url(ltd="com"):
url = [
"https://",
RandomInputHelper.get_random_value(8, [string.ascii_lowercase]),
".",
ltd
]
return "".join(url) | Get a random url with the given ltd.
Args:
ltd (str): The ltd to use (e.g. com).
Returns:
str: The random url. |
10,293 | def get(self, project):
try:
data = self.request(project + )
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
raise Exception("Unable to retrieve CLAM Data")
else:
return data | Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code |
10,294 | def pixy_set_servos(self, s0, s1):
task = asyncio.ensure_future(self.core.pixy_set_servos(s0, s1))
self.loop.run_until_complete(task) | Sends the setServos Pixy command.
This method sets the pan/tilt servos that are plugged into Pixy's two servo ports.
:param s0: value 0 to 1000
:param s1: value 0 to 1000
:returns: No return value. |
10,295 | def qteMacroNameMangling(self, macroCls):
macroName = re.sub(r"([A-Z])", r, macroCls.__name__)
if macroName[0] == :
macroName = macroName[1:]
return macroName.lower() | Convert the class name of a macro class to macro name.
The name mangling inserts a '-' character after every capital
letter and then lowers the entire string.
Example: if the class name of ``macroCls`` is 'ThisIsAMacro'
then this method will return 'this-is-a-macro', ie. every
... |
10,296 | def run(cmd, stdout=None, stderr=None, **kwargs):
devnull = None
try:
stdoutfilter = None
stderrfilter = None
wantstdout = False
wantstderr = False
if stdout is False:
devnull = open(, )
stdout = devnull
elif stdout is True:
... | A blocking wrapper around subprocess.Popen(), but with a simpler interface
for the stdout/stderr arguments:
stdout=False / stderr=False
stdout/stderr will be redirected to /dev/null (or discarded in some
other suitable manner)
stdout=True / stderr=True
stdout/stderr will be captured... |
10,297 | def bind(self, cube):
if self.measure:
table, column = self.measure.bind(cube)
else:
table, column = cube.fact_table, cube.fact_pk
column = getattr(func, self.function)(column)
column = column.label(self.ref)
column.quote = True
r... | When one column needs to match, use the key. |
10,298 | def get_data(self, url=,headers={}, date=str(datetime.date.today()),
dict_to_store={}, type=, repo_name=):
url = (url + + type)
r3 = requests.get(url, headers=headers)
json = r3.json()
if type == :
self.views_json[repo_name] = json
elif type... | Retrieves data from json and stores it in the supplied dict. Accepts
'clones' or 'views' as type. |
10,299 | def concat(objs, axis=0, join=, join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
sort=None, copy=True):
op = _Concatenator(objs, axis=axis, join_axes=join_axes,
ignore_index=ignore_index, join=join,
... | Concatenate pandas objects along a particular axis with optional set logic
along the other axes.
Can also add a layer of hierarchical indexing on the concatenation axis,
which may be useful if the labels are the same (or overlapping) on
the passed axis number.
Parameters
----------
objs : ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.