Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,000 | def _pre_index_check(handler, host=None, core_name=None):
hostsuccessdataerrorswarnings
if _get_none_or_value(core_name) is None and _check_for_cores():
errors = []
return _get_return_dict(False, errors=errors)
return resp | PRIVATE METHOD - MASTER CALL
Does a pre-check to make sure that all the options are set and that
we can talk to solr before trying to send a command to solr. This
Command should only be issued to masters.
handler : str
The import handler to check the state of
host : str (None):
The ... |
338,001 | def default_value(self):
if not hasattr(self, "_default_value"):
if self.elem_type == "select":
try:
def_value = get_option_value(self.elem.select_one("[selected]"))
except AttributeError:
... | The default category when making a query |
338,002 | def predictive_probability_multistate(M_c, X_L_list, X_D_list, Y, Q):
logprobs = [float(predictive_probability(M_c, X_L, X_D, Y, Q))
for X_L, X_D in zip(X_L_list, X_D_list)]
return logmeanexp(logprobs) | Returns the predictive probability, averaged over each sample. |
338,003 | def delete(self, session, lookup_keys, *args, **kwargs):
model = self._get_model(lookup_keys, session)
session.delete(model)
session.commit()
return {} | Deletes the model found using the lookup_keys
:param Session session: The SQLAlchemy session to use
:param dict lookup_keys: A dictionary mapping the fields
and their expected values
:return: An empty dictionary
:rtype: dict
:raises: NotFoundException |
338,004 | def _wait_for_js(self):
if not hasattr(self, ):
return
if hasattr(self, ) and self._js_vars:
EmptyPromise(
lambda: _are_js_vars_defined(self.browser, self._js_vars),
u"JavaScript variables defined: {0}".format(", ".join(self._js_vars))
).fulf... | Class method added by the decorators to allow
decorated classes to manually re-check JavaScript
dependencies.
Expect that `self` is a class that:
1) Has been decorated with either `js_defined` or `requirejs`
2) Has a `browser` property
If either (1) or (2) is not satisfied, then do nothing. |
338,005 | def failure(self):
self.short_interval += self.short_unit
self.long_interval += self.long_unit
self.short_interval = min(self.short_interval, self.max_short_timer)
self.long_interval = min(self.long_interval, self.max_long_timer)
self.update_interval() | Update the timer to reflect a failed call |
338,006 | def terminate(self, end):
if self.terminated:
raise TdlError()
if end == LIST_TYPE:
self.terminated = False
elif end == EMPTY_LIST_TYPE:
if self._last_path:
self[self._last_path] = None
else:
self._avm = Non... | Set the value of the tail of the list.
Adding values via :meth:`append` places them on the `FIRST`
feature of some level of the feature structure (e.g.,
`REST.FIRST`), while :meth:`terminate` places them on the
final `REST` feature (e.g., `REST.REST`). If *end* is a
:class:`Conj... |
338,007 | def from_board(cls, board):
if len(board):
left = board.left_end()
right = board.right_end()
else:
left = None
right = None
return cls(left, right, len(board)) | :param Board board: board to represent
:return: SkinnyBoard to represent the given Board |
338,008 | def _is_node_an_element(self, node):
if isinstance(node, BaseET.Element):
return True
if hasattr(node, ) and isinstance(node.tag, basestring):
return True | Return True if the given node is an ElementTree Element, a fact that
can be tricky to determine if the cElementTree implementation is
used. |
338,009 | def load_yaml_from_url(ont_url):
res = requests.get(ont_url)
if res.status_code != 200:
raise Exception( % ont_url)
root = yaml.load(res.content)
return root | Return a YAML object loaded from a YAML file URL. |
338,010 | def priority_argsort(list_, priority):
r
reordered_list = priority_sort(list_, priority)
sortx = [list_.index(item) for item in reordered_list]
return sortx | r"""
Args:
list_ (list):
priority (list): desired order of items
Returns:
list: reordered_index_list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list_ = [2, 4, 6, 8, 10]
>>> priority = [8... |
338,011 | def del_feed(name):
with Database("aliases") as aliases, Database("feeds") as feeds:
if aliases[name]:
proper_name = aliases[name]
elif feeds[name]:
proper_name = feeds[name]
for k, v in aliases:
if v == proper_name:
del aliases[k]
... | remove from database (and delete aliases) |
338,012 | def annotate_highlight(filenode, annotate_from_changeset_func=None,
order=None, headers=None, **options):
options[] = True
formatter = AnnotateHtmlFormatter(filenode=filenode, order=order,
headers=headers,
annotate_from_changeset_func=annotate_from_changeset_func, **options)
lex... | Returns html portion containing annotated table with 3 columns: line
numbers, changeset information and pygmentized line of code.
:param filenode: FileNode object
:param annotate_from_changeset_func: function taking changeset and
returning single annotate cell; needs break line at the end
:param ... |
338,013 | def update_pass(user_id, newpass):
out_dic = {: False, : }
entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id)
entry.execute()
out_dic[] = True
return out_dic | Update the password of a user. |
338,014 | def get_gradebooks(self):
if self.retrieved:
raise errors.IllegalState()
self.retrieved = True
return objects.GradebookList(self._results, runtime=self._runtime) | Gets the gradebook list resulting from the search.
return: (osid.grading.GradebookList) - the gradebook list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.* |
338,015 | def do_file_download(client, args):
if not os.path.isdir(args.dest_path) and not args.dest_path.endswith():
print("file-download: "
"target is not a directory".format(args.dest_path))
if not os.path.exists(args.dest_path):
print("\tHint: add trailing / to create... | Download file |
338,016 | def diskMonitor(self):
while self.loop():
try:
newest = max(glob.iglob("%s/*" % (self.kwargs.directory)), key=os.path.getmtime)
except Exception:
pass
else:
if time() - os.path.getctime(newest) >= self.kwargs.idle_time... | Primitive monitor which checks whether new data is added to disk. |
338,017 | def make_transparent(image):
data = image.copy().getdata()
modified = []
for item in data:
if _check_pixel(item) is True:
modified.append((255, 255, 255, 255))
continue
modified.append(item)
image.putdata(modified)
return image | Turn all black pixels in an image into transparent ones |
338,018 | def combined_credits(self, **kwargs):
path = self._get_id_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the combined (movie and TV) credits for a specific person id.
To get the expanded details for each TV record, call the /credit method
with the provided credit_id. This will provide details about which
episode and/or season the credit is for.
Args:
language: (optional)... |
338,019 | def read(self, size=None):
if not self._is_open:
raise IOError()
if self._current_offset < 0:
raise IOError(
.format(
self._current_offset))
if self._uncompressed_stream_size is None:
self._uncompressed_stream_size = self._GetUncompressedStreamSize()
if ... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... |
338,020 | def delete_rows(self, row, no_rows=1):
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
try:
self.code_array.delete(row, no_rows, axis=0, tab=tab)
except ValueError, err:
post_command_event(self.main_... | Deletes no_rows rows and marks grid as changed |
338,021 | def GetString(self):
string_list = []
string_list.append(.format(self.plugin_name))
time_compiled = getattr(self, , 0)
if time_compiled:
time_compiled = timelib.Timestamp.CopyToIsoFormat(time_compiled)
string_list.append(.format(time_compiled))
filter_string = getattr(self, , )
... | Retrieves a string representation of the report.
Returns:
str: string representation of the report. |
338,022 | def _split_samples_by_qc(samples):
to_process = []
extras = []
for data in [utils.to_single_data(x) for x in samples]:
qcs = dd.get_algorithm_qc(data)
if qcs and (dd.get_align_bam(data) or dd.get_work_bam(data) or
tz.get_in(["config", "algorithm", "kraken"],... | Split data into individual quality control steps for a run. |
338,023 | def get_pp_name(self):
ppnames = []
natomtypes = int(self._get_line(, self.outputf).split()[5])
with open(self.outputf) as fp:
for line in fp:
if "PseudoPot.
ppnames.append(Scalar(value=next(fp).split()[-1].rstrip()))
... | Determine the pseudopotential names from the output |
338,024 | def smart_search_prefix(self):
search_options = {}
extra_query = None
vrf_filter = None
if in request.json:
search_options[] = request.json[]
if in request.json:
if request.json[] == :
search_options[] = True
else:... | Perform a smart search.
The smart search function tries extract a query from
a text string. This query is then passed to the search_prefix
function, which performs the search. |
338,025 | def get(self, request, bot_id, id, format=None):
return super(SourceStateList, self).get(request, bot_id, id, format) | Get list of source state of a handler
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated |
338,026 | def get_serializer_info(self, serializer):
if hasattr(serializer, ):
serializer = serializer.child
serializer.fields.pop(api_settings.URL_FIELD_NAME, None)
return OrderedDict([
(field_name, self.get_field_info(field))
... | Given an instance of a serializer, return a dictionary of metadata
about its fields. |
338,027 | def _parse_packet_v2(self, data):
s a single zero
byte).
:param data:
:return: rest of data, PacketV2
field data extends past end of buffer')
return data[payload_len:], PacketV2(ft, data[0:payload_len]) | Parses a V2 data packet at the start of the given data.
The format of a packet is as follows:
field_type(varint) payload_len(varint) data[payload_len bytes]
apart from EOS which has no payload_en or data (it's a single zero
byte).
:param data:
:return: rest of data, P... |
338,028 | def set_file_metadata(ase, metadata, timeout=None):
dir, fpath, _ = parse_file_path(ase.name)
ase.client.set_file_metadata(
share_name=ase.container,
directory_name=dir,
file_name=fpath,
metadata=metadata,
timeout=timeout) | Set file metadata
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param dict metadata: metadata kv pairs
:param int timeout: timeout |
338,029 | def most_frequent_terms(self, depth):
counts = self.term_counts()
top_terms = set(list(counts.keys())[:depth])
end_count = list(counts.values())[:depth][-1]
bucket = self.term_count_buckets()[end_count]
return top_terms.union(set(... | Get the X most frequent terms in the text, and then probe down to get
any other terms that have the same count as the last term.
Args:
depth (int): The number of terms.
Returns:
set: The set of frequent terms. |
338,030 | def parse(self, data, extent, desc_tag):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
(tag_unused, self.vol_desc_seqnum, self.part_flags, self.part_num,
part_contents, part_contents_use, self.access_type,
self.part_start_location, s... | Parse the passed in data into a UDF Partition Volume Descriptor.
Parameters:
data - The data to parse.
extent - The extent that this descriptor currently lives at.
desc_tag - A UDFTag object that represents the Descriptor Tag.
Returns:
Nothing. |
338,031 | def get_metadata(self):
inspect_data = self.inspect(refresh=True)
inspect_to_container_metadata(self.metadata, inspect_data, self.image)
return self.metadata | Convert dictionary returned after docker inspect command into instance of ContainerMetadata class
:return: ContainerMetadata, container metadata instance |
338,032 | def select_by_selector(self, selector):
option = find_element_by_jquery(world.browser, selector)
selectors = find_parents_by_jquery(world.browser, selector)
if not selectors:
raise AssertionError("No parent element found for the option.")
selector = selectors[0]
selector.click()
sle... | Select the option matching the CSS selector. |
338,033 | def add_snmp_host(self, **kwargs):
host_info = kwargs.pop()
community = kwargs.pop()
callback = kwargs.pop(, self._callback)
config = ET.Element()
snmp_server = ET.SubElement(config, ,
xmlns=("urn:brocade.com:mgmt:"
... | Add SNMP host to NOS device.
Args:
host_info (tuple(str, str)): Tuple of host IP and port.
community (str): Community string to be added to device.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback... |
338,034 | def get(self, request, pzone_pk):
try:
pzone = PZone.objects.get(pk=pzone_pk)
except PZone.DoesNotExist:
raise Http404("Cannot find given pzone.")
filters = {"pzone": pzone}
if "from" in request.GET:
parsed = dateparse.par... | Get all the operations for a given pzone. |
338,035 | def render(self, form_id=None):
page_bar = self.page_bars.get(int(self.page / 10))
if page_bar is None:
return
_htmls = []
if form_id:
_htmls.append(u)
_htmls.append()
_htmls.append(u % self.total)
current_start = self.page
... | 动态输出html内容 |
338,036 | def _valid_value(self, value):
if not self.valid_values:
return True
valid_values = (self.valid_values if isinstance(self.valid_values, list)
else list(self.valid_values))
return value in valid_values | bool: Whether the given value is valid. |
338,037 | def all_databases(client, exclude=[]):
return (
client[db_name]
for db_name in client.list_database_names()
if db_name not in exclude
) | Yield all databases except excluded (default
excludes 'local'). |
338,038 | def rename_feature(self, mapobject_type_name, name, new_name):
logger.info(
,
name, self.experiment_name, mapobject_type_name
)
content = {
: new_name,
}
feature_id = self._get_feature_id(mapobject_type_name, name)
url = self._... | Renames a feature.
Parameters
----------
mapobject_type_name: str
name of the segmented objects type
name: str
name of the feature that should be renamed
new_name: str
name that should be given to the feature
See also
--------... |
338,039 | def _m2m_field_data(field, obj):
data = _basic_field_data(field, obj)
data[Field.TYPE] = FieldType.M2M
related = field.rel.to
relation_info = {
Field.REL_DB_TABLE: related._meta.db_table,
Field.REL_APP: related._meta.app_label,
Field.REL_MODEL: related.__name__
}
dat... | Returns m2m ``field`` as a dict.
Value is an array of related primary keys and some meta information
for reconstructing objects. |
338,040 | def apseudo(Ss, ipar, sigma):
Is = random.randint(0, len(Ss) - 1, size=len(Ss))
if not ipar:
BSs = Ss[Is]
else:
A, B = design(6)
K, BSs = [], []
for k in range(len(Ss)):
K.append(np.dot(A, Ss[k][0:6]))
Pars = np.random.normal(K, sigma)
... | draw a bootstrap sample of Ss |
338,041 | def message_create(self, originator, recipients, body, params=None):
if params is None: params = {}
if type(recipients) == list:
recipients = .join(recipients)
params.update({: originator, : body, : recipients})
return Message().load(self.request(, , params)) | Create a new message. |
338,042 | def abort_keepalive_pings(self) -> None:
assert self.state is State.CLOSED
exc = ConnectionClosed(self.close_code, self.close_reason)
exc.__cause__ = self.transfer_data_exc
for ping in self.pings.values():
ping.set_exception(exc)
if self.pings:
... | Raise ConnectionClosed in pending keepalive pings.
They'll never receive a pong once the connection is closed. |
338,043 | def _get_event_source_status(awsclient, evt_source, lambda_arn):
event_source_obj = _get_event_source_obj(awsclient, evt_source)
return event_source_obj.status(lambda_arn) | Given an event_source dictionary, create the object and get the event source status. |
338,044 | def to_transitions(self) -> :
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self.environment_information for ei in l]
if self.environment_information is not None else None,
tran... | Convert given rollout to Transitions |
338,045 | def read_data(self,variable_instance):
if self.inst is None:
return
vp_func = variable_instance.variableproperty_set.filter(name=).first()
measure_function =
if vp_func:
if vp_func.value():
measure_function = %vp_func.value()
tr... | read values from the device |
338,046 | def unpack_char16(self, data):
if data is None:
return None
len_data = len(data)
if len_data == 0:
raise CIMXMLParseError(
"Char16 value is empty",
conn_id=self.conn_id)
if len_data > 1:
... | Unpack a CIM-XML string value of CIM type 'char16' and return it
as a unicode string object, or None.
data (unicode string): CIM-XML string value, or None (in which case
None is returned). |
338,047 | def load(self, id_code):
filestream = open(.format(self.data_path, id_code), )
workflow = pickle.load(filestream)
return workflow | Loads a workflow identified by id_code
id_code - unique identifier, previously must have called save with same id_code |
338,048 | def get_node_age_sum(self, age=None):
if age is None:
age = self.age
return pow(self.comp, age) | Get the sum of branches grown in an specific age.
Returns:
int: The sum of all nodes grown in an age. |
338,049 | def _sound_settings(area, setting, value, validate_value):
if validate_value:
if (setting in CONST.VALID_SOUND_SETTINGS
and value not in CONST.ALL_SETTING_SOUND):
raise AbodeException(ERROR.INVALID_SETTING_VALUE,
CONST... | Will validate sound settings and values, returns data packet. |
338,050 | def mode_mapping(self):
mav_type = self.field(, , self.mav_type)
mav_autopilot = self.field(, , None)
if mav_autopilot == mavlink.MAV_AUTOPILOT_PX4:
return px4_map
if mav_type is None:
return None
map = None
if mav_type in [mavlink.MAV_TYP... | return dictionary mapping mode names to numbers, or None if unknown |
338,051 | def use_service(bundle_context, svc_reference):
if svc_reference is None:
raise TypeError("Invalid ServiceReference")
try:
yield bundle_context.get_service(svc_reference)
finally:
try:
bundle_context.unget_service(svc_reference)
except ... | Utility context to safely use a service in a "with" block.
It looks after the the given service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:param svc_reference: The reference of the service to use
:return: The requested service
:raise ... |
338,052 | def unpack_fraction(num: str) -> str:
nums = [int(n) for n in num.split() if n]
if len(nums) == 2 and nums[0] > nums[1]:
over = nums[0] // nums[1]
rem = nums[0] % nums[1]
return f
return num | Returns unpacked fraction string 5/2 -> 2 1/2 |
338,053 | def reset(self):
self.metadata.drop_all(self.engine)
self.metadata.create_all(self.engine) | Reset the database
Drop all tables and recreate them |
338,054 | def handle_scrollwheel(self, event):
scroll_x, scroll_y = self._get_scroll(event)
if scroll_x:
self.events.append(
self.emulate_wheel(scroll_x, , self.timeval))
if scroll_y:
self.events.append(
self.emulate_wheel(scroll_... | Handle the scrollwheel (it is a ball on the mighty mouse). |
338,055 | def get_field(field):
if isinstance(field, djmodels.fields.Field):
return field
elif isinstance(field, basestring):
field = field.split()
if len(field) == 3:
model = get_model(app=field[0], model=field[1])
elif len(field) == 2:
model = get_model(app=D... | Return a field object based on a dot-delimited app.model.field name |
338,056 | def _get_package(self):
mask =
package_keyname =
package = self.ordering_manager.get_package_by_key(package_keyname, mask=mask)
return package | Get the package related to simple hardware ordering. |
338,057 | def main(fd, verbose=0):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
if _HAVE_SIGMASK:
signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
for f in (sys.stdin, sys.stdout):
try:
f.close()
except Excep... | Run semaphore tracker. |
338,058 | def get_account_user(self, account_id, user_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_account_user_with_http_info(account_id, user_id, **kwargs)
else:
(data) = self.get_account_user_with_http_info(account_id, user_id, **kwargs)
... | Details of the user. # noqa: E501
An endpoint for retrieving details of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{userID} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... |
338,059 | def compare(eq_dfs, columns=None, selection=):
content = np.empty((eq_dfs[0].shape[0], len(eq_dfs)), dtype=np.float64)
rel_perf = pd.DataFrame(content, eq_dfs[0].index, columns, dtype=np.float64)
for i in range(len(eq_dfs)):
rel_perf.iloc[:, i] = eq_dfs[i].loc[:, selection] / eq_dfs[i].iloc[0].... | Get the relative performance of multiple equities.
.. versionadded:: 0.5.0
Parameters
----------
eq_dfs : list or tuple of DataFrame
Performance data for multiple equities over
a consistent time frame.
columns : iterable of str, default None
Labels to use for the columns of... |
338,060 | def get_template(
self,
url,
dest,
template=,
makedirs=False,
saltenv=,
cachedir=None,
**kwargs):
if in kwargs:
kwargs.pop()
kwargs[] = saltenv
url_data = urlparse(... | Cache a file then process it as a template |
338,061 | def _get_namespaces(apiserver_url, name=""):
url = "{0}/api/v1/namespaces/{1}".format(apiserver_url, name)
ret = http.query(url)
if ret.get("body"):
return salt.utils.json.loads(ret.get("body"))
else:
return None | Get namespace is namespace is defined otherwise return all namespaces |
338,062 | def merge_intervals(elems, overlap_thres=2.0):
overlap_thres = max(0.0, overlap_thres)
ordered = sorted(elems, key=lambda e: e.x0)
intervals = []
cur = [-overlap_thres, -overlap_thres]
for e in ordered:
if e.x0 - cur[1] > overlap_thres:
if cur[1] > 0.0:
... | Project in x axis
Sort by start
Go through segments and keep max x1
Return a list of non-overlapping intervals |
338,063 | def str_strip(x, to_strip=None):
sl = _to_string_sequence(x).strip( if to_strip is None else to_strip) if to_strip != else x
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | Removes leading and trailing characters.
Strips whitespaces (including new lines), or a set of specified
characters from each string saple in a column, both from the left
right sides.
:param str to_strip: The characters to be removed. All combinations of the characters will be removed.
... |
338,064 | def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs):
ensure_model_obj_has_mapping_constructor(model_obj)
ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights)
ensure_rows_to_obs_validity(rows_to_obs)
return None | Ensures the args to `create_long_form_weights` have expected properties. |
338,065 | def cast(self, other_class):
if other_class.tag != self.__class__.tag:
raise TypeError(unwrap(
,
type_name(other_class),
type_name(self),
other_class.tag,
self.__class__.tag
))
new_obj = ot... | Converts the current object into an object of a different class. The
new class must use the ASN.1 encoding for the value.
:param other_class:
The class to instantiate the new object from
:return:
An instance of the type other_class |
338,066 | def is_tainted(variable, context, only_unprotected=False, ignore_generic_taint=False):
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if isinstance(variable, Constant):
return False
slither = context.slither
taints = slither.context[KEY_INPUT]... | Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool |
338,067 | def create_business_rules(self, hosts, services, hostgroups, servicegroups,
macromodulations, timeperiods):
for item in self:
item.create_business_rules(hosts, services, hostgroups,
servicegroups, macromodulations, timeper... | Loop on hosts or services and call SchedulingItem.create_business_rules
:param hosts: hosts to link to
:type hosts: alignak.objects.host.Hosts
:param services: services to link to
:type services: alignak.objects.service.Services
:param hostgroups: hostgroups to link to
:... |
338,068 | def init_widget(self):
super(UiKitProgressView, self).init_widget()
d = self.declaration
if d.progress:
self.set_progress(d.progress) | Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created. |
338,069 | def get_trt_sources(self, optimize_same_id=None):
atomic = []
acc = AccumDict(accum=[])
for sm in self.source_models:
for grp in sm.src_groups:
if grp and grp.atomic:
atomic.append((grp.trt, grp))
elif grp:
... | :returns: a list of pairs [(trt, group of sources)] |
338,070 | def add_to_pairtree(output_path, meta_id):
paired_path = pair_tree_creator(meta_id)
path_append =
for pair_dir in paired_path.split(os.sep):
path_append = os.path.join(path_append, pair_dir)
combined_path = os.path.join(output_path, path_append)
... | Creates pairtree dir structure within pairtree for new
element. |
338,071 | def is_timeseries(nc, variable):
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
for req in (, , ):
if req not in cmatrix:
return False
if len(cmatrix[]) != 0:
return False
if len(cmatrix[]) != 0:
return False
... | Returns true if the variable is a time series feature type.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check |
338,072 | def progress_patch(self, _=False):
from .progress import ShellProgressView
self.cli_ctx.progress_controller.init_progress(ShellProgressView())
return self.cli_ctx.progress_controller | forces to use the Shell Progress |
338,073 | def _respond(self, channel, text):
result = self._format_message(channel, text)
if result is not None:
logger.info(
,
truncate(result, max_len=50),
)
self.socket.send_str(result) | Respond to a message on the current socket.
Args:
channel (:py:class:`str`): The channel to send to.
text (:py:class:`str`): The message text to send. |
338,074 | def get_all_fields(cls, class_obj=None, fields=None):
def return_fields(obj):
internal_fields = fields
if internal_fields is None:
internal_fields = {}
for attribute in dir(obj):
try:
attr_val = getattr(obj, att... | TODO: This needs to be properly used |
338,075 | def buscar_por_equipamento(self, nome_equipamento, ip_equipamento):
if nome_equipamento == or nome_equipamento is None:
raise InvalidParameterError(
u)
if not is_valid_ip(ip_equipamento):
raise InvalidParameterError(
u)
url = ... | Obtém um ambiente a partir do ip e nome de um equipamento.
:param nome_equipamento: Nome do equipamento.
:param ip_equipamento: IP do equipamento no formato XXX.XXX.XXX.XXX.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
... |
338,076 | def key_values_cache_key_name(cls, *key_fields):
key_fields = key_fields or cls.KEY_FIELDS
return .format(cls.__name__, .join(key_fields)) | Key for fetching unique key values from the cache |
338,077 | def add(self, items):
if not isinstance(items, list):
items = [items]
for m in items:
updated = False
for i in range(len(self.items)):
if self.items[i].name == m.name:
self.items[i] = m
updated = True
... | add a submenu |
338,078 | def get_all_events(self):
self.all_events = {}
events = self.tree.findall()
events += self.tree.findall()
for e in events:
event_id = e.attrib[]
if event_id in self._static_events:
continue
event_type = e.find().text
... | Make a list of all events in the TRIPS EKB.
The events are stored in self.all_events. |
338,079 | def _use_color(msg, ansi_fmt, output_stream):
if configs._on_rtd or (not configs.alwaysColorize and not output_stream.isatty()):
log = msg
else:
log = colorize(msg, ansi_fmt)
return log | Based on :data:`~exhale.configs.alwaysColorize`, returns the colorized or
non-colorized output when ``output_stream`` is not a TTY (e.g. redirecting
to a file).
**Parameters**
``msg`` (str)
The message that is going to be printed by the caller of this method.
``ansi_fmt`` (str)... |
338,080 | async def async_determine_channel(channel):
from fuzzywuzzy import process
channel_data = await async_get_channels()
if not channel_data:
_LOGGER.error()
return
channels = [c for c in channel_data.get(, {}).keys()]
if channel in channels:
return channel
else:
... | Check whether the current channel is correct. If not try to determine it
using fuzzywuzzy |
338,081 | def set_tag(self, p_key, p_value="", p_force_add=False, p_old_value=""):
if p_value == "":
self.remove_tag(p_key, p_old_value)
return
tags = self.fields[]
value = p_old_value if p_old_value else self.tag_value(p_key)
if not p_force_add and value:
... | Sets a occurrence of the tag identified by p_key. Sets an arbitrary
instance of the tag when the todo contains multiple tags with this key.
When p_key does not exist, the tag is added.
When p_value is not set, the tag will be removed.
When p_force_add is true, a tag will always be adde... |
338,082 | def get_bookmarks(self, **filters):
filter_dict = filter_args_to_dict(filters, ACCEPTED_BOOKMARK_FILTERS)
url = self._generate_url(, query_params=filter_dict)
return self.get(url) | Get Bookmarks for the current user.
Filters:
:param archive: Filter Bookmarks returned by archived status.
:param favorite: Filter Bookmarks returned by favorite status.
:param domain: Filter Bookmarks returned by a domain.
:param added_since: Filter bookmarks by date added (si... |
338,083 | def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, ca... | Update a calendar event.
Update and return a calendar event |
338,084 | def verbosity_level(self, value):
if value is not None:
assert type(value) is int, " attribute: type is not !".format("verbosity_level", value)
assert value >= 0 and value <= 4, " attribute: Value need to be exactly beetween 0 and 4!".format(
"verbosity_level")... | Setter for **self.__verbosity_level** attribute.
:param value: Attribute value.
:type value: int |
338,085 | def provider_parser(subparser):
identity_group = subparser.add_mutually_exclusive_group()
identity_group.add_argument(
"--auth-id", help="specify user id for authentication")
identity_group.add_argument(
"--auth-subid", help="specify subuser id for authentication")
identity_group.ad... | Configure provider parser for CloudNS |
338,086 | def withdraw(self, currency, amount, address):
self._validate_currency(currency)
self._log(.format(amount, currency, address))
coin_name = self.major_currencies[currency]
return self._rest_client.post(
endpoint=.format(coin_name)
) | Withdraw a major currency from QuadrigaCX to the given wallet.
:param currency: Major currency name in lowercase (e.g. "btc", "eth").
:type currency: str | unicode
:param amount: Withdrawal amount.
:type amount: int | float | str | unicode | decimal.Decimal
:param address: Walle... |
338,087 | def calc_gamma_from_energy_autocorrelation_fit(self, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
autocorrelation = calc_autocorrelation(self.voltage[:-1]**2*self.OmegaTrap.n**2+(_np.diff(self.voltage)*self.SampleFreq)**2)
time = self.time.get_array()[:len(autocorrelation)]
... | Calculates the total damping, i.e. Gamma, by calculating the energy each
point in time. This energy array is then used for the autocorrleation.
The autocorrelation is fitted with an exponential relaxation function and
the function returns the parameters with errors.
Parameters
... |
338,088 | def dependentItems(store, tableClass, comparisonFactory):
for cascadingAttr in (_cascadingDeletes.get(tableClass, []) +
_cascadingDeletes.get(None, [])):
for cascadedItem in store.query(cascadingAttr.type,
comparisonFactory(cascadingAttr... | Collect all the items that should be deleted when an item or items
of a particular item type are deleted.
@param tableClass: An L{Item} subclass.
@param comparison: A one-argument callable taking an attribute and
returning an L{iaxiom.IComparison} describing the items to
collect.
@return: An ... |
338,089 | def valueWritePreprocessor(valueString, replaceParamsFile=None):
if type(valueString) is bool:
log.warning("Only numerical variable types can be handled by the valueReadPreprocessor function.")
return valueString
variableString = valueString
if replaceParamsFile is not None:... | Look up variable name in replace param file for the negative id given and return it.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if
replacement variabl... |
338,090 | def clean_layer(layer):
output_layer_name = clean_geometry_steps[]
output_layer_name = output_layer_name % layer.keywords[]
layer.startEditing()
count = 0
request = QgsFeatureRequest().setSubsetOfAttributes([])
for feature in layer.getFeatures(request):
geom = feature.ge... | Clean a vector layer.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The buffered vector layer.
:rtype: QgsVectorLayer |
338,091 | def named_eq_relations(self, name, neg=False):
if self.eqLinks and not neg:
if isinstance(name, six.string_types):
return filter(lambda x: x.relation.name == name,
self.eqLinks)
elif isinstance(name, list):
return f... | Returns list of named eqLinks.
<name> may be string or list. |
338,092 | def ethernet_adapters(self, ethernet_adapters):
self._ethernet_adapters.clear()
for _ in range(0, ethernet_adapters):
self._ethernet_adapters.append(EthernetAdapter(interfaces=4))
log.info(.format(name=self._name,
... | Sets the number of Ethernet adapters for this IOU VM.
:param ethernet_adapters: number of adapters |
338,093 | def register_new_state_machines(self, model, prop_name, info):
if info[] == :
self.observe_model(info[][1])
self.logger.info(NotificationOverview(info))
elif info[] == :
pass
else:
self.logger.warning(NotificationOverview(info)) | The method register self as observer newly added StateMachineModels after those were added to the list of
state_machines hold by observed StateMachineMangerModel. The method register as observer of observable
StateMachineMangerModel.state_machines. |
338,094 | def prepare_build_environment(self,
user_sdk_dir,
user_ndk_dir,
user_android_api,
user_ndk_api):
self.ensure_dirs()
if self._build_env_prepared:
... | Checks that build dependencies exist and sets internal variables
for the Android SDK etc.
..warning:: This *must* be called before trying any build stuff |
338,095 | def make_isotropic_source(name, Spectrum_Filename, spectrum):
data = dict(Spectrum_Filename=Spectrum_Filename)
if spectrum is not None:
data.update(spectrum)
return roi_model.IsoSource(name, data) | Construct and return a `fermipy.roi_model.IsoSource` object |
338,096 | def build(self):
if self.is_built():
return
with _wait_signal(self.loadFinished, 20):
self.rebuild()
self._built = True | Build the full HTML source. |
338,097 | def get_project(self, project_id):
project_response = self.get_request( % project_id)
return Project(self, project_response[]) | Gets a single project by id. |
338,098 | def upgrade(cfg):
db_node = cfg["db"]
old_db_elems = ["host", "name", "port", "pass", "user", "dialect"]
has_old_db_elems = [x in db_node for x in old_db_elems]
if any(has_old_db_elems):
print("Old database configuration found. "
"Converting to new connect_string. "
... | Provide forward migration for configuration files. |
338,099 | def col_transform(self, col, digits):
if col is None or float(col) < 0.0:
return None
else:
col = self.number_to_base(int(col), self.base, digits)
if len(col) == digits:
return col
else:
return [0 for _ in range(di... | The lambda body to transform the column values |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.