Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
383,900 | def mod_repo(repo, **kwargs):
s configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt pkg.mod_repo alias alias=new_alias
... | Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (Tru... |
383,901 | def cleanup(arctic_lib, symbol, version_ids, versions_coll, shas_to_delete=None, pointers_cfgs=None):
pointers_cfgs = set(pointers_cfgs) if pointers_cfgs else set()
collection = arctic_lib.get_top_level_collection()
version_ids = list(version_ids)
all_symbol_pointers_cfgs = _get_symbol_p... | Helper method for cleaning up chunks from a version store |
383,902 | def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None):
if not isinstance(dataFrame, pandas.core.frame.DataFrame):
raise TypeError("not of type pandas.core.frame.DataFrame")
self.layoutAboutToBeChanged.emit()
if copyDataFrame:
self._dataFrame = da... | Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFr... |
383,903 | def getAttributeNode(self, attr: str) -> Optional[Attr]:
return self.attributes.getNamedItem(attr) | Get attribute of this node as Attr format.
If this node does not have ``attr``, return None. |
383,904 | def processes(self, plantuml_text):
url = self.get_url(plantuml_text)
try:
response, content = self.http.request(url, **self.request_opts)
except self.HttpLib2Error as e:
raise PlantUMLConnectionError(e)
if response.status != 200:
raise PlantU... | Processes the plantuml text into the raw PNG image data.
:param str plantuml_text: The plantuml markup to render
:returns: the raw image data |
383,905 | def add(name, function_name, cron):
lambder.add_event(name=name, function_name=function_name, cron=cron) | Create an event |
383,906 | def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
self.consumer_key = consumer_key or self.consumer_key
self.consumer_secret = consumer_secret or self.consumer_secret
self.access_token = access_token... | After converting the token into verifier, call this to finalize the
authorization. |
383,907 | def disvecinf(self, x, y, aq=None):
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rv = np.zeros((2, self.nparam, aq.naq))
if aq == self.aq:
qxqy = np.zeros((2, aq.naq))
qxqy[:, :] = self.bessel.disbeslsho(float(x), float(y), self.z1, self.z2, aq.lab,
... | Can be called with only one x,y value |
383,908 | def desaturate(c, k=0):
from matplotlib.colors import ColorConverter
c = ColorConverter().to_rgb(c)
intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
return [intensity * k + i * (1 - k) for i in c] | Utility function to desaturate a color c by an amount k. |
383,909 | def add_marker_to_qtls(qtlfile, mapfile, outputfile=):
qtl_list = read_input_file(qtlfile, )
map_list = read_input_file(mapfile, )
if not qtl_list or not map_list:
return
qtl_list[0].append()
qtls = []
qtls.append(qtl_list[0])
for qtl in qtl_list[1:]:
qtl.append(add_ma... | This function adds to a list of QTLs, the closest marker to the
QTL peak.
:arg qtlfile: a CSV list of all the QTLs found.
The file should be structured as follow::
Trait, Linkage group, position, other columns
The other columns will not matter as long as the first three
col... |
383,910 | def initial(self, request, *args, **kwargs):
super(NodeImageList, self).initial(request, *args, **kwargs)
self.node = get_queryset_or_404(
Node.objects.published().accessible_to(request.user),
{: self.kwargs[]}
)
self.check_object_permis... | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node |
383,911 | def _setSampleSizeBytes(self):
self.sampleSizeBytes = self.getPacketSize()
if self.sampleSizeBytes > 0:
self.maxBytesPerFifoRead = (32 // self.sampleSizeBytes) | updates the current record of the packet size per sample and the relationship between this and the fifo reads. |
383,912 | def get_authorizations_for_resource_and_function(self, resource_id, function_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(
... | Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list contains all known authorizations or an error
results. Otherwise, the returned... |
383,913 | def from_seqfeature(s, **kwargs):
source = s.qualifiers.get(, )[0]
score = s.qualifiers.get(, )[0]
seqid = s.qualifiers.get(, )[0]
frame = s.qualifiers.get(, )[0]
strand = _feature_strand[s.strand]
start = s.location.start.position + 1
stop = s.location.end.position
featu... | Converts a Bio.SeqFeature object to a gffutils.Feature object.
The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be
stored as qualifiers. Any other qualifiers will be assumed to be GFF
attributes. |
383,914 | def remove_straddlers(events, time, s_freq, toler=0.1):
dur = (events[:, -1] - 1 - events[:, 0]) / s_freq
continuous = time[events[:, -1] - 1] - time[events[:, 0]] - dur < toler
return events[continuous, :] | Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
... |
383,915 | def ekopr(fname):
fname = stypes.stringToCharP(fname)
handle = ctypes.c_int()
libspice.ekopr_c(fname, ctypes.byref(handle))
return handle.value | Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int |
383,916 | def build_machine(system_info,
core_resource=Cores,
sdram_resource=SDRAM,
sram_resource=SRAM):
try:
max_cores = max(c.num_cores for c in itervalues(system_info))
except ValueError:
max_cores = 0
try:
max_sdram = max(c.larges... | Build a :py:class:`~rig.place_and_route.Machine` object from a
:py:class:`~rig.machine_control.machine_controller.SystemInfo` object.
.. note::
Links are tested by sending a 'PEEK' command down the link which
checks to see if the remote device responds correctly. If the link
is dead, no... |
383,917 | def calibrate(self, data, key):
logger.warning()
if key.calibration == :
pass
elif key.calibration == :
pass
else:
pass
return data | Data calibration. |
383,918 | def get_app_name(self):
app_name = self.get_attribute_value(, )
if app_name is None:
activities = self.get_main_activities()
main_activity_name = None
if len(activities) > 0:
main_activity_name = activities.pop()
... | Return the appname of the APK
This name is read from the AndroidManifest.xml
using the application android:label.
If no label exists, the android:label of the main activity is used.
If there is also no main activity label, an empty string is returned.
:rtype: :class:`str` |
383,919 | def gather_votes(self, candidates):
votes = []
for a in self.get_agents(addr=False):
vote = a.vote(candidates)
votes.append(vote)
return votes | Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifact, preference)``
-tuples sorted in... |
383,920 | def _do_link_patterns(self, text):
link_from_hash = {}
for regex, repl in self.link_patterns:
replacements = []
for match in regex.finditer(text):
if hasattr(repl, "__call__"):
href = repl(match)
else:
... | Caveat emptor: there isn't much guarding against link
patterns being formed inside other standard Markdown links, e.g.
inside a [link def][like this].
Dev Notes: *Could* consider prefixing regexes with a negative
lookbehind assertion to attempt to guard against this. |
383,921 | def _prompt_choice(var_name, options):
choice_map = OrderedDict(
(.format(i), value) for i, value in enumerate(options, 1) if value[0] !=
)
choices = choice_map.keys()
default =
choice_lines = [.format(c[0], c[1][0], c[1][1]) for c in choice_map.items()]
prompt = .join((
... | Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
:type var_name: ``str``
:param options: A list of options
:type option... |
383,922 | def find_by_id(cls, id):
obj = cls.find_one(cls._id_spec(id))
if not obj:
raise NotFoundException(cls.collection, id)
return obj | Finds a single document by its ID. Throws a
NotFoundException if the document does not exist (the
assumption being if you've got an id you should be
pretty certain the thing exists) |
383,923 | def get_commands(self, command_name, **kwargs):
chip_id = kwargs.pop("ChipID", self.chip_id_bitarray)
commands = []
if command_name == "zeros":
bv = bitarray(endian=)
if "length" in kwargs:
bv += bitarray(kwargs["length"], endian=)
... | get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior |
383,924 | def sortByColumn(self, column, order=QtCore.Qt.AscendingOrder):
super(XTreeWidget, self).sortByColumn(column, order)
self._sortOrder = order | Overloads the default sortByColumn to record the order for later \
reference.
:param column | <int>
order | <QtCore.Qt.SortOrder> |
383,925 | def get_service_health(service_id: str) -> str:
if DC.get_replicas(service_id) != DC.get_actual_replica(service_id):
health_status = "Unhealthy"
else:
health_status = "Healthy"
return health_status | Get the health of a service using service_id.
Args:
service_id
Returns:
str, health status |
383,926 | def set_repo_permission(self, repo, permission):
assert isinstance(repo, github.Repository.Repository), repo
put_parameters = {
"permission": permission,
}
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.url + "/repos/" + repo... | :calls: `PUT /teams/:id/repos/:org/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:param permission: string
:rtype: None |
383,927 | def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"):
if fig is None:
fig = ax.get_figure()
if loc == "left" or loc == "right":
width = fig.get_figwidth()
new = width * (1 + _pc2f(size) + _pc2f(pad))
_logger.debug(.format(new))
elif loc == "top... | Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely.
.. versionadded:: 1.3
Parameters
----------
ax : :class:`matplotlib.axis.Axis`
The axis to plot to.
im : :class:`matplotlib.image.AxesImage`
The plotted image to use for the colorbar.
... |
383,928 | def init_layout(self):
super(AndroidRadioGroup, self).init_layout()
d = self.declaration
w = self.widget
if d.checked:
self.set_checked(d.checked)
else:
for c in d.children:
if c.checked:
d.checked ... | Set the checked state after all children have
been populated. |
383,929 | def detailxy(self, canvas, button, data_x, data_y):
if button == 0:
chviewer = self.fv.getfocus_viewer()
if chviewer != self.fitsimage:
return True
data_x = data_x + self.pick_x1
data_y ... | Motion event in the pick fits window. Show the pointing
information under the cursor. |
383,930 | def make_back_author_contributions(self, body):
cont_expr = "./front/article-meta/author-notes/fn[@fn-type=]"
contribution = self.article.root.xpath(cont_expr)
if contribution:
author_contrib = deepcopy(contribution[0])
remove_all_attributes(author_contrib)
... | Though this goes in the back of the document with the rest of the back
matter, it is not an element found under <back>.
I don't expect to see more than one of these. Compare this method to
make_article_info_competing_interests() |
383,931 | def get_usedby_aql(self, params):
if self._usedby is None:
return None
_result = {}
params = self.merge_valued(params)
for k, v in self._usedby[].items():
if isinstance(v, str):
k = k.format(**params)
v = v.format(**params... | Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return: |
383,932 | def _multiplyThroughputs(self):
index = 0
for component in self.components:
if component.throughput != None:
break
index += 1
return BaseObservationMode._multiplyThroughputs(self, index) | Overrides base class in order to deal with opaque components. |
383,933 | def _set_LED(self, status):
self.hw.remote_at(
dest_addr=self.remote_addr,
command=,
parameter= if status else ) | _set_LED: boolean -> None
Sets the status of the remote LED |
383,934 | def remove_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> None:
nodes = list(get_unweighted_sources(graph, key=key))
graph.remove_nodes_from(nodes) | Prune unannotated nodes on the periphery of the sub-graph.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data. Defaults to
:data:`pybel_tools.constants.WEIGHT`. |
383,935 | def open(self, url):
cache = self.cache()
id = self.mangle(url, )
d = cache.get(id)
if d is None:
d = self.fn(url, self.options)
cache.put(id, d)
else:
d.options = self.options
for imp in d.imports:
imp.impo... | Open a WSDL at the specified I{url}.
First, the WSDL attempted to be retrieved from
the I{object cache}. After unpickled from the cache, the
I{options} attribute is restored.
If not found, it is downloaded and instantiated using the
I{fn} constructor and added to the cache for t... |
383,936 | def weld_standard_deviation(array, weld_type):
weld_obj_var = weld_variance(array, weld_type)
obj_id, weld_obj = create_weld_object(weld_obj_var)
weld_obj_var_id = get_weld_obj_id(weld_obj, weld_obj_var)
weld_template = _weld_std_code
weld_obj.weld_code = weld_template.format(var=weld_obj_va... | Returns the *sample* standard deviation of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Representation of this computation. |
383,937 | def same(*values):
if not values:
return True
first, rest = values[0], values[1:]
return all(value == first for value in rest) | Check if all values in a sequence are equal.
Returns True on empty sequences.
Examples
--------
>>> same(1, 1, 1, 1)
True
>>> same(1, 2, 1)
False
>>> same()
True |
383,938 | def update_path(self, path):
oldpath = self.path
self.path = []
for p in path:
if p[0] != :
break
router = self.router_container.router_from_id(p)
self.path.append(router)
if len(se... | There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
LongName-style router names (this depends on the... |
383,939 | def _attributeLinesToDict(attributeLines):
attributes = dict()
for line in attributeLines:
attributeId, attributeValue = line.split(, 1)
attributes[attributeId.strip()] = attributeValue.strip()
return attributes | Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
NOTE: Some attributes can occur multiple times in... |
383,940 | def is_cozy_registered():
req = curl_couchdb()
users = req.json()[]
if len(users) > 0:
return True
else:
return False | Check if a Cozy is registered |
383,941 | def update(self, membershipId, isModerator=None, **request_parameters):
check_type(membershipId, basestring, may_be_none=False)
check_type(isModerator, bool)
put_data = dict_from_items_with_values(
request_parameters,
isModerator=isModerator,
)
... | Update a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
isModerator(bool): Set to True to make the person a team moderator.
**request_parameters: Additional request parameters (provides
support for parameters that may be added... |
383,942 | def get_asset_form_for_update(self, asset_id=None):
if asset_id is None:
raise NullArgument()
try:
url_path = construct_url(,
bank_id=self._catalog_idstr,
asset_id=asset_id)
asset = obj... | Gets the asset form for updating an existing asset.
A new asset form should be requested for each update
transaction.
:param asset_id: the ``Id`` of the ``Asset``
:type asset_id: ``osid.id.Id``
:return: the asset form
:rtype: ``osid.repository.AssetForm``
:raise... |
383,943 | def create_initial_tree(channel):
config.LOGGER.info(" Setting up initial channel structure... ")
tree = ChannelManager(channel)
config.LOGGER.info(" Validating channel structure...")
channel.print_tree()
tree.validate()
config.LOGGER.info(" Tree is valid\n")
return tre... | create_initial_tree: Create initial tree structure
Args:
channel (Channel): channel to construct
Returns: tree manager to run rest of steps |
383,944 | def _open_interface(self, client, uuid, iface, key):
conn_id = self._validate_connection(, uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data[] = monotonic()
slug = self._build_device_slug(uuid)
try:
re... | Open an interface on a connected device.
Args:
client (string): The client id who is requesting this operation
uuid (int): The id of the device we're opening the interface on
iface (string): The name of the interface that we're opening
key (string): The key to au... |
383,945 | async def handle_exception(self, exc: Exception, action: str, request_id):
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors(exc.detail),
status=exc.status_code,
request_id=request_id... | Handle any exception that occurs, by sending an appropriate message |
383,946 | def _get_2d_plot(self, label_stable=True, label_unstable=True,
ordering=None, energy_colormap=None, vmin_mev=-60.0,
vmax_mev=60.0, show_colorbar=True,
process_attributes=False, plt=None):
if plt is None:
plt = pretty_plot(8, 6)
... | Shows the plot using pylab. Usually I won't do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way. |
383,947 | def interface_endpoints(self):
api_version = self._get_api_version()
if api_version == :
from .v2018_08_01.operations import InterfaceEndpointsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
... | Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>` |
383,948 | def auth(self, encoded):
message, signature = self.split(encoded)
computed = self.sign(message)
if not hmac.compare_digest(signature, computed):
raise AuthenticatorInvalidSignature | Validate integrity of encoded bytes |
383,949 | def stopService(self):
self._service.factory.stopTrying()
yield self._service.factory.stopFactory()
yield service.MultiService.stopService(self) | Gracefully stop the service.
Returns:
defer.Deferred: a Deferred which is triggered when the service has
finished shutting down. |
383,950 | def create(self, request, *args, **kwargs):
return super(AlertViewSet, self).create(request, *args, **kwargs) | Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: appli... |
383,951 | def check_date_str_format(s, default_time="00:00:00"):
try:
str_fmt = s
if ":" not in s:
str_fmt = .format(s, default_time)
dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S")
return RET_OK, dt_obj
except ValueError:
error_str = ERROR_STR_PREFIX +... | Check the format of date string |
383,952 | def keywords_for(*args):
if isinstance(args[0], Model):
obj = args[0]
if getattr(obj, "content_model", None):
obj = obj.get_content_model()
keywords_name = obj.get_keywordsfield_name()
keywords_queryset = getattr(obj, keywords_name).all()
... | Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud. |
383,953 | def fix_symbol_store_path(symbol_store_path = None,
remote = True,
force = False):
try:
if symbol_store_path is None:
local_path = "C:\\SYMBOLS"
if not path.isdir(local_path):
loc... | Fix the symbol store path. Equivalent to the C{.symfix} command in
Microsoft WinDbg.
If the symbol store path environment variable hasn't been set, this
method will provide a default one.
@type symbol_store_path: str or None
@param symbol_store_path: (Optional) Symbol store pa... |
383,954 | def feeds(self):
url = self._build_url()
json = self._json(self._get(url), 200)
del json[]
del json[]
urls = [
, , ,
, ,
,
]
for url in urls:
json[url] = URITemplate(json[url])
links = json.ge... | List GitHub's timeline resources in Atom format.
:returns: dictionary parsed to include URITemplates |
383,955 | def add_to_matching_blacklist(db, entity):
with db.connect() as session:
try:
add_to_matching_blacklist_db(session, entity)
except ValueError as e:
raise InvalidValueError(e) | Add entity to the matching blacklist.
This function adds an 'entity' o term to the matching blacklist.
The term to add cannot have a None or empty value, in this case
a InvalidValueError will be raised. If the given 'entity' exists in the
registry, the function will raise an AlreadyExistsError exceptio... |
383,956 | def connect(self, host=, port=3306, user=, password=, database=None):
if database is None:
raise exceptions.RequiresDatabase()
self._db_args = { : host, : port, : user, : password, : database }
with self._db_conn() as conn:
conn.query()
return self | Connect to the database specified |
383,957 | def clear_title(self):
metadata = Metadata(**settings.METADATA[])
if metadata.is_read_only() or metadata.is_required():
raise NoAccess()
self._my_map[][] = | Removes the title.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
383,958 | async def debug(self, client_id, conn_string, command, args):
conn_id = self._client_info(client_id, )[conn_string]
return await self.adapter.debug(conn_id, command, args) | Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
... |
383,959 | def print_vertical(vertical_rows, labels, color, args):
if color:
sys.stdout.write(f)
for row in vertical_rows:
print(*row)
sys.stdout.write()
print("-" * len(row) + "Values" + "-" * len(row))
for value in zip_longest(*value_list, fillvalue=):
print(" ".join(v... | Print the whole vertical graph. |
383,960 | def transfer(sendContext, receiveContext, chunkSize):
try:
chunkSize = receiveContext.chunkSize
except AttributeError:
pass
if sendContext is not None and receiveContext is not None:
with receiveContext as writer:
with sendContext as reader... | Transfer (large) data from sender to receiver. |
383,961 | def of(fixture_classes: Iterable[type], context: Union[None, ] = None) -> Iterable[]:
classes = list(copy.copy(fixture_classes))
fixtures = []
while len(classes):
current = classes.pop()
subclasses = current.__subclasses__()
if len(subclasses):
classes.extend(su... | Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ``torment.TestContext`` to initialize Fixtures with
**Return Value(s)**
Instantiated ``torment.fixtures.Fixture`` objects for each... |
383,962 | def routing(routes, request):
path = request.path.strip()
args = {}
for name, route in routes.items():
if route[] == :
}
raise TornNotFoundError | Definition for route matching : helper |
383,963 | def _enable_l1_keepalives(self, command):
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = self.iourc_path
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True)... | Enables L1 keepalive messages if supported.
:param command: command line |
383,964 | def __parse_identities(self, json):
try:
for uidentity in json[].values():
uuid = self.__encode(uidentity[])
uid = UniqueIdentity(uuid=uuid)
if uidentity[]:
profile = uidentity[]
if type(profile[]) !=... | Parse identities using Sorting Hat format.
The Sorting Hat identities format is a JSON stream on which its
keys are the UUID of the unique identities. Each unique identity
object has a list of identities and enrollments.
When the unique identity does not have a UUID, it will be conside... |
383,965 | def retrieve(self, key):
column_file = os.path.join(self._hash_dir, % key)
cache_file = os.path.join(self._hash_dir, % key)
if os.path.exists(cache_file):
data = np.load(cache_file)
if os.path.exists(column_file):
with open(column_file, ) as js... | Retrieves a cached array if possible. |
383,966 | def load_image(name, n, m=None, gpu=None, square=None):
if m is None:
m = n
if gpu is None:
gpu = 0
if square is None:
square = 0
command = (.format(name,
n, m, gpu, square))
return j.eval(command) | Function to load images with certain size. |
383,967 | def tablestructure(tablename, dataman=True, column=True, subtable=False,
sort=False):
t = table(tablename, ack=False)
six.print_(t.showstructure(dataman, column, subtable, sort)) | Print the structure of a table.
It is the same as :func:`table.showstructure`, but without the need to open
the table first. |
383,968 | def get_all_preordered_namespace_hashes( self ):
cur = self.db.cursor()
namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock )
return namespace_hashes | Get all oustanding namespace preorder hashes that have not expired.
Used for testing |
383,969 | def feed_arthur():
logger.info("Collecting items from redis queue")
db_url =
conn = redis.StrictRedis.from_url(db_url)
logger.debug("Redis connection stablished with %s.", db_url)
pipe = conn.pipeline()
pipe.lrange(Q_STORAGE_ITEMS, 0, -1)
pipe.ltrim(Q_STORAGE_ITEMS, 1, 0)
... | Feed Ocean with backend data collected from arthur redis queue |
383,970 | def path(self):
if isinstance(self.dir, Directory):
return self.dir._path
elif isinstance(self.dir, ROOT.TDirectory):
return self.dir.GetPath()
elif isinstance(self.dir, _FolderView):
return self.dir.path()
else:
return str(self.di... | Get the path of the wrapped folder |
383,971 | def list(self, entity=None):
uri = "/%s" % self.uri_base
if entity:
uri = "%s?entityId=%s" % (uri, utils.get_id(entity))
resp, resp_body = self._list(uri, return_raw=True)
return resp_body | Returns a dictionary of data, optionally filtered for a given entity. |
383,972 | def start_server_background(port):
if sys.version_info[0] == 2:
lines = (
)
cell = lines.format(port=port)
else:
path = repr(os.path.dirname(os.path.realpath(__file__)))
lines = (
)
... | Start the newtab server as a background process. |
383,973 | def write(self, output_io):
for name, tax in self.taxonomy.items():
output_io.write("%s\t%s\n" % (name, .join(tax))) | Write a taxonomy to an open stream out in GG format. Code calling this
function must open and close the io object. |
383,974 | def set_triggered_by_event(self, value):
if value is None or not isinstance(value, bool):
raise TypeError("TriggeredByEvent must be set to a bool")
else:
self.__triggered_by_event = value | Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value. |
383,975 | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
self.mglo.bind(attribute, cls, buffer.mglo, fmt, offset, stride, divisor, normalize) | Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Arg... |
383,976 | def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
fields = [, , , , , ]
if not circleinds: circleinds = range(len(data[]))
datalen = len(data[])
inds = ci... | Make a light-weight loc figure |
383,977 | def _add_rg(unmapped_file, config, names):
picard = broad.runner_from_path("picard", config)
rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names)
return rg_fixed | Add the missing RG header. |
383,978 | def format_help(self):
if not self._cell_args:
return super(CommandParser, self).format_help()
else:
return orig_help | Override help doc to add cell args. |
383,979 | def HandleSimpleResponses(
self, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
return self._AcceptResponses(b, info_cb, timeout_ms=timeout_ms) | Accepts normal responses from the device.
Args:
timeout_ms: Timeout in milliseconds to wait for each response.
info_cb: Optional callback for text sent from the bootloader.
Returns:
OKAY packet's message. |
383,980 | def mkdir(self, mdir, parents=False):
assert mdir.startswith(), "%s: invalid manta path" % mdir
parts = mdir.split()
assert len(parts) > 3, "%s: cannot create top-level dirs" % mdir
if not parents:
self.put_directory(mdir)
else:
... | Make a directory.
Note that this will not error out if the directory already exists
(that is how the PutDirectory Manta API behaves).
@param mdir {str} A manta path, e.g. '/trent/stor/mydir'.
@param parents {bool} Optional. Default false. Like 'mkdir -p', this
will create p... |
383,981 | def visible(self, request):
s instance set
'
return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none() | Checks the both, check_visible and apply_visible, against the owned model and it's instance set |
383,982 | def DictProduct(dictionary):
keys, values = Unzip(iteritems(dictionary))
for product_values in itertools.product(*values):
yield dict(zip(keys, product_values)) | Computes a cartesian product of dict with iterable values.
This utility function, accepts a dictionary with iterable values, computes
cartesian products of these values and yields dictionaries of expanded values.
Examples:
>>> list(DictProduct({"a": [1, 2], "b": [3, 4]}))
[{"a": 1, "b": 3}, {"a": 1, "b"... |
383,983 | def from_table(table, fields=None):
if fields is None:
fields =
elif isinstance(fields, list):
fields = .join(fields)
return Query( % (fields, table._repr_sql_())) | Return a Query for the given Table object
Args:
table: the Table object to construct a Query out of
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a list of field names.
Returns:
A Quer... |
383,984 | def dictionary_merge(a, b):
for key, value in b.items():
if key in a and isinstance(a[key], dict) and isinstance(value, dict):
dictionary_merge(a[key], b[key])
continue
a[key] = b[key]
return a | merges dictionary b into a
Like dict.update, but recursive |
383,985 | def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(TweetableAdminMixin,
self).formfield_for_dbfield(db_field, **kwargs)
if Api and db_field.name == "status" and get_auth_settings():
def wrapper(render):
def wrapped(*args, **kwargs):
... | Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and then adding it to the
formssets attribute of the admin class fell ap... |
383,986 | def collect_conflicts_between(
context: ValidationContext,
conflicts: List[Conflict],
cached_fields_and_fragment_names: Dict,
compared_fragment_pairs: "PairSet",
parent_fields_are_mutually_exclusive: bool,
field_map1: NodeAndDefCollection,
field_map2: NodeAndDefCollection,
) -> None:
... | Collect all Conflicts between two collections of fields.
This is similar to, but different from the `collectConflictsWithin` function above.
This check assumes that `collectConflictsWithin` has already been called on each
provided collection of fields. This is true because this validator traverses each
... |
383,987 | def reconnect(self):
log.debug()
try:
self.ssl_skt.close()
except socket.error:
log.error()
log.debug()
self.authenticate() | Try to reconnect and re-authenticate with the server. |
383,988 | def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
if forbidden_item_ids is None:
forbidden_item_ids = set()
def _children(item_ids):
if item_ids is None:
items = Item.objects.filter(active=True).prefetch_related()
... | Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
... |
383,989 | def _write_nex(self, mdict, nlocus):
max_name_len = max([len(i) for i in mdict])
namestring = "{:<" + str(max_name_len+1) + "} {}\n"
matrix = ""
for i in mdict.items():
matrix += namestring.format(i[0], i[1])
minidir = os.path.realpath(os.... | function that takes a dictionary mapping names to sequences,
and a locus number, and writes it as a NEXUS file with a mrbayes
analysis block given a set of mcmc arguments. |
383,990 | def print_common_terms(common_terms):
if not common_terms:
print()
else:
for set_pair in common_terms:
set1, set2, terms = set_pair
print(.format(set1, set2))
for term in terms:
print(.format(term)) | Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms(). |
383,991 | def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
self._user = authenticate(username=username, password=password)
if self._user is None:
raise forms.ValidationError(
ugettext("Inval... | Authenticate the given username/email and password. If the fields
are valid, store the authenticated user for returning via save(). |
383,992 | def profile(self, profile):
self._staging_data = None
lang = profile.get(, {}).get(, )
profile_args = ArgBuilder(lang, self.profile_args(profile.get()))
self._profile = profile
self._profile[] = profile_args
s... | Set the current profile.
Args:
profile (dict): The profile data. |
383,993 | def draw_triangle(a, b, c, color, draw):
draw.polygon([a, b, c], fill=color) | Draws a triangle with the given vertices in the given color. |
383,994 | def clear_n_of_m(self):
if (self.get_n_of_m_metadata().is_read_only() or
self.get_n_of_m_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map[] = \
int(self._n_of_m_metadata[][0]) | stub |
383,995 | def genome_alignment_iterator(fn, reference_species, index_friendly=False,
verbose=False):
kw_args = {"reference_species": reference_species}
for e in maf.maf_iterator(fn, index_friendly=index_friendly,
yield_class=GenomeAlignmentBlock,
... | build an iterator for an MAF file of genome alignment blocks.
:param fn: filename or stream-like object to iterate over.
:param reference_species: which species in the alignment should be treated
as the reference?
:param index_friendly: if True, buffering is disa... |
383,996 | def get_structure_seqs(pdb_file, file_type):
my_structure = StructureIO(pdb_file)
model = my_structure.first_model
structure_seqs = {}
for chain in model:
chain_seq =
tracker = 0
for res in chain.get_residues():
... | Get a dictionary of a PDB file's sequences.
Special cases include:
- Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR
- HETATMs. Currently written as an "X", or unknown amino acid.
Args:
pdb_file: Path to PDB file
Retu... |
383,997 | def add_motifs(self, args):
self.lock.acquire()
if args is None or len(args) != 2 or len(args[1]) != 3:
try:
job = args[0]
logger.warn("job %s failed", job)
self.finished.append(job)
except Exception:
... | Add motifs to the result object. |
383,998 | def __get_jp(self, extractor_processor, sub_output=None):
if sub_output is None and extractor_processor.output_field is None:
raise ValueError(
"ExtractorProcessors input paths cannot be unioned across fields. Please specify either a sub_output or use a single scalar output... | Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata |
383,999 | def _find_penultimate_layer(model, layer_idx, penultimate_layer_idx):
if penultimate_layer_idx is None:
for idx, layer in utils.reverse_enumerate(model.layers[:layer_idx - 1]):
if isinstance(layer, Wrapper):
layer = layer.layer
if isinstance(layer, (_Conv, _Pooli... | Searches for the nearest penultimate `Conv` or `Pooling` layer.
Args:
model: The `keras.models.Model` instance.
layer_idx: The layer index within `model.layers`.
penultimate_layer_idx: The pre-layer to `layer_idx`. If set to None, the nearest penultimate
`Conv` or `Pooling` laye... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.