Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,700 | def on_service_arrival(self, svc_ref):
with self._lock:
if svc_ref not in self.services:
prop_value = svc_ref.get_property(self._key)
if (
prop_value not in self._future_value
and prop_value is not None... | Called when a service has been registered in the framework
:param svc_ref: A service reference |
368,701 | def _validate_allof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical(, definitions, field, value)
if valids < len(definitions):
self._error(field, errors.ALLOF, _errors,
valids, len(definitions)) | {'type': 'list', 'logical': 'allof'} |
368,702 | def update_ipsec_site_connection(self, ipsecsite_conn, body=None):
return self.put(
self.ipsec_site_connection_path % (ipsecsite_conn), body=body
) | Updates an IPsecSiteConnection. |
368,703 | def set_select(self, select_or_deselect = , value=None, text=None, index=None):
if select_or_deselect is :
if value is not None:
Select(self.element).select_by_value(value)
elif text is not None:
Select(self.element).select_by_visible_te... | Private method used by select methods
@type select_or_deselect: str
@param select_or_deselect: Should I select or deselect the element
@type value: str
@type value: Value to be selected
@type text: str
@type text: ... |
368,704 | def to_user(user):
from sevenbridges.models.user import User
if not user:
raise SbgError()
elif isinstance(user, User):
return user.username
elif isinstance(user, six.string_types):
return user
else:
raise SbgError() | Serializes user to id string
:param user: object to serialize
:return: string id |
368,705 | def get(self, name, section=None, fallback=False):
try:
_section, name = name.split(
preferences_settings.SECTION_KEY_SEPARATOR)
return self[_section][name]
except ValueError:
pass
try:
return self[secti... | Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if you want to avoid providing section param
:type name: str.
... |
368,706 | def _area(sma, eps, phi, r):
aux = r * math.cos(phi) / sma
signal = aux / abs(aux)
if abs(aux) >= 1.:
aux = signal
return abs(sma**2 * (1.-eps) / 2. * math.acos(aux)) | Compute elliptical sector area. |
368,707 | def create_pax_header(self, info, encoding):
info["magic"] = POSIX_MAGIC
pax_headers = self.pax_headers.copy()
for name, hname, length in (
("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
("uname", "uname", 32), ("... | Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information. |
368,708 | def join(self, right, on=None, how=):
available_join_types = [,,,]
if not isinstance(right, SFrame):
raise TypeError("Can only join two SFrames")
if how not in available_join_types:
raise ValueError("Invalid join type")
if (self.num_columns() <= 0) or ... | Merge two SFrames. Merges the current (left) SFrame with the given
(right) SFrame using a SQL-style equi-join operation by columns.
Parameters
----------
right : SFrame
The SFrame to join.
on : None | str | list | dict, optional
The column name(s) repres... |
368,709 | def requires_list(self):
requires = self.variant.get_requires(build_requires=self.building)
reqlist = RequirementList(requires)
if reqlist.conflict:
raise ResolveError(
"The package %s has an internal requirements conflict: %s"
% (str(self), ... | It is important that this property is calculated lazily. Getting the
'requires' attribute may trigger a package load, which may be avoided if
this variant is reduced away before that happens. |
368,710 | def save_history(self):
open(self.LOG_PATH, ).write("\n".join( \
[to_text_string(self.pydocbrowser.url_combo.itemText(index))
for index in range(self.pydocbrowser.url_combo.count())])) | Save history to a text file in user home directory |
368,711 | def from_dict(cls, d):
key = d.get("name")
options = d.get("options", None)
subkey_list = d.get("subkeys", [])
if len(subkey_list) > 0:
subkeys = list(map(lambda k: AdfKey.from_dict(k), subkey_list))
else:
subkeys = None
return cls(key, op... | Construct a MSONable AdfKey object from the JSON dict.
Parameters
----------
d : dict
A dict of saved attributes.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the JSON dict ``d``. |
368,712 | def connect(self, protocol=None, mode=None, disposition=None):
CardConnection.connect(self, protocol)
pcscprotocol = translateprotocolmask(protocol)
if 0 == pcscprotocol:
pcscprotocol = self.getProtocol()
if mode == None:
mode = SCARD_SHARE_SHARED
... | Connect to the card.
If protocol is not specified, connect with the default
connection protocol.
If mode is not specified, connect with SCARD_SHARE_SHARED. |
368,713 | def add_chapter(self, title):
chap_id = % self.chap_counter
self.chap_counter += 1
self.sidebar += % (
chap_id, title)
self.body += % (chap_id, title) | Adds a new chapter to the report.
:param str title: Title of the chapter. |
368,714 | def rlmb_tiny_recurrent():
hparams = rlmb_ppo_tiny()
hparams.epochs = 1
hparams.generative_model = "next_frame_basic_recurrent"
hparams.generative_model_params = "next_frame_basic_recurrent"
return hparams | Tiny setting with a recurrent next-frame model. |
368,715 | def commit_account_vesting(self, block_height):
log.debug("Commit all database state before vesting")
self.db.commit()
if block_height in self.vesting:
traceback.print_stack()
log.fatal("Tried to vest tokens twice at {}".format(block_height))
... | vest any tokens at this block height |
368,716 | def _initialize_global_state(self,
redis_address,
redis_password=None,
timeout=20):
self.redis_client = services.create_redis_client(
redis_address, redis_password)
start_time = time.t... | Initialize the GlobalState object by connecting to Redis.
It's possible that certain keys in Redis may not have been fully
populated yet. In this case, we will retry this method until they have
been populated or we exceed a timeout.
Args:
redis_address: The Redis address to... |
368,717 | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
message = txdbus.MethodCallMessage(path, method, interface=interface,
destination=service, signature=signature, body=args... | Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *service*, at path *path*, on interface
*interface*.
The *signature* and *args* are optional arguments that can be used to
add parameters ... |
368,718 | def mark_locations(h,section,locs,markspec=,**kwargs):
xyz = get_section_path(h,section)
(r,theta,phi) = sequential_spherical(xyz)
rcum = np.append(0,np.cumsum(r))
if type(locs) is float or type(locs) is np.float64:
locs = np.array([locs])
if type(locs) is list:
locs... | Marks one or more locations on along a section. Could be used to
mark the location of a recording or electrical stimulation.
Args:
h = hocObject to interface with neuron
section = reference to section
locs = float between 0 and 1, or array of floats
optional arguments specify de... |
368,719 | def get_trips(self, timestamp, start, via, destination, departure=True, prev_advices=1, next_advices=1):
timezonestring =
if is_dst():
timezonestring =
url =
url = url + + start
url = url + + destination
if via:
url = url + + via
... | Fetch trip possibilities for these parameters
http://webservices.ns.nl/ns-api-treinplanner?<parameters>
fromStation
toStation
dateTime: 2012-02-21T15:50
departure: true for starting at timestamp, false for arriving at timestamp
previousAdvices
nextAdvices |
368,720 | def get_state(self, force_update=False):
if force_update or self._state is None:
return int(self.basicevent.GetBinaryState()[])
return self._state | Returns 0 if off and 1 if on. |
368,721 | def get_conversation(self, conversation, **kwargs):
from canvasapi.conversation import Conversation
conversation_id = obj_or_id(conversation, "conversation", (Conversation,))
response = self.__requester.request(
,
.format(conversation_id),
_kwargs=c... | Return single Conversation
:calls: `GET /api/v1/conversations/:id \
<https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_
:param conversation: The object or ID of the conversation.
:type conversation: :class:`canvasapi.conversation.Conversation` or int... |
368,722 | def reloaded(name, jboss_config, timeout=60, interval=5):
jboss
log.debug(" ======================== STATE: jboss7.reloaded (name: %s) ", name)
ret = {: name,
: True,
: {},
: }
status = __salt__[](jboss_config)
if not status[] or status[] not in (, ):
ret[] ... | Reloads configuration of jboss server.
jboss_config:
Dict with connection properties (see state description)
timeout:
Time to wait until jboss is back in running state. Default timeout is 60s.
interval:
Interval between state checks. Default interval is 5s. Decreasing the interval m... |
368,723 | def __set_variable_watch(self, tid, address, size, action):
if size == 1:
sizeFlag = self.BP_WATCH_BYTE
elif size == 2:
sizeFlag = self.BP_WATCH_WORD
elif size == 4:
sizeFlag = self.BP_WATCH_DWORD
elif siz... | Used by L{watch_variable} and L{stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@param size: Size of variable to watch. The only supported sizes are:
by... |
368,724 | def _check_exclude(self, val):
if val is None:
exclude = frozenset()
elif isinstance(val, str):
exclude = frozenset([val.lower()])
else:
exclude = frozenset(map(lambda s: s.lower(), val))
if len(exclude - frozenset(METRICS)) > 0:
... | Validate the excluded metrics. Returns the set of excluded params. |
368,725 | async def _dump_variant(self, writer, elem, elem_type=None, params=None):
if isinstance(elem, VariantType) or elem_type.WRAPS_VALUE:
await dump_uint(writer, elem.variant_elem_type.VARIANT_CODE, 1)
await self.dump_field(
writer, getattr(elem, elem.variant_elem), e... | Dumps variant type to the writer.
Supports both wrapped and raw variant.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: |
368,726 | def gaussian_polygons(points, n=10):
gdf = gpd.GeoDataFrame(data={: classify_clusters(points, n=n)}, geometry=points)
polygons = []
for i in range(n):
sel_points = gdf[gdf[] == i].geometry
polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull)
pol... | Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point`
objects. |
368,727 | def ShowInfo(self):
self._output_writer.Write(
.format())
plugin_list = self._GetPluginData()
for header, data in plugin_list.items():
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=[, ],
title=header)
for entry_header, entry... | Shows information about available hashers, parsers, plugins, etc. |
368,728 | def resolveWithMib(self, mibViewController):
if self._state & self.ST_CLEAM:
return self
self._args[0].resolveWithMib(mibViewController)
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
, , )
if not isinstance(self._args[0].getMi... | Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectT... |
368,729 | def new_app(self, App, prefix=None, callable=None, **params):
params.update(self.cfg.params)
params.pop(, None)
prefix = prefix or
if not prefix and in self._apps:
prefix = App.name or App.__name__.lower()
if not prefix:
name = self.name
... | Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for the application,
the prefix is appended to
the a... |
368,730 | def main():
last_known =
if os.path.isfile(metafile):
with open(metafile) as fh:
last_known = fh.read()
import mbed_cloud
current = mbed_cloud.__version__
sigfigs = 4
current_version = LooseVersion(current).version
last_known_version = LooseVersion(last_... | Writes out newsfile if significant version bump |
368,731 | def _remove_unicode_keys(dictobj):
if sys.version_info[:2] >= (3, 0): return dictobj
assert isinstance(dictobj, dict)
newdict = {}
for key, value in dictobj.items():
if type(key) is unicode:
key = key.encode()
newdict[key] = value
return newdict | Convert keys from 'unicode' to 'str' type.
workaround for <http://bugs.python.org/issue2646> |
368,732 | def post_license_request(request):
uuid_ = request.matchdict[]
posted_data = request.json
license_url = posted_data.get()
licensors = posted_data.get(, [])
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute(, (uuid_,))
try:
... | Submission to create a license acceptance request. |
368,733 | def begin_data_item_live(self, data_item):
with self.__live_data_items_lock:
old_live_count = self.__live_data_items.get(data_item.uuid, 0)
self.__live_data_items[data_item.uuid] = old_live_count + 1
if old_live_count == 0:
data_item._enter_live_state()
... | Begins a live state for the data item.
The live state is propagated to dependent data items.
This method is thread safe. See slow_test_dependent_data_item_removed_while_live_data_item_becomes_unlive. |
368,734 | def clean_all(self, config_file, region=None, profile_name=None):
logging.info()
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is True:
raise ValueError("Config is already clean.")
if region is None:
region = self._region
... | Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `a... |
368,735 | def prep_for_deserialize(model, record, using, init_list=None):
attribs = record.pop()
mod = model.__module__.split()
if hasattr(model._meta, ):
app_label = getattr(model._meta, )
elif mod[-1] == :
app_label = mod[-2]
else:
raise ImproperlyConfigured("Can.Id'),... | Convert a record from SFDC (decoded JSON) to dict(model string, pk, fields)
If fixes fields of some types. If names of required fields `init_list `are
specified, then only these fields are processed. |
368,736 | def annotate_snv(adpter, variant):
variant_id = get_variant_id(variant)
variant_obj = adapter.get_variant(variant={:variant_id})
annotated_variant = annotated_variant(variant, variant_obj)
return annotated_variant | Annotate an SNV/INDEL variant
Args:
adapter(loqusdb.plugin.adapter)
variant(cyvcf2.Variant) |
368,737 | def _is_child_wikicode(self, obj, recursive=True):
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent
return nodes
target = deref(obj.nodes)
if target is deref(self.nodes):
return True
if recursive:
... | Return whether the given :class:`.Wikicode` is a descendant. |
368,738 | def do_commander(self):
if self._args.commands is not None:
cmds = []
for cmd in self._args.commands:
cmds.append(flatten_args(split_command_line(arg) for arg in cmd))
else:
cmds = None
PyOCDCommander(self._args, cmd... | ! @brief Handle 'commander' subcommand. |
368,739 | def _match_tags(repex_tags, path_tags):
if in repex_tags or (not repex_tags and not path_tags):
return True
elif set(repex_tags) & set(path_tags):
return True
return False | Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match. |
368,740 | def send_message(self, *args, **kwargs):
return send_message(*args, **self._merge_overrides(**kwargs)).run() | See :func:`send_message` |
368,741 | def header(self):
self.config.display.format_strings(self.HEADER_FORMAT, self.RESULT_FORMAT)
self.config.display.add_custom_header(self.VERBOSE_FORMAT, self.VERBOSE)
if type(self.HEADER) == type([]):
self.config.display.header(*self.HEADER, file_name=self.current_target_fil... | Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None. |
368,742 | def set_window_option(self, option, value):
self.server._update_windows()
if isinstance(value, bool) and value:
value =
elif isinstance(value, bool) and not value:
value =
cmd = self.cmd(
,
% (self.get(), self.index),
... | Wrapper for ``$ tmux set-window-option <option> <value>``.
Parameters
----------
option : str
option to set, e.g. 'aggressive-resize'
value : str
window option value. True/False will turn in 'on' and 'off',
also accepts string of 'on' or 'off' directl... |
368,743 | def save(self, exclude_scopes: tuple = (,)) -> None:
if not hasattr(self, ):
raise RuntimeError(
.format(self.__class__.__name__))
path = str(self.save_path.resolve())
log.info(.format(path))
var_list = self._get_saveable_variables(excl... | Save model parameters to self.save_path |
368,744 | def gen_colors(img):
magick_command = has_im()
for i in range(0, 20, 1):
raw_colors = imagemagick(16 + i, img, magick_command)
if len(raw_colors) > 16:
break
elif i == 19:
logging.error("Imagemagick couldnt generate a palette.")
logging.warning... | Format the output from imagemagick into a list
of hex colors. |
368,745 | def sanity_check_execution_spec(execution_spec):
def_ = dict(type="single",
distributed_spec=None,
session_config=None)
if execution_spec is None:
return def_
assert isinstance(execution_spec, dict), "ERROR: execution-spec needs to be of type dict (but is... | Sanity checks a execution_spec dict, used to define execution logic (distributed vs single, shared memories, etc..)
and distributed learning behavior of agents/models.
Throws an error or warns if mismatches are found.
Args:
execution_spec (Union[None,dict]): The spec-dict to check (or None). Dict n... |
368,746 | def within_miles(self, key, point, max_distance, min_distance=None):
if min_distance is not None:
min_distance = min_distance / 3958.8
return self.within_radians(key, point, max_distance / 3958.8, min_distance) | 增加查询条件,限制返回结果指定字段值的位置在某点的一段距离之内。
:param key: 查询条件字段名
:param point: 查询地理位置
:param max_distance: 最大距离限定(英里)
:param min_distance: 最小距离限定(英里)
:rtype: Query |
368,747 | def get_distributed_seismicity_source_nodes(source):
source_nodes = []
source_nodes.append(
Node("magScaleRel",
text=source.magnitude_scaling_relationship.__class__.__name__))
source_nodes.append(
Node("ruptAspectRatio", text=source.rupture_aspect_ratio))
... | Returns list of nodes of attributes common to all distributed seismicity
source classes
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.area.AreaSource` or :class:
`openquake.hazardlib.source.point.PointSource`
:returns:
List of instances of ... |
368,748 | def print_update(self):
print("\r\n")
now = datetime.datetime.now()
print("Update info: (from: %s)" % now.strftime("%c"))
current_total_size = self.total_stined_bytes + self.total_new_bytes
if self.total_errored_items:
print(" * WARNING: %i omitted files!" ... | print some status information in between. |
368,749 | def get_id(self, grp):
thehash = hex(hash(grp))
if ISPY3:
thehash = thehash.encode()
return self.cache.get(grp, hashlib.sha1(thehash).hexdigest()) | Return a hash of the tuple of indices that specify the group |
368,750 | def get_versioning_status(self, headers=None):
response = self.connection.make_request(, self.name,
query_args=, headers=headers)
body = response.read()
boto.log.debug(body)
if response.status == 200:
d = {}
ver = re.search(self.VersionRE,... | Returns the current status of versioning on the bucket.
:rtype: dict
:returns: A dictionary containing a key named 'Versioning'
that can have a value of either Enabled, Disabled,
or Suspended. Also, if MFADelete has ever been enabled
on the bucket, ... |
368,751 | def _co_moving2angle(self, x, y, idex):
T_z = self._T_z_list[idex]
theta_x = x / T_z
theta_y = y / T_z
return theta_x, theta_y | transforms co-moving distances Mpc into angles on the sky (radian)
:param x: co-moving distance
:param y: co-moving distance
:param z_lens: redshift of plane
:return: angles on the sky |
368,752 | def install_builtin (translator, do_unicode):
try:
import __builtin__ as builtins
except ImportError:
import builtins
has_unicode = hasattr(translator, )
if do_unicode and has_unicode:
builtins.__dict__[] = translator.ugettext
builtins.__dict__... | Install _() and _n() gettext methods into default namespace. |
368,753 | async def bluetooth(dev: Device, target, value):
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings()) | Get or set bluetooth settings. |
368,754 | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_stream = BytearrayStream()
if self._wrapping_method:
self._wrapping_method.write(
local_stream,
kmip_version=kmip_version
)
else:
raise Val... | Write the data encoding the KeyWrappingSpecification struct to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... |
368,755 | def add_external_path(self, path):
if not osp.exists(path):
return
self.removeItem(self.findText(path))
self.addItem(path)
self.setItemData(self.count() - 1, path, Qt.ToolTipRole)
while self.count() > MAX_PATH_HISTORY + EXTERNAL_PATHS:
sel... | Adds an external path to the combobox if it exists on the file system.
If the path is already listed in the combobox, it is removed from its
current position and added back at the end. If the maximum number of
paths is reached, the oldest external path is removed from the list. |
368,756 | def difference_of_pandas_dfs(df_self, df_other, col_names=None):
df = pd.concat([df_self, df_other])
df = df.reset_index(drop=True)
df_gpby = df.groupby(col_names)
idx = [x[0] for x in list(df_gpby.groups.values()) if len(x) == 1]
df_sym_diff = df.reindex(idx)
df_diff = pd.concat([df_other,... | Returns a dataframe with all of df_other that are not in df_self, when considering the columns specified in col_names
:param df_self: pandas Dataframe
:param df_other: pandas Dataframe
:param col_names: list of column names
:return: |
368,757 | def _format_date(self, obj) -> str:
if obj is None:
return
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, ) | Short date format.
:param obj: date or datetime or None
:return: str |
368,758 | def _reprJSON(self):
return {: (self.id, self.specfile, self.dataProcessingRef,
self.precursor, self.product, self.params,
self.attrib, self.arrayInfo
)
} | Returns a JSON serializable represenation of a ``Ci`` class instance.
Use :func:`maspy.core.Ci._fromJSON()` to generate a new ``Ci`` instance
from the return value.
:returns: a JSON serializable python object |
368,759 | def getAverageBuildDuration(self, package, **kwargs):
seconds = yield self.call(, package, **kwargs)
if seconds is None:
defer.returnValue(None)
defer.returnValue(timedelta(seconds=seconds)) | Return a timedelta that Koji considers to be average for this package.
Calls "getAverageBuildDuration" XML-RPC.
:param package: ``str``, for example "ceph"
:returns: deferred that when fired returns a datetime object for the
estimated duration, or None if we could find no est... |
368,760 | def add_layer_to_canvas(layer, name):
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
QgsProject.instance().addMapLayer(layer, False) | Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str |
368,761 | def CROSS(A, B):
var = np.where(A < B, 1, 0)
return (pd.Series(var, index=A.index).diff() < 0).apply(int) | A<B then A>B A上穿B B下穿A
Arguments:
A {[type]} -- [description]
B {[type]} -- [description]
Returns:
[type] -- [description] |
368,762 | def as_xml(self,parent):
n=parent.newChild(None,self.name.upper(),None)
if self.type:
n.newTextChild(None,"TYPE",self.type)
n.newTextChild(None,"CRED",binascii.b2a_base64(self.cred))
return n | Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode` |
368,763 | def scale(s, dtype=None):
assert len(s) == 3
return np.array(np.diag(np.concatenate([s, (1.,)])), dtype) | Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing the scaling. |
368,764 | def convert(self, request, response, data):
return self.escape(request.environ.get(, {}).get(
self.modifier.param, )) | Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary returned by the prepare()
... |
368,765 | def u_base(self, theta, phi, lam, q):
return self.append(UBase(theta, phi, lam), [q], []) | Apply U to q. |
368,766 | def build_phenotype(phenotype_id, adapter):
phenotype_obj = {}
phenotype = adapter.hpo_term(phenotype_id)
if phenotype:
phenotype_obj[] = phenotype[]
phenotype_obj[] = phenotype[]
return phenotype | Build a small phenotype object
Build a dictionary with phenotype_id and description
Args:
phenotype_id (str): The phenotype id
adapter (scout.adapter.MongoAdapter)
Returns:
phenotype_obj (dict):
dict(
phenotype_id = str,
feature = str, # descri... |
368,767 | def set(self, property_dict):
self.metadata = self.db.update(self.path, property_dict).json() | Attempts to set the given properties of the object.
An example of this is setting the nickname of the object::
cdb.set({"nickname": "My new nickname"})
note that there is a convenience property `cdb.nickname` that allows you to get/set the nickname directly. |
368,768 | def group_pairs(blocks, layout_blocks_list):
image_dict={}
for block_id in layout_blocks_list:
image_seq=blocks[block_id].ec_hdr.image_seq
if image_seq not in image_dict:
image_dict[image_seq]=[block_id]
else:
image_dict[image_seq].append(block_id)
log(... | Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list |
368,769 | def _adjust_to_origin(arg, origin, unit):
if origin == :
original = arg
j0 = Timestamp(0).to_julian_date()
if unit != :
raise ValueError("unit must be for origin=")
try:
arg = arg - j0
except TypeError:
raise ValueError("incompatible ... | Helper function for to_datetime.
Adjust input argument to the specified origin
Parameters
----------
arg : list, tuple, ndarray, Series, Index
date to be adjusted
origin : 'julian' or Timestamp
origin offset for the arg
unit : string
passed unit from to_datetime, must be... |
368,770 | def resolved_row(objs, geomatcher):
def get_locations(lst):
for elem in lst:
try:
yield elem[]
except TypeError:
yield elem
geomatcher[] = geomatcher.faces.difference(
reduce(
set.union,
[geomatcher[obj] for ob... | Temporarily insert ``RoW`` into ``geomatcher.topology``, defined by the topo faces not used in ``objs``.
Will overwrite any existing ``RoW``.
On exiting the context manager, ``RoW`` is deleted. |
368,771 | def _quadrature_expectation(p, obj1, feature1, obj2, feature2, num_gauss_hermite_points):
num_gauss_hermite_points = 40 if num_gauss_hermite_points is None else num_gauss_hermite_points
if obj2 is None:
eval_func = lambda x: get_eval_func(obj1, feature1)(x)
mu, cov = p.mu[:-1], p.cov[0, :-... | Handling of quadrature expectations for Markov Gaussians (useful for time series)
Fallback method for missing analytic expectations wrt Markov Gaussians
Nota Bene: obj1 is always associated with x_n, whereas obj2 always with x_{n+1}
if one requires e.g. <x_{n+1} K_{x_n, Z}>_p(x_{n:n+1}), compute ... |
368,772 | def ml_acr(tree, character, prediction_method, model, states, avg_br_len, num_nodes, num_tips, freqs=None, sf=None,
kappa=None, force_joint=True):
n = len(states)
state2index = dict(zip(states, range(n)))
missing_data = 0.
observed_frequencies = np.zeros(n, np.float64)
for _ in tree:... | Calculates ML states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param prediction_method: str, MPPA (marginal approximation), MAP (max a posteriori) or JOINT
:param tree: ete3.Tree, the tree of interest
:param character: str, character for wh... |
368,773 | def configure_root():
root_logger = logging.getLogger()
for hdlr in root_logger.handlers:
if isinstance(hdlr, logging.StreamHandler):
root_logger.removeHandler(hdlr)
root_logger.setLevel(ROOT_LOG_LEVEL)
hdlr = logging.StreamHandler(ROOT_LOG_STREAM)
formatter = c... | Configure the root logger. |
368,774 | def video_l1_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
del vocab_size
logits = top_out
logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:-1])
targets = tf.reshape(targets, [-1] + common_layers.shape_list(targets)[2:])
weights = weights_fn(targets)
ta... | Compute loss numerator and denominator for one shard of output. |
368,775 | def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity=, kpc_per_arcsec=None, exposure_time=None):
if self.has_light_profile:
return sum(map(lambda p: p.luminosity_within_ellipse_in_units(major_axis=major_axis, unit_luminosity=unit_luminosity,
... | Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This
is performed via integration of each light profile and is centred, oriented and aligned with each light
model's individual geometry.
See *light_profiles.luminosity_within_ellipse* for d... |
368,776 | def _build_epsf_step(self, stars, epsf=None):
if len(stars) < 1:
raise ValueError(
)
if epsf is None:
epsf = self._create_initial_epsf(stars)
else:
epsf = copy.deepcopy(epsf)
r... | A single iteration of improving an ePSF.
Parameters
----------
stars : `EPSFStars` object
The stars used to build the ePSF.
epsf : `EPSFModel` object, optional
The initial ePSF model. If not input, then the ePSF will be
built from scratch.
... |
368,777 | def connect(self, protocol_factory):
protocol_factory.set_vhost(self._vhost)
protocol_factory.set_heartbeat(self._heartbeat)
description = "tcp:{}:{}:timeout={}".format(
self._host, self._port, self._timeout)
endpoint = clientFromString(self._react... | Connect to the C{protocolFactory} to the AMQP broker specified by the
URI of this endpoint.
@param protocol_factory: An L{AMQFactory} building L{AMQClient} objects.
@return: A L{Deferred} that results in an L{AMQClient} upon successful
connection otherwise a L{Failure} wrapping L{Co... |
368,778 | def step_until_intersect(pos, field_line, sign, time, direction=None,
step_size_goal=5.,
field_step_size=None):
field_copy = field_line
last_min_dist = 2500000.
scalar = 0.
... | Starting at pos, method steps along magnetic unit vector direction
towards the supplied field line trace. Determines the distance of
closest approach to field line.
Routine is used when calculting the mapping of electric fields along
magnetic field lines. Voltage remains constant along the field... |
368,779 | def register_metric(self, name, metric, time_bucket_in_sec):
if name in self.metrics_map:
raise RuntimeError("Another metric has already been registered with name: %s" % name)
Log.debug("Register metric: %s, with interval: %s", name, str(time_bucket_in_sec))
self.metrics_map[name] = metric
... | Registers a given metric
:param name: name of the metric
:param metric: IMetric object to be registered
:param time_bucket_in_sec: time interval for update to the metrics manager |
368,780 | def find_num_contigs(contig_lengths_dict):
num_contigs_dict = dict()
for file_name, contig_lengths in contig_lengths_dict.items():
num_contigs_dict[file_name] = len(contig_lengths)
return num_contigs_dict | Count the total number of contigs for each strain
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:return: num_contigs_dict: dictionary of strain name: total number of contigs |
368,781 | def prettyMatcherList(things):
norm = []
for x in makeSequence(things):
if hasattr(x, ):
norm.append(x.pattern)
else:
norm.append(x)
return "()" % "".join(norm) | Try to construct a nicely-formatted string for a list of matcher
objects. Those may be compiled regular expressions or strings... |
368,782 | def has_pubmed(edge_data: EdgeData) -> bool:
return CITATION in edge_data and CITATION_TYPE_PUBMED == edge_data[CITATION][CITATION_TYPE] | Check if the edge has a PubMed citation. |
368,783 | def sigint_handler(self, signum: int, frame) -> None:
if self.cur_pipe_proc_reader is not None:
self.cur_pipe_proc_reader.send_sigint()
if not self.sigint_protection:
raise KeyboardInterrupt("Got a keyboard interrupt") | Signal handler for SIGINTs which typically come from Ctrl-C events.
If you need custom SIGINT behavior, then override this function.
:param signum: signal number
:param frame |
368,784 | def __encode_items(self, items):
xs = [item._asdict() for (_key, item) in items.items()]
return list(map(lambda x: dict(zip(x.keys(), x.values())), xs)) | Encodes the InvoiceItems into a JSON serializable format
items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2,
unit_price='3500', total_price='7000',
description='VIP Tickets for party')),...] |
368,785 | def hide_arp_holder_arp_entry_mac_address_value(self, **kwargs):
config = ET.Element("config")
hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp")
arp_entry = ET.SubElement(hide_arp_holder, "arp-entry")
arp_ip_address_key = ET.Sub... | Auto Generated Code |
368,786 | def alexnet(pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), ), **kwargs):
r
net = AlexNet(**kwargs)
if pretrained:
from ..model_store import get_model_file
net.load_parameters(get_model_file(, root=root), ctx=ctx)
return net | r"""AlexNet model from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root :... |
368,787 | def plot_series(self, xres, varied_data, varied_idx, **kwargs):
for attr in .split():
if kwargs.get(attr, None) is None:
kwargs[attr] = getattr(self, attr)
ax = plot_series(xres, varied_data, **kwargs)
if self.par_by_name and isinstance(varied_idx, str):
... | Plots the results from :meth:`solve_series`.
Parameters
----------
xres : array
Of shape ``(varied_data.size, self.nx)``.
varied_data : array
See :meth:`solve_series`.
varied_idx : int or str
See :meth:`solve_series`.
\\*\\*kwargs :
... |
368,788 | def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
content = theFile.get_text_contents()
if Verbose:
print(" scanning ",str(theFile))
for i in range(len(file_tests_search)):
if file_tests[i][0] is None:
if ... | For theFile (a Node) update any file_tests and search for graphics files
then find all included files and call ScanFiles recursively for each of them |
368,789 | def clear(self):
r = self._h._http_resource(
method=,
resource=(, ),
)
return r.ok | Removes all SSH keys from a user's system. |
368,790 | def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] = stack_index
return self._get_c... | Get a stacked bar chart |
368,791 | def attached_partition(self):
if self._attached_partition is None:
part_mgr = self.manager.storage_group.manager.cpc.partitions
part = part_mgr.resource_object(self.get_property())
self._attached_partition = part
return self._attached_partition | :class:`~zhmcclient.Partition`: The partition to which this virtual
storage resource is attached.
The returned partition object has only a minimal set of properties set
('object-id', 'object-uri', 'class', 'parent').
Note that a virtual storage resource is always attached to a partitio... |
368,792 | def prettify_xml(elem):
from xml.dom import minidom
import xml.etree.cElementTree as et
rough_string = et.tostring(elem, )
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | Return a pretty-printed XML string for the Element. |
368,793 | def validate_unique(self, *args, **kwargs):
super(EighthSignup, self).validate_unique(*args, **kwargs)
if self.has_conflict():
raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already exists for the User and the EighthScheduledActivity's block",)}) | Checked whether more than one EighthSignup exists for a User on a given EighthBlock. |
368,794 | def DEFINE_multi_enum_class(
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
**args):
DEFINE_flag(
_flag.MultiEnumClassFlag(name, default, help, enum_class),
flag_values, module_name, **args) | Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple
enum values into the list.
Args:
name: str, the flag name.
default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
default value of the flag; see
`D... |
368,795 | def _fix_path(self, path):
if path.endswith():
path = path.rstrip()
return safe_str(path) | Paths are stored without trailing slash so we need to get rid off it if
needed. Also mercurial keeps filenodes as str so we need to decode
from unicode to str |
368,796 | def next_event(self, delete=False):
if delete:
msg = "Delete this event? This cannot be undone."
msgbox = QMessageBox(QMessageBox.Question, , msg)
msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgbox.setDefaultButton(QMessageBox.Yes)
... | Go to next event. |
368,797 | def save(self):
content = self.dumps()
fileutils.save_text_to_file(content, self.file_path) | Saves the settings contents |
368,798 | def prepend_name_scope(name, import_scope):
if import_scope:
try:
str_to_replace = r"([\^]|loc:@|^)(.*)"
return re.sub(str_to_replace, r"\1" + import_scope + r"/\2",
tf.compat.as_str_any(name))
except TypeError as e:
logging.warning(e)
return name
els... | Prepends name scope to a name. |
368,799 | def to_model(self):
e = ApiPool().current_server_api.model.Error(
status=self.status,
error=self.code.upper(),
error_description=str(self),
)
if self.error_id:
e.error_id = self.error_id
if self.user_message:
e.user_mes... | Return a bravado-core Error instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.