Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
350,500 | def _s3_resource(dallinger_region=False):
config = get_config()
if not config.ready:
config.load()
region = "us-east-1" if dallinger_region else config.get("aws_region")
return boto3.resource(
"s3",
region_name=region,
aws_access_key_id=config.get("aws_access_key_id... | A boto3 S3 resource using the AWS keys in the config. |
350,501 | def initialize_state(self):
if self.__scan_hardware_source:
self.__profile_changed_event_listener = self.__scan_hardware_source.profile_changed_event.listen(self.__update_profile_index)
self.__frame_parameters_changed_event_listener = self.__scan_hardware_source.frame_parameters... | Call this to initialize the state of the UI after everything has been connected. |
350,502 | def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql"):
registerplugins()
ident = URIRef(identifier)
graph = Graph(, identifier=ident)
graph.open(filepath, create=True)
for prefix, ns in (prefixes or GRAPH_BINDINGS).items():
if prefix == "":
pre... | Generate a graph and change the global graph to this one
:param filepath: A Uri for the graph
:param prefixes: A dictionary of prefixes and namespaces to bind to the graph
:param identifier: An identifier that will identify the Graph root |
350,503 | def _parse_parameter(tag, parser, parent):
name, modifiers, dtype, kind = _parse_common(tag)
if "default" in tag.attrib:
default = tag.attrib["default"]
else:
default = None
if "dimension" in tag.attrib:
dimension = tag.attrib["dimension"]
else:
dimension = None
... | Creates a ValueElement instance from the specified <parameter> XML tag. |
350,504 | def reflect(self, x0, y0, x, y):
rx = x0 - (x-x0)
ry = y0 - (y-y0)
return rx, ry | Reflects the point x, y through origin x0, y0. |
350,505 | def get(self, status_item):
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_level)
sparql =
value = self.conn.query(sparql=sparql.format(self.group, status_item))
if len(value) > 0 and \
cbool(value[0].get(,{}).ge... | queries the database and returns that status of the item.
args:
status_item: the name of the item to check |
350,506 | def httpauth_login_required(func):
def wrapper(request, *args, **kwargs):
user = None
auth_string = request.META.get(, None)
if auth_string:
(authmeth, auth) = auth_string.split(" ", 1)
auth = auth.strip().decode()
(username, password) = au... | Put this decorator before your view to check if the user is logged in
via httpauth and return a JSON 401 error if he/she is not. |
350,507 | def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | Returns list of field-defining SQL fragments. |
350,508 | def describe(value):
if isinstance(value, types.ModuleType):
return describe_file(value)
elif isinstance(value, messages.Field):
return describe_field(value)
elif isinstance(value, messages.Enum):
return describe_enum_value(value)
elif isinstance(value, type):
if iss... | Describe any value as a descriptor.
Helper function for describing any object with an appropriate descriptor
object.
Args:
value: Value to describe as a descriptor.
Returns:
Descriptor message class if object is describable as a descriptor, else
None. |
350,509 | def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):
url =
payload = {
: + topic_name,
: registration_ids,
}
response = self.requests_session.post(url, json=payload)
if response.status_code == 200:
return True... | Subscribes a list of registration ids to a topic
Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic
Returns:
True: if operation succeeded
Raises:
InvalidDataError: data sent to server was incorrectly formatted
... |
350,510 | def delete_zone(args):
if args.__dict__.get():
domain = args.domain
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.delete_zone(args.server, token, domain) | Delete zone.
Argument:
args: arguments object |
350,511 | def autodiff_ast(func, wrt, motion, mode, preserve_result, check_dims, verbose):
node = annotate.resolve_calls(func)
node = desugar.explicit_loop_indexes(node)
fence.validate(node, inspect.getsource(func))
node = anf_.anf(node)
if verbose >= 2:
print()
print(quoting.to_source(node))
if mode == :
... | Perform AD on a single function and return the AST.
Args:
See `grad`.
Returns:
node: The AST of a module containing the adjoint and primal function
definitions.
required: A list of non-built in functions that this function called, and
of which the primals and adjoints need to be made a... |
350,512 | def normalize(string, chars_to_remove=None, replacement=):
ret = string.translate(str.maketrans({
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}))
if isinstance(chars_to_remove, dict):
for chars, replace in chars_to_rem... | Remove accented characters and such.
The argument chars_to_remove is a dictionary that maps a string of chars to
a single character. Every occurrence of every character in the first string
will be replaced by that second character passed as value. If only one
mapping is desired, chars_to_remove may be ... |
350,513 | def unload():
global __tile_maps
global active_map
if TileMapManager.active_map != None:
world = Ragnarok.get_world()
for obj in TileMapManager.active_map.objects:
world.remove_obj(obj)
world.remove_obj(TileMapManager.active_map) | Unload the current map from the world. |
350,514 | def switch_client(self):
proc = self.cmd(, % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr) | Switch client to this session.
Raises
------
:exc:`exc.LibTmuxException` |
350,515 | def unpack_dosdate(self, offset):
try:
o = self._offset + offset
return dosdate(self._buf[o:o + 2], self._buf[o + 2:o + 4])
except struct.error:
raise OverrunBufferException(o, len(self._buf)) | Returns a datetime from the DOSDATE and DOSTIME starting at
the relative offset.
Arguments:
- `offset`: The relative offset from the start of the block.
Throws:
- `OverrunBufferException` |
350,516 | def handle_deletions(self):
deduplicated_objs = {}
for model in self.model_objs_registered_for_deletion:
key = .format(
ContentType.objects.get_for_model(model, for_concrete_model=False),
model.id
)
deduplicated_objs[key] = mo... | Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. Any receipts that are from previous rounds and no... |
350,517 | def capitalize_keys(suspect):
if not isinstance(suspect, dict):
raise TypeError()
converted = {}
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
if key[0].isupper():
continue
if in key:
new_key = .join... | :param suspect:
:return new dict with capitalized keys: |
350,518 | def varange(starts, count):
try:
return stack(arange(s, s + count) for s in starts)
except TypeError:
return arange(starts, starts + count) | Vectorized `arange()` taking a sequence of starts and a count of elements.
For example::
>>> varange(1, 5)
array([1, 2, 3, 4, 5])
>>> varange((1, 3), 5)
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7]]) |
350,519 | def rebuildDays( self ):
time = QTime(0, 0, 0)
hour = True
x = 6
y = 6 + 24
w = self.width() - 12 - 25
dh = 48
indent = 58
text_data = []
vlines = []
hlines ... | Rebuilds the interface as a week display. |
350,520 | def load(self, value):
if self.property_type is None:
return value
elif not isinstance(self.property_type, BaseType):
raise TypeError()
else:
native_value = self.property_type.to_native(value)
self.property_type.validate(native_value)
... | Load a value, converting it to the proper type if validation_type exists. |
350,521 | def formatdate(timeval=None):
if timeval is None:
timeval = time.time()
timeval = time.gmtime(timeval)
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
timeval[2],
("Jan", "Feb", "Mar", "Apr", "Ma... | Returns time format preferred for Internet standards.
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
According to RFC 1123, day and month names must always be in
English. If not for that, this code could use strftime(). It
can't because strftime() honors the locale and could generate
... |
350,522 | def run_analysis(self, argv):
args = self._parser.parse_args(argv)
obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
expCube=args.expcube,
srcMaps=args.cmap,
binnedExpMap=args.bexpm... | Run this analysis |
350,523 | def _filter_types(types_dict):
def exclude(k):
return k.path.startswith() or k.func_name ==
return {k: v for k, v in iteritems(types_dict) if not exclude(k)} | Filter type info before dumping it to the file. |
350,524 | def run_forge(args):
version = args.version
commit_id = args.commit_id
branch = args.branch
try:
print(Version(version, commit_id, branch))
except DockerTagNamingException, de:
print(de)
sys.exit(1) | Handle the forge subcommand
:param args: Parsed command line arguments
:return: None, output is written to console |
350,525 | def setup_platform(hass, config, add_entities, discovery_info=None):
if discovery_info is None:
return
switches = []
manager = hass.data[DOMAIN][]
if manager.outlets is not None and manager.outlets:
if len(manager.outlets) == 1:
count_string =
else:
... | Set up the VeSync switch platform. |
350,526 | def translit(src, table=UkrainianKMU, preserve_case=True):
u
src = text_type(src)
src_is_upper = src.isupper()
if hasattr(table, "DELETE_PATTERN"):
src = table.DELETE_PATTERN.sub(u"", src)
if hasattr(table, "PATTERN1"):
src = table.PATTERN1.sub(lambda x: table.SPECIAL_CASES[x.grou... | u""" Transliterates given unicode `src` text
to transliterated variant according to a given transliteration table.
Official ukrainian transliteration is used by default
:param src: string to transliterate
:type src: str
:param table: transliteration table
:type table: transliteration table obje... |
350,527 | def _strip_consts(graph_def, max_const_size=32):
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == :
tensor = n.attr[].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
... | Strip large constant values from graph_def.
This is mostly a utility function for graph(), and also originates here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb |
350,528 | def create_tab(self, location=None):
eb = self._get_or_create_editor_buffer(location)
self.tab_pages.insert(self.active_tab_index + 1, TabPage(Window(eb)))
self.active_tab_index += 1 | Create a new tab page. |
350,529 | def get_long_description():
with open("README.rst", "r") as f:
readme = f.read()
with open("CHANGELOG.rst", "r") as f:
changelog = f.read()
changelog = changelog.replace("\nUnreleased\n------------------", "")
return "\n".join([readme, changelog]) | Return this projects description. |
350,530 | def register_to_xmldoc(xmldoc, program, paramdict, **kwargs):
process = append_process(xmldoc, program = program, **kwargs)
append_process_params(xmldoc, process, process_params_from_dict(paramdict))
return process | Register the current process and params to an XML document.
program is the name of the program. paramdict is a dictionary of
name/value pairs that will be used to populate the process_params
table; see process_params_from_dict() for information on how these
name/value pairs are interpreted. Any additional keywor... |
350,531 | def find_source_table(expr):
def finder(expr):
if isinstance(expr, ir.TableExpr):
return lin.halt, expr
else:
return lin.proceed, None
first_tables = lin.traverse(finder, expr.op().flat_args())
options = list(toolz.unique(first_tables, key=methodcaller()))
... | Find the first table expression observed for each argument that the
expression depends on
Parameters
----------
expr : ir.Expr
Returns
-------
table_expr : ir.TableExpr
Examples
--------
>>> import ibis
>>> t = ibis.table([('a', 'double'), ('b', 'string')], name='t')
>... |
350,532 | def bind_permanent(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype):
hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime.PermanentLifeTimeManager) | shortcut for bind_type with PermanentLifeTimeManager on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object |
350,533 | def get(cache_dir=CACHE_DIR):
current_wall = os.path.join(cache_dir, "wal")
if os.path.isfile(current_wall):
return util.read_file(current_wall)[0]
return "None" | Get the current wallpaper. |
350,534 | def participants(self):
ret = []
for p in self.players:
try:
if p.isComputer: ret.append(p)
if not p.isObserver: ret.append(p)
except AttributeError: pass
return ret | agents + computers (i.e. all non-observers) |
350,535 | def isidentifier(s, dotted=False):
if dotted:
return all(isidentifier(a) for a in s.split())
if PY3:
return s.isidentifier()
else:
import re
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
return bool(_name_re.match(s)) | A function equivalent to the str.isidentifier method on Py3 |
350,536 | def checkKey(self, key=None):
url = Client.ENDPOINT.format()
if not key: key = self.apiKey
params = {
: key or self.apiKey
}
returned = get(url, params=params)
self.checkResponse(returned)
root = ET.fromstring(returned.text... | Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:raises: :class:`brickfront.errors.InvalidApiKey` |
350,537 | def reconnect_to_broker(self):
if self.client:
self.poller.unregister(self.client)
self.client.close()
self.client = self.ctx.socket(zmq.DEALER)
self.client.linger = 0
self.client.connect(self.broker)
self.poller.register(self.client, zmq... | Connect or reconnect to broker |
350,538 | def get_url_base_from_url_token(
self, url_api_token: str = "https://id.api.isogeo.com/oauth/token"
):
in_parsed = urlparse(url_api_token)
api_url_base = in_parsed._replace(
path="", netloc=in_parsed.netloc.replace("id.", "")
)
return api_url_base.geturl(... | Returns the Isogeo API root URL (which is not included into
credentials file) from the token URL (which is always included).
:param url_api_token str: url to Isogeo API ID token generator |
350,539 | def get_data(search_string, search_by=):
r_details = requests.get(,
headers={
:%search_string,
:
},
params = {
:,
:search_string
}).json()
r_wscore = requests.get(,
headers={... | Download data from talosintelligence.com for the given IP
Return tabbed data text |
350,540 | def _add_options_to_parser(self, opts_dict, parser):
store_bool = (, )
for opt, sct in opts_dict.items():
meta = self._conf[sct].def_[opt]
kwargs = copy.deepcopy(meta.cmd_kwargs)
action = kwargs.get()
if action is internal.Switch:
... | Add options to a parser. |
350,541 | def count(self):
self.fields_sort = fields_sort
return ret | return the count of the criteria |
350,542 | def by_water_area_in_sqmi(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.water_area_in_sqmi.name,
ascending=False,
... | Search zipcode information by water area / sq miles range. |
350,543 | def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs):
def decorator(f):
if not in cls.__dict__:
cls.url_for_endpoints = {None: {}}
cls.url_for_endpoints.setdefault(_app, {})
for keyword in paramattrs:
... | View decorator that registers the view as a :meth:`url_for` target. |
350,544 | def _overwrite(self, filename, func, force=False):
now = int(time.time() * 1000)
last_overwrite_time = self._last_overwrite_time.get(filename) or now
if (now - last_overwrite_time >= 1000) or force:
if os.path.exists(self._html_dir):
f.write(func())
self._last_overwrite_tim... | Overwrite a file with the specified contents.
Write times are tracked, too-frequent overwrites are skipped, for performance reasons.
:param filename: The path under the html dir to write to.
:param func: A no-arg function that returns the contents to write.
:param force: Whether to force a write now, ... |
350,545 | def get(filename, section, parameter):
filename = _quote(filename)
section = _quote(section)
parameter = _quote(parameter)
result = __salt__[](
.format(
filename, section, parameter
),
python_shell=False,
)
if result[] == 0:... | Get a value from an OpenStack configuration file.
filename
The full path to the configuration file
section
The section from which to search for the parameter
parameter
The parameter to return
CLI Example:
.. code-block:: bash
salt-call openstack_config.get /etc/... |
350,546 | def find_prev_keyword(sql):
if not sql.strip():
return None,
parsed = sqlparse.parse(sql)[0]
flattened = list(parsed.flatten())
logical_operators = (, , , )
for t in reversed(flattened):
if t.value == or (t.is_keyword and (
t.value.upper() not ... | Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped |
350,547 | def kilometers(meters=0, miles=0, feet=0, nautical=0):
ret = 0.
if meters:
ret += meters / 1000.
if feet:
ret += feet / ft(1.)
if nautical:
ret += nautical / nm(1.)
ret += miles * 1.609344
return ret | TODO docs. |
350,548 | def from_api_repr(cls, resource):
project = resource["projectId"]
dataset_id = resource["datasetId"]
return cls(project, dataset_id) | Factory: construct a dataset reference given its API representation
Args:
resource (Dict[str, str]):
Dataset reference resource representation returned from the API
Returns:
google.cloud.bigquery.dataset.DatasetReference:
Dataset reference parsed... |
350,549 | def validate_proxy_args(cls, *args):
supplied_proxies = Counter((not arg for arg in (*args,))).get(False)
if not supplied_proxies:
return
elif supplied_proxies > 1:
raise RaccoonException("Must specify only one of the following:\n"
... | No more than 1 of the following can be specified: tor_routing, proxy, proxy_list |
350,550 | def distributeParams(self,param_name,param_count,center,spread,dist_type):
if dist_type == :
param_dist = approxUniform(N=param_count,bot=center-spread,top=center+spread)
elif dist_type == :
tail_N = 3
param_dist = approxLog... | Distributes heterogeneous values of one parameter to the AgentTypes in self.agents.
Parameters
----------
param_name : string
Name of the parameter to be assigned.
param_count : int
Number of different values the parameter will take on.
center : float
... |
350,551 | def tasks(self):
if self._tasks is None:
self._tasks = self.parent.tasks.tasks(
tasklist="@default", showCompleted="true", showHidden="true",
completedMin=self.since, completedMax=self.until)
log.info(u"NB TASKS {0}".format(len(self._tasks)))
... | All completed tasks within specified time range |
350,552 | def get_xml(self, pretty=True):
return etree.tostring(self.root, encoding="utf-8", pretty_print=pretty) | Get the XML as an UTF-8 string
:returns: bytes encoded as UTF-8 |
350,553 | def sign_request(private_key, method, endpoint, body_bytes, headers):
head_bytes = _generate_request_head_bytes(method, endpoint, headers)
bytes_to_sign = head_bytes + body_bytes
signer = PKCS1_v1_5.new(private_key)
digest = SHA256.new()
digest.update(bytes_to_sign)
sign = signer.sign(dige... | :type private_key: RSA.RsaKey
:type method: str
:type endpoint: str
:type body_bytes: bytes
:type headers: dict[str, str]
:rtype: str |
350,554 | def kdf_iterations(self):
encryption_algo = self[].native
if encryption_algo == :
return self[][][][].native
if encryption_algo.find() == -1:
if encryption_algo.find() != -1:
return self[][].native
raise ValueError(unwrap(
... | Returns the number of iterations that should be run via the KDF.
:return:
An integer |
350,555 | def get_resources(self, names=None, stores=None, workspaces=None):
stores = self.get_stores(
names = stores,
workspaces = workspaces
)
resources = []
for s in stores:
try:
resources.extend(s.get_resources())
excep... | Resources include feature stores, coverage stores and WMS stores, however does not include layer groups.
names, stores and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering.
Will always return an array. |
350,556 | def update(self, params, values):
params = listify(params)
values = listify(values)
for i, p in enumerate(params):
if (p[-2:] == ) and (values[i] < 0):
values[i] = 0.0
super(PlatonicSpheresCollection, self).update(params, values) | Calls an update, but clips radii to be > 0 |
350,557 | def close(self) -> None:
if self._closed:
return
self._closed = True
if self._instance_cache is not None:
cached_val = self._instance_cache.pop(self.io_loop, None)
if cached_val is not N... | Destroys this HTTP client, freeing any file descriptors used.
This method is **not needed in normal use** due to the way
that `AsyncHTTPClient` objects are transparently reused.
``close()`` is generally only necessary when either the
`.IOLoop` is also being closed, or the ``force_instan... |
350,558 | def _step00(self, in_row, tmp_row, out_row):
for key, value in in_row.items():
in_row[key] = WhitespaceCleaner.clean(value)
return None, None | Prunes whitespace for all fields in the input row.
:param dict in_row: The input row.
:param dict tmp_row: Not used.
:param dict out_row: Not used. |
350,559 | def transcript_sort_key(transcript):
return (
-len(transcript.protein_sequence),
-len(transcript.sequence),
transcript.name
) | Key function used to sort transcripts. Taking the negative of
protein sequence length and nucleotide sequence length so that
the transcripts with longest sequences come first in the list. This couldn't
be accomplished with `reverse=True` since we're also sorting by
transcript name (which places TP53-001... |
350,560 | def share_database(self, username, roles=None):
if roles is None:
roles = []
valid_roles = [
,
,
,
,
,
,
,
]
doc = self.security_document()
data = doc.get(, {})
... | Shares the current remote database with the username provided.
You can grant varying degrees of access rights,
default is to share read-only, but additional
roles can be added by providing the specific roles as a
``list`` argument. If the user already has this database shared with
... |
350,561 | def available_resource_group_delegations(self):
api_version = self._get_api_version()
if api_version == :
from .v2018_08_01.operations import AvailableResourceGroupDelegationsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not avail... | Instance depends on the API version:
* 2018-08-01: :class:`AvailableResourceGroupDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableResourceGroupDelegationsOperations>` |
350,562 | def pass_defaults(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
merged = {}
merged.update(self.defaults)
merged.update(kwargs)
return func(self, *args, **merged)
return wrapper | Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to |
350,563 | def set_widgets(self):
self.progress_bar.setValue(0)
self.results_webview.setHtml()
self.pbnReportWeb.hide()
self.pbnReportPDF.hide()
self.pbnReportComposer.hide()
self.lblAnalysisStatus.setText(tr()) | Set widgets on the Progress tab. |
350,564 | def dump(o, f):
if not f.write:
raise TypeError("You can only dump an object to a file descriptor")
d = dumps(o)
f.write(d)
return d | Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
Returns:
String containing the toml corresponding to dictionary
Raises:
TypeError: When anything other than file descriptor is passed |
350,565 | def set_option(self, key, value):
self._options.update(self._option_schema({key: value}))
self.clear_cache() | Set the option `key` (string) to `value`.
Instance method, affects only current instance.
This will clear the cache. |
350,566 | def ipython_only(option):
if __IPYTHON__:
return option
argname = extract_option_object(option).name
def d(f):
@wraps(f)
def _(*args, **kwargs):
kwargs[argname] = None
return f(*args, **kwargs)
return _
return d | Mark that an option should only be exposed in IPython.
Parameters
----------
option : decorator
A click.option decorator.
Returns
-------
ipython_only_dec : decorator
A decorator that correctly applies the argument even when not
using IPython mode. |
350,567 | def uses_placeholder_y(ds):
if isinstance(ds, torch.utils.data.Subset):
return uses_placeholder_y(ds.dataset)
return isinstance(ds, Dataset) and hasattr(ds, "y") and ds.y is None | If ``ds`` is a ``skorch.dataset.Dataset`` or a
``skorch.dataset.Dataset`` nested inside a
``torch.utils.data.Subset`` and uses
y as a placeholder, return ``True``. |
350,568 | def set_uuid(obj, uuid=None):
from uuid import uuid4, UUID
if uuid is None:
uuid = uuid4()
elif isinstance(uuid, bytes):
if len(uuid) == 16:
uuid = UUID(bytes=uuid)
else:
uuid = UUID(hex=uuid)
if "uuid" in obj.attrs:
del obj.attrs["uuid"]
... | Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype |
350,569 | def issue_command(self, command, args=None, dry_run=False, comment=None):
req = rest_pb2.IssueCommandRequest()
req.sequenceNumber = SequenceGenerator.next()
req.origin = socket.gethostname()
req.dryRun = dry_run
if comment:
req.comment = comment
if ar... | Issue the given command
:param str command: Either a fully-qualified XTCE name or an alias in the
format ``NAMESPACE/NAME``.
:param dict args: named arguments (if the command requires these)
:param bool dry_run: If ``True`` the command is not actually issued. This
... |
350,570 | def sitecol(self):
if in vars(self):
return self.__dict__[]
if self.filename is None or not os.path.exists(self.filename):
return
with hdf5.File(self.filename, ) as h5:
self.__dict__[] = sc = h5.get()
return sc | Read the site collection from .filename and cache it |
350,571 | def _fmt_serialization_call(self, data_type, input_value, serialize, depth=0):
data_type, _ = unwrap_nullable(data_type)
serializer_func = if serialize else
serializer_args = []
if is_primitive_type(data_type):
return input_value
if is_list_type(data_type... | Returns the appropriate serialization / deserialization method
call for the given data type. |
350,572 | def remove_empties(variable):
import h5py
for key, val in variable.attrs.items():
if isinstance(val, h5py._hl.base.Empty):
variable.attrs.pop(key)
return variable | Remove empty objects from the *variable*'s attrs. |
350,573 | def fill_phenotype_label(self,inplace=False):
def _get_phenotype(d):
vals = [k for k,v in d.items() if v == 1]
return np.nan if len(vals) == 0 else vals[0]
if inplace:
if self.shape[0] == 0: return self
self[] = self.apply(lambda x: _get_phenotyp... | Set the phenotype_label column according to our rules for mutual exclusion |
350,574 | def _add_slice(seq, slc):
if seq and seq[-1].stop == slc.start:
seq[-1] = slice(seq[-1].start, slc.stop)
else:
seq.append(slc) | Our textwrap routine deals in slices. This function will concat
contiguous slices as an optimization so lookup performance is faster.
It expects a sequence (probably a list) to add slice to or will extend
the last slice of the sequence if it ends where the new slice begins. |
350,575 | def prep_value(self, value):
if value in MULTI_EMAIL_FIELD_EMPTY_VALUES:
return ""
elif isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return "\n".join(value)
raise ValidationError() | Prepare value before effectively render widget |
350,576 | def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
warnings.warn(
,
... | Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names... |
350,577 | def check(self, value):
if self.lower:
if np.any(value < self.lower):
return False
if self.upper:
if np.any(value > self.upper):
return False
return True | Check a value falls within a bound.
Parameters
----------
value : scalar or ndarray
value to test
Returns
-------
bool:
If all values fall within bounds
Example
-------
>>> bnd = Bound(1, 2)
>>> bnd.check(1.5)
... |
350,578 | def flatten_list_abundance(node: ListAbundance) -> ListAbundance:
return node.__class__(list(chain.from_iterable(
(
flatten_list_abundance(member).members
if isinstance(member, ListAbundance) else
[member]
)
for member in node.members
))) | Flattens the complex or composite abundance. |
350,579 | def _construct_update(self, outgoing_route):
update = None
path = outgoing_route.path
localpref_attr = BGPPathAttributeLocalPref(
self._common_conf.local_pref)
key = const.ATTR_MAPS_LABEL_DEFAULT
if i... | Construct update message with Outgoing-routes path attribute
appropriately cloned/copied/updated. |
350,580 | def default_images_directory(type):
server_config = Config.instance().get_section_config("Server")
img_dir = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
if type == "qemu":
return os.path.join(img_dir, "QEMU")
elif type == "iou":
return os.path.join(img_dir,... | :returns: Return the default directory for a node type |
350,581 | def inrypl(vertex, direct, plane):
assert (isinstance(plane, stypes.Plane))
vertex = stypes.toDoubleVector(vertex)
direct = stypes.toDoubleVector(direct)
nxpts = ctypes.c_int()
xpt = stypes.emptyDoubleVector(3)
libspice.inrypl_c(vertex, direct, ctypes.byref(plane), ctypes.byref(nxpts),
... | Find the intersection of a ray and a plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html
:param vertex: Vertex vector of ray.
:type vertex: 3-Element Array of floats
:param direct: Direction vector of ray.
:type direct: 3-Element Array of floats
:param plane: A SPICE p... |
350,582 | def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop)
if self.isheavy():
logger.warning("Selection size of %.2f GB, exceeding our size limit %.2f GB. Instance c... | Read data. |
350,583 | def can_cut(self):
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position())) | Returns whether text can be cut to the clipboard. |
350,584 | def get_unread_forums_from_list(self, forums, user):
unread_forums = []
visibility_contents = ForumVisibilityContentTree.from_forums(forums)
forum_ids_to_visibility_nodes = visibility_contents.as_dict
tracks = super().get_queryset().select_related().filter(
user=use... | Filter a list of forums and return only those which are unread.
Given a list of forums find and returns the list of forums that are unread for the passed
user. If a forum is unread all of its ancestors are also unread and will be included in the
final list. |
350,585 | def sortByColumn(self, index):
if self.sort_old == [None]:
self.header_class.setSortIndicatorShown(True)
sort_order = self.header_class.sortIndicatorOrder()
self.sig_sort_by_column.emit()
if not self.model().sort(index, sort_order):
if len(self.sor... | Implement a column sort. |
350,586 | def _is_actual_elif(self, node):
if isinstance(node.parent, astroid.If):
orelse = node.parent.orelse
if orelse and orelse == [node]:
if (node.lineno, node.col_offset) in self._elifs:
return True
return False | Check if the given node is an actual elif
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
Unfortunately we need to know the exact type in certain
cases. |
350,587 | def interop_parse(self):
try:
run_metrics = py_interop_run_metrics.run_metrics()
valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, 0)
py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load)
run_metrics.read(self.p... | Use interop to parse the files in the InterOp folder to extract the number of reads mapping to PhiX as well as
the error rate |
350,588 | def n_hot(ids, c):
res = np.zeros((c,), dtype=np.float32)
res[ids] = 1
return res | one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids |
350,589 | def _resolve_host(fqdn, localname):
if fqdn:
return socket.getfqdn()
elif localname is not None:
return localname
return socket.gethostname() | Resolve the ``host`` GELF field
:param fqdn: Boolean indicating whether to use :meth:`socket.getfqdn`
to obtain the ``host`` GELF field.
:type fqdn: bool
:param localname: Use specified hostname as the ``host`` GELF field.
:type localname: str or None
:return: Stri... |
350,590 | def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False,
usev=False):
return self.find_closest_trackpoint(R,vR,vT,z,vz,phi,
interp=interp,xy=xy,
usev=usev) | For backward compatibility |
350,591 | def _create_jspath(self) -> Path:
src = self._build_dir /
os.makedirs(src, exist_ok=True)
return src | Create the source directory for the build. |
350,592 | def logging_file_install(path):
if path is None:
path = configuration_get_default_folder() / LOGGING_DEFAULTNAME
if not path.parent.exists():
log.error()
log.error()
return
formatter = logging.Formatter(LOGGING_FORMAT)
logger = logging.getLogger()
logger.remov... | Install logger that will write to file. If this function has already installed a handler, replace it.
:param path: path to the log file, Use None for default file location. |
350,593 | def units(comp_sum, uncomp_sum):
compressed = round((sum(map(float, comp_sum)) / 1024), 2)
uncompressed = round((sum(map(float, uncomp_sum)) / 1024), 2)
comp_unit = uncomp_unit = "Mb"
if compressed > 1024:
compressed = round((compressed / 1024), 2)
comp_unit = "Gb"
if uncompress... | Calculate package size |
350,594 | def add(self, s, c, track=False):
return self._add(s, self.convert_list(c), track=track) | This function adds constraints to the backend solver.
:param c: A sequence of ASTs
:param s: A backend solver object
:param bool track: True to enable constraint tracking, which is used in unsat_core() |
350,595 | def _get_default_router(self, routers, router_name=None):
if router_name is None:
for router in routers:
if router[] is not None:
return router[]
else:
for router in routers:
if router[] == router_name:
... | Returns the default router for ordering a dedicated host. |
350,596 | def get_d_moments(model,x):
input_dim = model.input_dim
x = reshape(x,input_dim)
_, v = model.predict(x)
dmdx, dvdx = model.predictive_gradients(x)
dmdx = dmdx[:,:,0]
dsdx = dvdx / (2*np.sqrt(v))
return (dmdx, dsdx) | Gradients with respect to x of the moments (mean and sdev.) of the GP
:param model: GPy model.
:param x: location where the gradients are evaluated. |
350,597 | def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any:
if isinstance(result, dict):
if result.get() == :
raise ActionFailed(retcode=result.get())
return result.get() | Retrieve 'data' field from the API result object.
:param result: API result that received from HTTP API
:return: the 'data' field in result object
:raise ActionFailed: the 'status' field is 'failed' |
350,598 | def is_installed(self, shutit_module_obj):
shutit_global.shutit_global_object.yield_to_draw()
if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed:
return True
if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modu... | Returns true if this module is installed.
Uses cache where possible. |
350,599 | def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False):
t exists.
:param bool md5_check:
.. seealso:: CopyFile
:raises DirectoryNotFoundError:
If target_dir does not exist, and create_target_dir is False
.. seealso:: CopyFile for documentation on accepted prot... | Copy files from the given source to the target.
:param unicode source_dir:
A filename, URL or a file mask.
Ex.
x:\coilib50
x:\coilib50\*
http://server/directory/file
ftp://server/directory/file
:param unicode target_dir:
A directory or a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.