Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
11,000 | def _check_and_send(self):
if self.transport._stop_event.ready() or not self.transport.greenlet:
self.log.error("CanRetrying messagePartner not reachable. Skipping.fixedStopping message send retryRaiden queue is goneStopping message send retryMessage was removed from queueSend\n'.join(messa... | Check and send all pending/queued messages that are not waiting on retry timeout
After composing the to-be-sent message, also message queue from messages that are not
present in the respective SendMessageEvent queue anymore |
11,001 | def labels(self, *labelvalues, **labelkwargs):
if not self._labelnames:
raise ValueError( % self)
if self._labelvalues:
raise ValueError( % (
self,
dict(zip(self._labelnames, self._labelvalues))
))
if labelvalues and ... | Return the child for the given labelset.
All metrics can have labels, allowing grouping of related time series.
Taking a counter as an example:
from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels(... |
11,002 | def get_self_uri(self, content_type):
"return the first self uri with the content_type"
try:
return [self_uri for self_uri in self.self_uri_list
if self_uri.content_type == content_type][0]
except IndexError:
return None | return the first self uri with the content_type |
11,003 | def infer_delimiter(filename, comment_char="
lines = []
with open(filename, "r") as f:
for line in f:
if line.startswith(comment_char):
continue
if len(lines) < n_lines:
lines.append(line)
else:
break
if len(lin... | Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents. |
11,004 | def child_task(self):
from MAVProxy.modules.lib import mp_util
import wx_processguard
from wx_loader import wx
from wxsettings_ui import SettingsDlg
mp_util.child_close_fds()
app = wx.App(False)
dlg = SettingsDlg(self.settings)
dlg.parent... | child process - this holds all the GUI elements |
11,005 | def indirect(self, interface):
if interface == IWebViewer:
return _AnonymousWebViewer(self.store)
return super(AnonymousSite, self).indirect(interface) | Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. |
11,006 | def p_func_args(self, p):
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | func_args : func_args COMMA expression |
11,007 | def admin_view_reverse_fk_links(modeladmin: ModelAdmin,
obj,
reverse_fk_set_field: str,
missing: str = "(None)",
use_str: bool = True,
separator: str = "<br>",
... | Get multiple Django admin site URL for multiple objects linked to our
object of interest (where the other objects have foreign keys to our
object). |
11,008 | def bugreport(dest_file="default.log"):
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT]
try:
dest_file_handler = open(dest_file, "w")
except IOError:
print("IOError: Failed to create a log file")
if _isDeviceAvailable():
result = _exec... | Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting
:return: result of _exec_command() execution |
11,009 | def pass_session_attributes(self):
for key, value in six.iteritems(self.request.session.attributes):
self.response.sessionAttributes[key] = value | Copies request attributes to response |
11,010 | def mimeData(self, items):
func = self.dataCollector()
if func:
return func(self, items)
record_items = []
for item in self.selectedItems():
if isinstance(item, XOrbRecordItem):
record_items.append(item)
... | Returns the mime data for dragging for this instance.
:param items | [<QTreeWidgetItem>, ..] |
11,011 | def dlogprior(self, param):
assert param in self.freeparams, "Invalid param: {0}".format(param)
return self._dlogprior[param] | Value of derivative of prior depends on value of `prior`. |
11,012 | def get_authinfo(request):
if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)):
return False
iv = base64.b64decode(request.session["files_iv"])
text = base64.b64decode(request.session["files_text"])
key = base64.b64... | Get authentication info from the encrypted message. |
11,013 | def upload_logs(self, release_singleton=True):
if release_singleton:
self.release_singleton()
def _upload():
for log in self.get_logs():
new_name = self._uniquename(log)
self._upload(log, new_name)
self.de... | uploads a log to a server using the method and gui specifed
in self.pcfg
singleton mode can be disabled so a new version can be restarted whille uploading oges
on typicallin in the case of uploadnig after a crash or sys exit
set self.cfg log_upload_interface to gui/cli/or background |
11,014 | def txt(self, diff, f):
env = Environment(
loader=PackageLoader(, ),
trim_blocks=True,
lstrip_blocks=True
)
template = env.get_template()
def format_row(label, values):
change = format_comma(values[])
percent_change =... | Generate a text report for a diff. |
11,015 | def check_token(func):
@wraps(func)
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
if response.status_code == 401:
raise InvalidToken()
else:
return response
return wrapper | 检查 access token 是否有效. |
11,016 | def checkInfo(email=None, username=None, api_key=None):
if api_key==None:
allKeys = config_api_keys.returnListOfAPIKeys()
try:
api_key = allKeys["pipl_com"]
except:
api_key = "samplekey"
results = {}
results["perso... | Method that checks if the given hash is stored in the pipl.com website.
:param email: queries to be launched.
:param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py file.
:return: Python structure for the Json received. It ha... |
11,017 | def values(self):
return [
_ColumnPairwiseSignificance(
self._slice,
col_idx,
self._axis,
self._weighted,
self._alpha,
self._only_larger,
self._hs_dims,
... | list of _ColumnPairwiseSignificance tests.
Result has as many elements as there are coliumns in the slice. Each
significance test contains `p_vals` and `t_stats` significance tests. |
11,018 | def token_view(token):
if request.method == "POST" and in request.form:
db.session.delete(token)
db.session.commit()
return redirect(url_for())
show_token = session.pop(, False)
form = TokenForm(request.form, name=token.client.name, scopes=token.scopes)
form.scopes.choice... | Show token details. |
11,019 | def community_post_comments(self, post_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/post_comments
api_path = "/api/v2/community/posts/{post_id}/comments.json"
api_path = api_path.format(post_id=post_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/post_comments#list-comments |
11,020 | def set_contrast(self, contrast):
self._contrast = contrast
self.x_spread = 2 * (1.0 - contrast)
self.y_spread = 2.0 - 2 * (1.0 - contrast)
self._build_cdict() | Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A numbe... |
11,021 | def dispense(self):
self.sendcommand(Vendapin.DISPENSE)
time.sleep(1)
response = self.receivepacket()
print( + str(response))
if not self.was_packet_accepted(response):
raise Exception( + str(response))
return self.parsedata(response... | dispense a card if ready, otherwise throw an Exception |
11,022 | def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char=, **kwargs):
clean_str = re.sub(r.format(
"".join(exclusion)), separate_char, text.strip()) or
clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)
if not in exclusion:
clean_lowerbar = re... | Clean text string of simbols only alphanumeric chars. |
11,023 | def unpack_rawr_zip_payload(table_sources, payload):
data = zfh.open(table_name, ).read()
unpacker = Unpacker(file_like=BytesIO(data))
source = table_sources[table_name]
return Table(source, unpacker)
return get_table | unpack a zipfile and turn it into a callable "tables" object. |
11,024 | def init(envVarName, enableColorOutput=False):
global _initialized
if _initialized:
return
global _ENV_VAR_NAME
_ENV_VAR_NAME = envVarName
if enableColorOutput:
_preformatLevels(envVarName + "_NO_COLOR")
else:
_preformatLevels(None)
if envVarName in os.enviro... | Initialize the logging system and parse the environment variable
of the given name.
Needs to be called before starting the actual application. |
11,025 | def create_app(app_id, app_name, source_id, region, app_data):
try:
create_at = datetime.datetime.now().strftime()
conn = get_conn()
c = conn.cursor()
c.execute("SELECT count(*) FROM app WHERE name= ".format(app_name))
old_app = c.fetchone()
if old_app[... | insert app record when stack run as a app |
11,026 | def add_semantic_data(self, path_as_list, value, key):
assert isinstance(key, string_types)
target_dict = self.get_semantic_data(path_as_list)
target_dict[key] = value
return path_as_list + [key] | Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return: |
11,027 | def evolve_genomes(rng, pop, params, recorder=None):
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
params.validate()
from ._fwdpy11 import MutationRegions
from ._fwdpy11 import evolve_without_tree_sequences
from ._fwdpy11 import d... | Evolve a population without tree sequence recordings. In other words,
complete genomes must be simulated and tracked.
:param rng: random number generator
:type rng: :class:`fwdpy11.GSLrng`
:param pop: A population
:type pop: :class:`fwdpy11.DiploidPopulation`
:param params: simulation paramete... |
11,028 | def Parse(self):
for data in self.Query(self.EVENTS_QUERY):
(timestamp, agent_bundle_identifier, agent_name, url, sender,
sender_address, type_number, title, referrer, referrer_alias) = data
yield [
timestamp, "OSX_QUARANTINE", url, referrer, title, agent_name,
agent_bund... | Iterator returning dict for each entry in history. |
11,029 | def tops(opts):
if not in opts:
return {}
whitelist = list(opts[].keys())
ret = LazyLoader(
_module_dirs(opts, , ),
opts,
tag=,
whitelist=whitelist,
)
return FilterDictWrapper(ret, ) | Returns the tops modules |
11,030 | def _init_os_api(self):
if not self.nova_client:
log.debug("Initializing OpenStack API clients:"
" OS_AUTH_URL="
" OS_USERNAME="
" OS_USER_DOMAIN_NAME="
" OS_PROJECT_NAME="
" OS_PRO... | Initialise client objects for talking to OpenStack API.
This is in a separate function so to be called by ``__init__``
and ``__setstate__``. |
11,031 | def ae_partial_waves(self):
ae_partial_waves = OrderedDict()
for mesh, values, attrib in self._parse_all_radfuncs("ae_partial_wave"):
state = attrib["state"]
ae_partial_waves[state] = RadialFunction(mesh, values)
return ae_partial_waves | Dictionary with the AE partial waves indexed by state. |
11,032 | def rotate(obj, axis, angle, origin=None):
R = _rodrigues_to_dcm(axis, angle)
try:
return obj.transform(PivotRotation(R, origin))
except AttributeError:
raise NotImplementedError | Rotation around unit vector following the right hand rule
Parameters:
obj : obj to be rotated (e.g. neurite, neuron).
Must implement a transform method.
axis : unit vector for the axis of rotation
angle : rotation angle in rads
Returns:
A copy of the object with the... |
11,033 | def next(self):
curr_page = self.currentPage()
if not curr_page:
return
elif not curr_page.validatePage():
return
pageId = curr_page.nextId()
try:
next_page = self._pages[pageId]
except KeyError:
return
se... | Goes to the previous page for this wizard. |
11,034 | def proxy_for(widget):
proxy_type = widget_proxies.get(widget.__class__)
if proxy_type is None:
raise KeyError( % widget)
return proxy_type(widget) | Create a proxy for a Widget
:param widget: A gtk.Widget to proxy
This will raise a KeyError if there is no proxy type registered for the
widget type. |
11,035 | def set_aesthetic(palette="yellowbrick", font="sans-serif", font_scale=1,
color_codes=True, rc=None):
_set_context(font_scale)
set_style(rc={"font.family": font})
set_palette(palette, color_codes=color_codes)
if rc is not None:
mpl.rcParams.update(rc) | Set aesthetic parameters in one step.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
----------
palette : string or sequence
Color palette, see :func:`color_palette`
font : string
Font family, see m... |
11,036 | def run(self, fnames=None):
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
self.sig_run.emit(fname) | Run Python scripts |
11,037 | def _fill_missing_values(df, range_values, fill_value=0, fill_method=None):
idx_colnames = df.index.names
idx_colranges = [range_values[x] for x in idx_colnames]
fullindex = pd.Index([p for p in product(*idx_colranges)],
name=tuple(idx_colnames))
... | Will get the names of the index colums of df, obtain their ranges from
range_values dict and return a reindexed version of df with the given
range values.
:param df: pandas DataFrame
:param range_values: dict or array-like
Must contain for each index column of df an entry with ... |
11,038 | def delete_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_topic_rule(ruleName=ruleName)
return {: True}
except ClientError as e:
return {: False, : __... | Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_rule myrule |
11,039 | def reindex(self, request):
r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"])
try:
with SearchLock(r, timeout=30 * 60, blocking_timeout=30):
p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"])
client = elasticsearch.Elast... | Recreate the Search Index. |
11,040 | def parametrized_class(decorator):
t really do anything, just here to have a central
implementation of the simple class decorator.'
def decorator_builder(*args, **kwargs):
def meta_decorator(cls):
return decorator(cls, *args, **kwargs)
return meta_decorator
return decorat... | Decorator used to make simple class decorator with arguments.
Doesn't really do anything, just here to have a central
implementation of the simple class decorator. |
11,041 | def nodes(self, tree):
if self.frequency == :
nodes = []
for subject in tree.subjects:
for sess in subject.sessions:
nodes.append(sess)
elif self.frequency == :
nodes = tree.subjects
elif self.frequency == ... | Returns the relevant nodes for the spec's frequency |
11,042 | def env(self, key, value=None, unset=False, asap=False):
if unset:
self._set(, key, multi=True)
else:
if value is None:
value = os.environ.get(key)
self._set( % ( if asap else ), % (key, value), multi=True)
return self | Processes (sets/unsets) environment variable.
If is not given in `set` mode value will be taken from current env.
:param str|unicode key:
:param value:
:param bool unset: Whether to unset this variable.
:param bool asap: If True env variable will be set as soon as possible. |
11,043 | def getLinkProperties(self, wanInterfaceId=1, timeout=1):
namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCommonLinkProperties", timeout=timeout)
return WanLinkProperties(r... | Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:rtype: WanLinkProperties |
11,044 | def _instance_callable(obj):
if not isinstance(obj, ClassTypes):
return getattr(obj, , None) is not None
if six.PY3:
for base in (obj,) + obj.__mro__:
if base.__dict__.get() is not None:
return True
else:
klass = obj
... | Given an object, return True if the object is callable.
For classes, return True if instances would be callable. |
11,045 | def register_as_guest(self):
response = self.api.register(auth_body=None, kind=)
return self._post_registration(response) | Register a guest account on this HS.
Note: HS must have guest registration enabled.
Returns:
str: Access Token
Raises:
MatrixRequestError |
11,046 | def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
self.ensure_db_open()
if len(fields) != len(values):
raise Asserti... | Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None). |
11,047 | def _get_inherited_field_types(class_to_field_type_overrides, schema_graph):
inherited_field_type_overrides = dict()
for superclass_name, field_type_overrides in class_to_field_type_overrides.items():
for subclass_name in schema_graph.get_subclass_set(superclass_name):
inherited_field_t... | Return a dictionary describing the field type overrides in subclasses. |
11,048 | def place_objects(self):
pos_arr, quat_arr = self.initializer.sample()
for k, obj_name in enumerate(self.objects):
self.objects[obj_name].set("pos", array_to_string(pos_arr[k]))
self.objects[obj_name].set("quat", array_to_string(quat_arr[k])) | Places objects randomly until no collisions or max iterations hit. |
11,049 | def visit_List(self, node):
if node.elts:
return list(set(sum([self.visit(elt) for elt in node.elts], [])))
else:
return [frozenset()] | List construction depend on each elements type dependency. |
11,050 | def show_batch_runner(self):
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() | Show the batch runner dialog. |
11,051 | def check_no_signature(self, function, docstring):
if docstring:
first_line = ast.literal_eval(docstring).strip().split()[0]
if function.name + in first_line.replace(, ):
return violations.D402() | D402: First line should not be function's or method's "signature".
The one-line docstring should NOT be a "signature" reiterating the
function/method parameters (which can be obtained by introspection). |
11,052 | def init_progress_bar(self):
if disable:
total = None
else:
self.iterable = list(self.iterable)
total = len(self.iterable)
return tqdm(total=total, disable=disable, leave=False,
desc=self.description) | Initialize and return a progress bar. |
11,053 | def spin(self):
try:
spin = self._spin
if spin is not None:
return spin
except AttributeError:
pass
if self.vartype is Vartype.SPIN:
self._spin = spin = self
else:
self._counterpart = ... | :class:`.BinaryQuadraticModel`: An instance of the Ising model subclass
of the :class:`.BinaryQuadraticModel` superclass, corresponding to
a binary quadratic model with spins as its variables.
Enables access to biases for the spin-valued binary quadratic model
regardless of the :class:`... |
11,054 | def to_file(file_):
from sevenbridges.models.file import File
if not file_:
raise SbgError()
elif isinstance(file_, File):
return file_.id
elif isinstance(file_, six.string_types):
return file_
else:
raise SbgError() | Serializes file to id string
:param file_: object to serialize
:return: string id |
11,055 | def get_ilo_firmware_version_as_major_minor(self):
data = self.get_host_health_data()
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
ilo_version_str = firmware_details.get(, None)
return common.get_major_minor(ilo_version_str) | Gets the ilo firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: String with the format "<major>.<minor>" or None. |
11,056 | def point_in_triangle(p, v1, v2, v3):
def _test(p1, p2, p3):
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
b1 = _test(p, v1, v2) < 0.0
b2 = _test(p, v2, v3) < 0.0
b3 = _test(p, v3, v1) < 0.0
return (b1 == b2) and (b2 == b3) | Checks whether a point is within the given triangle
The function checks, whether the given point p is within the triangle defined by the the three corner point v1,
v2 and v3.
This is done by checking whether the point is on all three half-planes defined by the three edges of the triangle.
:param p: The... |
11,057 | def query(path, method=, data=None, params=None, header_dict=None, decode=True):
certificate_path = config.get_cloud_config_value(
,
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
... | Perform a query directly against the Azure REST API |
11,058 | def get_index2data(model_description):
index2latex = {}
translation_csv = os.path.join(get_project_root(),
model_description["data-source"],
"index2formula_id.csv")
with open(translation_csv) as csvfile:
csvreader = csv.DictR... | Get a dictionary that maps indices to a list of (1) the id in the
hwrt symbol database (2) the latex command (3) the unicode code point
(4) a font family and (5) a font style.
Parameters
----------
model_description : string
A model description file that points to a feature folder where an
... |
11,059 | def ancestors(self):
ancestors = set([])
self._depth_ascend(self, ancestors)
try:
ancestors.remove(self)
except KeyError:
pass
return list(ancestors) | Returns a list of the ancestors of this node. |
11,060 | def queue_emission(self, msg):
if not msg:
return
for _emitter in self._emit:
if not hasattr(_emitter, ):
continue
def emit(emitter=_emitter):
self.log.debug("emit to {}".format(emitter.name))
emitter.emit(msg)
... | queue an emission of a message for all output plugins |
11,061 | async def save(proxies, filename):
with open(filename, ) as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
proto = if in proxy.types else
row = % (proto, proxy.host, proxy.port)
f.write(row) | Save proxies to a file. |
11,062 | def service(name, action):
if action == :
subprocess.check_output([, , str(name)],
universal_newlines=True)
elif action == :
subprocess.check_output([, , , str(name)],
universal_newlines=True)
else:
raise UFWError((... | Open/close access to a service
:param name: could be a service name defined in `/etc/services` or a port
number.
:param action: `open` or `close` |
11,063 | def open_files(by_pid=False):
**
pids = {}
procfs = os.listdir()
for pfile in procfs:
try:
pids[int(pfile)] = []
except ValueError:
pass
files = {}
for pid in pids:
ppath = .format(pid)
try:
tids = os.lis... | Return a list of all physical open files on the system.
CLI Examples:
.. code-block:: bash
salt '*' file.open_files
salt '*' file.open_files by_pid=True |
11,064 | def normalize(alias):
alias = re.sub(r, r, alias)
words = alias.lower().split()
words = filter(lambda w: w not in IGNORED_WORDS, words)
return .join(words) | Normalizes an alias by removing adverbs defined in IGNORED_WORDS |
11,065 | def ref_file(
ticker: str, fld: str, has_date=False, cache=False, ext=, **kwargs
) -> str:
data_path = os.environ.get(assist.BBG_ROOT, ).replace(, )
if (not data_path) or (not cache): return
proper_ticker = ticker.replace(, )
cache_days = kwargs.pop(, 10)
root = f
if len(kwargs) ... | Data file location for Bloomberg reference data
Args:
ticker: ticker name
fld: field
has_date: whether add current date to data file
cache: if has_date is True, whether to load file from latest cached
ext: file extension
**kwargs: other overrides passed to ref functi... |
11,066 | def _ExtractPathSpecsFromFile(self, file_entry):
produced_main_path_spec = False
for data_stream in file_entry.data_streams:
yield path_spec
if not data_stream.name:
produced_main_path_spec = True
if not produced_main_path_spec:
yield file_entry.path_spec | Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file. |
11,067 | def remove_role(role):
def processor(action, argument):
ActionRoles.query_by_action(action, argument=argument).filter(
ActionRoles.role_id == role.id
).delete(synchronize_session=False)
return processor | Remove a action for a role. |
11,068 | def set_time_zone(self, item):
i3s_time = item["full_text"].encode("UTF-8", "replace")
try:
i3s_time = i3s_time.decode()
except:
pass
parts = i3s_time.split()
i3s_datetime = " ".join(parts[:2])
if... | Work out the time zone and create a shim tzinfo.
We return True if all is good or False if there was an issue and we
need to re check the time zone. see issue #1375 |
11,069 | def find_mof(self, classname):
classname = classname.lower()
for search in self.parser.search_paths:
for root, dummy_dirs, files in os.walk(search):
for file_ in files:
if file_.endswith() and \
file_[:-4].lower() == c... | Find the MOF file that defines a particular CIM class, in the search
path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the
base part of the file name is the CIM class name.
Example: The class "CIM_ComputerSystem" is expected to be in a file
... |
11,070 | def to_native(self, obj, name, value):
if self.mapping:
for original, new in self.mapping.items():
value = value.replace(original, new)
return load(value, self.namespace) | Transform the MongoDB value into a Marrow Mongo value. |
11,071 | def score_samples(self, X):
check_is_fitted(self, "mean_")
Xr = X - self.mean_
n_features = X.shape[1]
precision = self.get_precision()
log_like = -0.5 * (Xr * (da.dot(Xr, precision))).sum(axis=1)
log_like -= 0.5 * (n_features * da.log(2.0 * np.pi) - ... | Return the log-likelihood of each sample.
See. "Pattern Recognition and Machine Learning"
by C. Bishop, 12.2.1 p. 574
or http://www.miketipping.com/papers/met-mppca.pdf
Parameters
----------
X : array, shape(n_samples, n_features)
The data.
Returns
... |
11,072 | def flush_redis_unsafe(redis_client=None):
if redis_client is None:
ray.worker.global_worker.check_connected()
redis_client = ray.worker.global_worker.redis_client
keys = redis_client.keys("LOGFILE:*")
if len(keys) > 0:
num_deleted = redis_client.delete(*keys)
else:
... | This removes some non-critical state from the primary Redis shard.
This removes the log files as well as the event log from Redis. This can
be used to try to address out-of-memory errors caused by the accumulation
of metadata in Redis. However, it will only partially address the issue as
much of the da... |
11,073 | def get_pk(self, field_val):
field_name = self.schema.pk.name
return self.is_field(field_name, field_val).get_one() | convenience method for running is_pk(_id).get_one() since this is so common |
11,074 | def create_object_id(collection, vault, name, version):
collection = _validate_string_argument(collection, )
vault = _validate_string_argument(vault, )
name = _validate_string_argument(name, )
version = _validate_string_argument(version, , True)
_parse_uri_argument(vault... | :param collection: The resource collection type.
:type collection: str
:param vault: The vault URI.
:type vault: str
:param name: The resource name.
:type name: str
:param version: The resource version.
:type version: str
:rtype: KeyVaultId |
11,075 | def parse_options():
version = "%%prog {version}".format(version=__version__)
parser = OptionParser(version=version)
parser.add_option(
"-u", "--username", action="store", dest="username",
type="string", default="", metavar="RECIPIENT", help="user"
)
parser.add_option(
... | Commandline options arguments parsing. |
11,076 | def _load_hooks_settings(self):
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if hook_show_widget is not None:
if hook_show_setting is not None:
h... | load hooks settings |
11,077 | def poll(self):
if self.group_id is None or self.config[] < (0, 8, 2):
return
self._invoke_completed_offset_commit_callbacks()
self.ensure_coordinator_ready()
if self.config[] >= (0, 9) and self._subscription.partitions_auto_assigned():
if self.need_rej... | Poll for coordinator events. Only applicable if group_id is set, and
broker version supports GroupCoordinators. This ensures that the
coordinator is known, and if using automatic partition assignment,
ensures that the consumer has joined the group. This also handles
periodic offset commi... |
11,078 | def set_terms(self,*terms, **kw_terms):
for t in terms:
self.add_term(t)
for k,v in kw_terms.items():
try:
value, props = v
except (ValueError, TypeError) as e:
value, props = v,{}
self.new_term(k,value,**props) | Create or set top level terms in the section. After python 3.6.0, the terms entries
should maintain the same order as the argument list. The term arguments can have any of these forms:
* For position argument, a Term object
* For kw arguments:
- 'TermName=TermValue'
- 'T... |
11,079 | def getSearchUrl(self, album, artist):
params = collections.OrderedDict()
params["search-alias"] = "popular"
params["field-artist"] = artist
params["field-title"] = album
params["sort"] = "relevancerank"
return __class__.assembleUrl(self.base_url, params) | See CoverSource.getSearchUrl. |
11,080 | def get_certificates(
self, vault_base_url, maxresults=None, include_pending=None, custom_headers=None, raw=False, **operation_config):
def internal_paging(next_link=None, raw=False):
if not next_link:
url = self.get_certificates.metadata[]
... | List certificates in a specified key vault.
The GetCertificates operation returns the set of certificates resources
in the specified key vault. This operation requires the
certificates/list permission.
:param vault_base_url: The vault name, for example
https://myvault.vault.az... |
11,081 | def p_opt_order(self, p):
if len(p) > 1:
if p[3] not in :
raise PythranSyntaxError("Invalid Pythran spec. "
"Unknown order ".format(p[3]))
p[0] = p[3]
else:
p[0] = None | opt_order :
| ORDER LPAREN IDENTIFIER RPAREN |
11,082 | def plot(self, x=None, y=None, z=None, what="count(*)", vwhat=None, reduce=["colormap"], f=None,
normalize="normalize", normalize_axis="what",
vmin=None, vmax=None,
shape=256, vshape=32, limits=None, grid=None, colormap="afmhot",
figsize=None, xlabel=None, ylabel=None, aspect="auto... | Viz data in a 2d histogram/heatmap.
Declarative plotting of statistical plots using matplotlib, supports subplots, selections, layers.
Instead of passing x and y, pass a list as x argument for multiple panels. Give what a list of options to have multiple
panels. When both are present then will be origaniz... |
11,083 | def oauth2_token_setter(remote, resp, token_type=, extra_data=None):
return token_setter(
remote,
resp[],
secret=,
token_type=token_type,
extra_data=extra_data,
) | Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is included
in the authorization code request.
:param remote: The remote applic... |
11,084 | def save(self, filename):
projex.text.xmlindent(self.xmlElement())
try:
f = open(filename, )
except IOError:
logger.exception( % filename)
return False
f.write(self.toString())
f.close()
return True | Saves the xml data to the inputed filename.
:param filename | <str> |
11,085 | def addFASTACommandLineOptions(parser):
parser.add_argument(
, type=open, default=sys.stdin, metavar=,
help=(
))
parser.add_argument(
, default=, choices=readClassNameToClass,
metavar=,
help=(
% .join(readClassNameToClass)))
g... | Add standard command-line options to an argparse parser.
@param parser: An C{argparse.ArgumentParser} instance. |
11,086 | def feather_links(self, factor=0.01, include_self=False):
def feather_node(node):
node_weight_sum = sum(l.weight for l in node.link_list)
for original_link in node.link_list[:]:
neighbor_node = original_link.target
neighb... | Feather the links of connected nodes.
Go through every node in the network and make it inherit the links
of the other nodes it is connected to. Because the link weight sum
for any given node can be very different within a graph, the weights
of inherited links are made proportional to th... |
11,087 | def result_report_class_wise(self):
results = self.results_class_wise_metrics()
output = self.ui.section_header(, indent=2) +
output += self.ui.row(
, , , ,
widths=[20, 12, 12, 12],
separators=[True, False, True, False],
indent=4
... | Report class-wise results
Returns
-------
str
result report in string format |
11,088 | def read_until(self, expected_commands, timeout):
msg = timeouts.loop_until_timeout_or_valid(
timeout, lambda: self.read_message(timeout),
lambda m: m.command in expected_commands, 0)
if msg.command not in expected_commands:
raise usb_exceptions.AdbTimeoutError(
,
... | Read AdbMessages from this transport until we get an expected command.
The ADB protocol specifies that before a successful CNXN handshake, any
other packets must be ignored, so this method provides the ability to
ignore unwanted commands. It's primarily used during the initial
connection to the device... |
11,089 | def ValidOptions(cls):
valid_options = []
for obj_name in dir(cls):
obj = getattr(cls, obj_name)
if inspect.isclass(obj) and issubclass(obj, cls.OptionBase):
valid_options.append(obj_name)
return valid_options | Returns a list of valid option names. |
11,090 | def adapter_add_nio_binding(self, adapter_number, port_number, nio):
try:
adapter = self._adapters[adapter_number]
except IndexError:
raise IOUError(.format(name=self._name,
ada... | Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port |
11,091 | def install_nginx(instance, dbhost, dbname, port, hostname=None):
_check_root()
log("Installing nginx configuration")
if hostname is None:
try:
configuration = _get_system_configuration(dbhost, dbname)
hostname = configuration.hostname
except Exception as e:
... | Install nginx configuration |
11,092 | def unserializers(self, value):
raise foundations.exceptions.ProgrammingError(
"{0} | attribute is read only!".format(self.__class__.__name__, "unserializers")) | Setter for **self.__unserializers** attribute.
:param value: Attribute value.
:type value: dict |
11,093 | def validate_call(kwargs, returns, is_method=False):
def decorator(func):
@wraps(func)
def inner(*passed_args, **passed_kwargs):
max_allowed_passed_args_len = 0
if is_method and type(func) in (types.FunctionType, classm... | Decorator which runs validation on a callable's arguments and its return
value. Pass a schema for the kwargs and for the return value. Positional
arguments are not supported. |
11,094 | def plot(darray, row=None, col=None, col_wrap=None, ax=None, hue=None,
rtol=0.01, subplot_kws=None, **kwargs):
darray = darray.squeeze()
plot_dims = set(darray.dims)
plot_dims.discard(row)
plot_dims.discard(col)
plot_dims.discard(hue)
ndims = len(plot_dims)
error_msg = (
... | Default plot of DataArray using matplotlib.pyplot.
Calls xarray plotting function based on the dimensions of
darray.squeeze()
=============== ===========================
Dimensions Plotting function
--------------- ---------------------------
1 :py:func:`xarray.plot.line`
... |
11,095 | def _commonprefix(files):
out = os.path.commonprefix(files)
out = out.rstrip("_R")
out = out.rstrip("_I")
out = out.rstrip("_")
return out | Retrieve a common prefix for files without extra _R1 _I1 extensions.
Allows alternative naming schemes (R1/R2/R3) (R1/R2/I1). |
11,096 | def extern_store_utf8(self, context_handle, utf8_ptr, utf8_len):
c = self._ffi.from_handle(context_handle)
return c.to_value(self._ffi.string(utf8_ptr, utf8_len).decode()) | Given a context and UTF8 bytes, return a new Handle to represent the content. |
11,097 | def splitext_files_only(filepath):
"Custom version of splitext that doesn') if os.path.isdir(filepath) else os.path.splitext(filepath)
) | Custom version of splitext that doesn't perform splitext on directories |
11,098 | def get_proficiencies_by_search(self, proficiency_query, proficiency_search):
if not self._can():
raise PermissionDenied()
return self._provider_session.get_proficiencies_by_search(proficiency_query, proficiency_search) | Pass through to provider ProficiencySearchSession.get_proficiencies_by_search |
11,099 | async def acquire(self, command=None, args=()):
if self.closed:
raise PoolClosedError("Pool is closed")
async with self._cond:
if self.closed:
raise PoolClosedError("Pool is closed")
while True:
await self._fill_free(override_m... | Acquires a connection from free pool.
Creates new connection if needed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.