Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,000 | def remove_constraint(self,name):
constraints = self.constraints
hidden_constraints = self.hidden_constraints
my_distribution_skip = self.distribution_skip
my_selectfrac_skip = self.selectfrac_skip
if name in constraints:
hidden_constraints[name] = constrain... | Remove a constraint (make it "hidden")
:param name:
Name of constraint. |
337,001 | def process_metadata(meta):
mvgds = []
metadata = meta[0]
for mvgd in meta:
if isinstance(mvgd[], list):
mvgds.extend(mvgd[])
else:
mvgds.append(mvgd[])
metadata[] = mvgds
return metadata | Merge metadata of run on multiple grid districts
Parameters
----------
meta: list of dict
Metadata of run of each MV grid district
Returns
-------
dict
Single metadata dict including merge metadata |
337,002 | def get_commit_url(repo_url):
if "github.com" in repo_url:
return repo_url[:-4] if repo_url.endswith(".git") else repo_url
if "git.openstack.org" in repo_url:
uri = .join(repo_url.split()[-2:])
return "https://github.com/{0}".format(uri)
return repo_url | Determine URL to view commits for repo. |
337,003 | def get_active_threads_involving_all_participants(self, *participant_ids):
query = Thread.objects.\
exclude(participation__date_left__lte=now()).\
annotate(count_participants=Count()).\
filter(count_participants=len(participant_ids))
for participant_id in p... | Gets the threads where the specified participants are active and no one has left. |
337,004 | def Froude(V, L, g=g, squared=False):
rs Chemical Engineers
Fr = V/(L*g)**0.5
if squared:
Fr *= Fr
return Fr | r'''Calculates Froude number `Fr` for velocity `V` and geometric length
`L`. If desired, gravity can be specified as well. Normally the function
returns the result of the equation below; Froude number is also often
said to be defined as the square of the equation below.
.. math::
Fr = \frac{V}{... |
337,005 | def get_all_draft_pages_from_space(self, space, start=0, limit=500, status=):
return self.get_all_pages_from_space(space, start, limit, status) | Get list of draft pages from space
Use case is cleanup old drafts from Confluence
:param space:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
... |
337,006 | def init_jvm(java_home=None,
jvm_dll=None,
jvm_maxmem=None,
jvm_classpath=None,
jvm_properties=None,
jvm_options=None,
config_file=None,
config=None):
if not config:
config = _get_python_api_config(config_file=co... | Creates a configured Java virtual machine which will be used by jpy.
:param java_home: The Java JRE or JDK home directory used to search JVM shared library, if 'jvm_dll' is omitted.
:param jvm_dll: The JVM shared library file. My be inferred from 'java_home'.
:param jvm_maxmem: The JVM maximum heap space, ... |
337,007 | def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True, env=os.environ):
logging.info("Running %s", command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines, env=env)
if print_output:
output_array = ... | Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, retu... |
337,008 | def UNIQUAC(xs, rs, qs, taus):
r
cmps = range(len(xs))
rsxs = sum([rs[i]*xs[i] for i in cmps])
phis = [rs[i]*xs[i]/rsxs for i in cmps]
qsxs = sum([qs[i]*xs[i] for i in cmps])
vs = [qs[i]*xs[i]/qsxs for i in cmps]
Ss = [sum([vs[j]*taus[j][i] for j in cmps]) for i in cmps]
loggammacs = [... | r'''Calculates the activity coefficients of each species in a mixture
using the Universal quasi-chemical (UNIQUAC) equation, given their mole
fractions, `rs`, `qs`, and dimensionless interaction parameters. The
interaction parameters are normally correlated with temperature, and need
to be calculated se... |
337,009 | def set_stream_class_lists_url(self, session_id):
url = self.api_url + + self.api_key + + session_id +
return url | this method returns the url to set the stream class list |
337,010 | def get(self, query_name):
url = "{0}/{1}".format(self.saved_query_url, query_name)
response = self._get_json(HTTPMethods.GET, url, self._get_master_key())
return response | Gets a single saved query for a project from the Keen IO API given a
query name.
Master key must be set. |
337,011 | def _tupleload(l: Loader, value, type_) -> Tuple:
if HAS_TUPLEARGS:
args = type_.__args__
else:
args = type_.__tuple_params__
if len(args) == 2 and args[1] == ...:
return tuple(l.load(i, args[0]) for i in value)
else:
if l.failonextra and len(value) > len(args):
... | This loads into something like Tuple[int,str] |
337,012 | def _get_wds(self, indices):
wds = [self.wd for _ in indices]
for i, index in enumerate(indices):
if index in self.param_dict:
wds[i] *= self.param_dict[index].wd_mult
elif index in self.wd_mult:
wds[i] *= self.wd_mult[index]
e... | Gets weight decays for indices.
Returns 0 for non-weights if the name of weights are provided for `__init__`.
Parameters
----------
indices : list of int
Indices of weights.
Returns
-------
wds : list of float
Weight decays for those indi... |
337,013 | def _abbreviate(text, threshold):
if text is not None and len(text) > threshold:
text = text[:threshold] + "..."
return text | Abbreviate the given text to threshold chars and append an ellipsis if its
length exceeds threshold; used for logging;
NOTE: the resulting text could be longer than threshold due to the ellipsis |
337,014 | def lyr_proj(lyr, t_srs, preserve_fields=True):
s_srs = lyr.GetSpatialRef()
cT = osr.CoordinateTransformation(s_srs, t_srs)
drv = ogr.GetDriverByName()
out_ds = drv.CreateDataSource()
outlyr = out_ds.CreateLayer(, srs=t_srs, geom_type=lyr.GetG... | Reproject an OGR layer |
337,015 | def _set_extcommunity(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=extcommunity.extcommunity, is_container=, presence=False, yang_name="extcommunity", rest_name="extcommunity", parent=self, path_helper=self._path_helper, extmethods=self._extmethods... | Setter method for extcommunity, mapped from YANG variable /routing_system/route_map/content/set/extcommunity (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_extcommunity is considered as a private
method. Backends looking to populate this variable should
do s... |
337,016 | def GASpecificConfig(r, info):
assert isinstance(info, DecoderSpecificInfo)
r.skip(1)
dependsOnCoreCoder = r.bits(1)
if dependsOnCoreCoder:
r.skip(14)
extensionFlag = r.bits(1)
if not info.channelConfiguration:
pce = ProgramConfigElement(r)
info.pce_channels = pc... | Reads GASpecificConfig which is needed to get the data after that
(there is no length defined to skip it) and to read program_config_element
which can contain channel counts.
May raise BitReaderError on error or
NotImplementedError if some reserved data was set. |
337,017 | def func_takes_last_result(waiter):
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return in waiter_spec.args | Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning. |
337,018 | def currentRepoTreeItemChanged(self):
currentItem, currentIndex = self.getCurrentItem()
hasCurrent = currentIndex.isValid()
assert hasCurrent == (currentItem is not None), \
"If current idex is valid, currentIndex may not be None"
if hasCurrent:
... | Called to update the GUI when a repo tree item has changed or a new one was selected. |
337,019 | def dev_from_pcapname(self, pcap_name):
try:
return next(iface for iface in six.itervalues(self)
if iface.pcap_name == pcap_name)
except (StopIteration, RuntimeError):
raise ValueError("Unknown pypcap network interface %r" % pcap_name) | Return Windows device name for given pcap device name. |
337,020 | def _process_response(self):
response = self.conn.getresponse()
if response.status == 200 or response.status == 201:
data = response.read()
else:
data = {
"error": {
"code": response.status,
"reason": respo... | Return a JSON result after an HTTP Request.
Process the response of an HTTP Request and make it a JSON error if
it failed. Otherwise return the response's content. |
337,021 | def delete_plat_operator(operator, auth, url):
oper_id = None
plat_oper_list = get_plat_operator(auth, url)
for i in plat_oper_list:
if operator == i[]:
oper_id = i[]
else:
oper_id = None
if oper_id is None:
return 409
f_url = url + "/imc... | Function to set the password of an existing operator
:param operator: str Name of the operator account
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: int of 204 if suc... |
337,022 | def pack_into(fmt, buf, offset, *args, **kwargs):
return CompiledFormat(fmt).pack_into(buf,
offset,
*args,
**kwargs) | Pack given values v1, v2, ... into given bytearray `buf`, starting
at given bit offset `offset`. Pack according to given format
string `fmt`. Give `fill_padding` as ``False`` to leave padding
bits in `buf` unmodified. |
337,023 | def validate_password(entry, username, check_function, password=None, retries=1, save_on_success=True, prompt=None, **check_args):
if password is None:
password = get_password(entry, username, prompt)
for _ in xrange(retries + 1):
if check_function(username, password, **check_args):
... | Validate a password with a check function & retry if the password is incorrect.
Useful for after a user has changed their password in LDAP, but their local keychain entry is then out of sync.
:param str entry: The keychain entry to fetch a password from.
:param str username: The username to authenti... |
337,024 | def add_intf_router(self, rout_id, tenant_id, subnet_lst):
try:
for subnet_id in subnet_lst:
body = {: subnet_id}
intf = self.neutronclient.add_interface_router(rout_id,
body=body)
... | Add the interfaces to a router. |
337,025 | def from_val(val_schema):
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
if len(definition) == 1:
... | Serialize a val schema to teleport. |
337,026 | def _validate(self, inst: "InstanceNode", scope: ValidationScope,
ctype: ContentType) -> None:
if isinstance(inst, ArrayEntry):
super()._validate(inst, scope, ctype)
else:
if scope.value & ValidationScope.semantics.value:
self._check_lis... | Extend the superclass method. |
337,027 | def execute(self, method, args, kwargs):
if args is None:
args = []
if kwargs is None:
kwargs = {}
try:
self._result = method(*args, **kwargs)
except Exception as ex:
self._exception = ex
raise
... | Execute the given method and stores its result.
The result is considered "done" even if the method raises an exception
:param method: The method to execute
:param args: Method positional arguments
:param kwargs: Method keyword arguments
:raise Exception: The exception raised by ... |
337,028 | def doExperiment(locationModuleWidth,
bumpType,
cellCoordinateOffsets,
numObjects,
featuresPerObject,
objectWidth,
numFeatures,
featureDistribution,
useTrace,
useRawTr... | Learn a set of objects. Then try to recognize each object. Output an
interactive visualization.
@param locationModuleWidth (int)
The cell dimensions of each module
@param cellCoordinateOffsets (sequence)
The "cellCoordinateOffsets" parameter for each module |
337,029 | def save_model(model, filename):
with open(filename, ) as f:
f.write(serialize_model(model)) | Save the model into a file.
:param model: HTK model to be saved
:param filename: File where to save the model |
337,030 | def get_wiki_page(self, subreddit, page):
return objects.WikiPage(self, six.text_type(subreddit), page.lower()) | Return a WikiPage object for the subreddit and page provided. |
337,031 | def _dict_to_proto(py_dict, proto):
dict_json_str = json.dumps(py_dict)
return json_format.Parse(dict_json_str, proto) | Converts a python dictionary to the proto supplied
:param py_dict: The dictionary to convert
:type py_dict: dict
:param proto: The proto object to merge with dictionary
:type proto: protobuf
:return: A parsed python dictionary in provided proto format
:raises:
... |
337,032 | def output_difference(self, example, got, optionflags):
want = example.want
if not (optionflags & DONT_ACCEPT_BLANKLINE):
got = re.sub(, BLANKLINE_MARKER, got)
if self._do_a_fancy_diff(want, got, optionflags):
want_lines =... | Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`. |
337,033 | def showcutoffs(self, redblue = False):
highmask = self.numpyarray > self.z2
lowmask = self.numpyarray < self.z1
if redblue == False :
if self.negative :
self.drawmask(highmask, colour = 255)
self.drawmask(lowmask, colour = 0)
... | We use drawmask to visualize pixels above and below the z cutoffs.
By default this is done in black (above) and white (below) (and adapts to negative images).
But if you choose redblue = True, I use red for above z2 and blue for below z1. |
337,034 | def is_named(self, filename):
self.is_file()
if not isinstance(filename, str_types):
raise TypeError()
val_filename = os.path.basename(os.path.abspath(self.val))
if val_filename != filename:
self._err( % (val_filename, filename))
return self | Asserts that val is an existing path to a file and that file is named filename. |
337,035 | def set_reboot_required_witnessed():
*
errcode = -1
dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH)
if not os.path.exists(dir_path):
try:
os.makedirs(dir_path)
except OSError as ex:
raise SaltInvocationError(
.format(dir... | This function is used to remember that an event indicating that a reboot is
required was witnessed. This function writes to a temporary filesystem so
the event gets cleared upon reboot.
Returns:
bool: ``True`` if successful, otherwise ``False``
.. code-block:: bash
salt '*' system.set... |
337,036 | def set_min_string_length(self, length=None):
if self.get_min_string_length_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_cardinal(
length,
self.get_min_string_length_metadata()):
raise InvalidArgume... | stub |
337,037 | def find_projects(self, file_identifier=".project"):
projects = []
for d in self.subdirs():
project_file = os.path.join(self.directory, d, file_identifier)
if os.path.isfile(project_file):
projects.append(d)
return projects | Search all directory recursively for subdirs
with `file_identifier' in it.
:type file_identifier: str
:param file_identifier: File identier, .project by default.
:rtype: list
:return: The list of subdirs with a `file_identifier' in it. |
337,038 | def add_permission(content_type, permission):
codename = "%s_%s" % (content_type.model, permission)
if not Permission.objects.filter(content_type=content_type, codename=codename):
Permission.objects.create(content_type=content_type,
codename=codena... | Adds the passed in permission to that content type. Note that the permission passed
in should be a single word, or verb. The proper 'codename' will be generated from that. |
337,039 | def docx_process_simple_text(text: str, width: int) -> str:
if width:
return .join(textwrap.wrap(text, width=width))
else:
return text | Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text |
337,040 | def startAll(self):
self.logger.info("Starting all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Starting {0}".format(thr.name))
thr.start()
self.logger.info("Started all threads") | Start all registered Threads. |
337,041 | def ReadMessageHandlerRequests(self):
res = []
leases = self.message_handler_leases
for requests in itervalues(self.message_handler_requests):
for r in itervalues(requests):
res.append(r.Copy())
existing_lease = leases.get(r.handler_name, {}).get(r.request_id, None)
res[-1... | Reads all message handler requests from the database. |
337,042 | def play_bootstrap_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
)
if interval and interval > 0:
if interval < 1:
interval = 1
... | Plays a Bootstrap tour on the current website. |
337,043 | def _get_records(self):
results = []
r = self.get_distinfo_resource()
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as record_reader:
for row in record_reader:
... | Get the list of installed files for the distribution
:return: A list of tuples of path, hash and size. Note that hash and
size might be ``None`` for some entries. The path is exactly
as stored in the file (which is as in PEP 376). |
337,044 | def save_animation(self, filename, datasets=None, fps=10, fill_value=None,
batch_size=1, ignore_missing=False, client=True, **kwargs):
if imageio is None:
raise ImportError("Missing required library")
scene_gen = self._scene_gen
first_scene = self.fi... | Helper method for saving to movie (MP4) or GIF formats.
Supported formats are dependent on the `imageio` library and are
determined by filename extension by default.
.. note::
Starting with ``imageio`` 2.5.0, the use of FFMPEG depends on
a separate ``imageio-ffmpeg`` p... |
337,045 | def get_stat(self, obj_name, stat_name):
return self.statistics[obj_name][self.captions.index(stat_name)] | :param obj_name: requested object name.
:param stat_name: requested statistics name.
:return: str, the value of the requested statics for the requested object. |
337,046 | def thread_helper(form_tag=True, edit_mode=False, for_moderator=False):
helper = FormHelper()
helper.form_action =
helper.attrs = {: }
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
,
css_class=
),
),
]
... | Thread's form layout helper |
337,047 | def add_metric_group_definition(self, definition):
assert isinstance(definition, FakedMetricGroupDefinition)
group_name = definition.name
if group_name in self._metric_group_defs:
raise ValueError("A metric group definition with this name "
"alre... | Add a faked metric group definition.
The definition will be used:
* For later addition of faked metrics responses.
* For returning the metric-group-info objects in the response of the
Create Metrics Context operations.
For defined metric groups, see chapter "Metric groups" i... |
337,048 | def _remove_redundant_overlapping_blocks(self):
sorted_nodes = sorted(self.graph.nodes(), key=lambda n: n.addr if n is not None else 0)
all_plt_stub_addrs = set(itertools.chain.from_iterable(obj.reverse_plt.keys() for obj in self.project.loader.all_objects if isinstance(obj, cle.MetaELF)))
... | On some architectures there are sometimes garbage bytes (usually nops) between functions in order to properly
align the succeeding function. CFGFast does a linear sweeping which might create duplicated blocks for
function epilogues where one block starts before the garbage bytes and the other starts aft... |
337,049 | def axes_style(style=, rc=None):
if rc is None:
rc = {}
rc_default = {}
for name, val in rc_default.items():
rc.setdefault(name, val)
return sns.axes_style(style=style, rc=rc) | Create pyfolio default axes style context.
Under the hood, calls and returns seaborn.axes_style() with
some custom settings. Usually you would use in a with-context.
Parameters
----------
style : str, optional
Name of seaborn style.
rc : dict, optional
Config flags.
Return... |
337,050 | def _map_or_apply(input_layer, op, *args, **kwargs):
kwargs.pop()
right = kwargs.pop(, False)
if input_layer.is_sequence():
if right:
args += (input_layer,)
else:
args = ((input_layer,) + args)
result = [op(*x, **kwargs) for x in _zip_with_scalars(args)]
if len(result) != len(inp... | Map op across the input if it is a sequence; otherwise apply it.
Note: This takes a keyword argument `right_` to right apply the op to this
input. The name is chosen to limit conflicts with other keyword arguments.
Args:
input_layer: The input_layer (self when chaining).
op: The op to apply:
*args: ... |
337,051 | def get_swagger(self, request):
api_base = self.parent
paths, definitions = self.parse_operations()
codecs = getattr(self.cenancestor, , CODECS)
return dict_filter({
: ,
: {
: self.title,
: str(getattr(api_base, , 0))
... | Generate this document. |
337,052 | def _grep_status(self, status_type):
args = "qstat -f {}".format(self.id).split()
res, _ = call(args)
exit_status = [line for line in res.split()
if in line]
try:
_, __, code = exit_status[0].split()
except IndexError:
code = None... | Greps through the job's current status to see if
it returned with the requested status.
status_type: complete, error |
337,053 | def load_L3G_arduino(filename, remove_begin_spurious=False, return_parser=False):
"Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)"
file_data = open(filename, ).read()
parser = L3GArduinoParser()
pa... | Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds) |
337,054 | def read_file(path, verbose=False):
for filehandle in filehandles(path, verbose=verbose):
return CTfile.load(filehandle) | Read single ``CTfile`` formatted file.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile` |
337,055 | def _delete_resource(self, url):
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().deleteURL(url, headers)
if not (response.status == 200 o... | When I Work DELETE method. |
337,056 | def add_field(self, name, data):
if name in self._fields:
raise ValueError
if not len(data) == self._num_fix:
raise ValueError
self._fields.append(name)
self.__dict__[name] = data | Add a new field to the datamat.
Parameters:
name : string
Name of the new field
data : list
Data for the new field, must be same length as all other fields. |
337,057 | def _raw_dimensions(self):
return tuple(
_RawDimension(dimension_dict, self._dimension_dicts)
for dimension_dict in self._dimension_dicts
) | Sequence of _RawDimension objects wrapping each dimension dict. |
337,058 | def periodic_hann(window_length):
return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
np.arange(window_length))) | Calculate a "periodic" Hann window.
The classic Hann window is defined as a raised cosine that starts and
ends on zero, and where every value appears twice, except the middle
point for an odd-length window. Matlab calls this a "symmetric" window
and np.hanning() returns it. However, for Fourier analysis, thi... |
337,059 | def _handler_http(self, result):
monitor = result[]
self.thread_debug("process_http", data=monitor, module=)
self.stats.http_handled += 1
logargs = {
:"metric",
: result[],
: monitor[],
: monitor[],
: monitor[... | Handle the result of an http monitor |
337,060 | def _parse_country_file(self, cty_file, country_mapping_filename=None):
import plistlib
cty_list = None
entities = {}
exceptions = {}
prefixes = {}
exceptions_index = {}
prefixes_index = {}
exceptions_counter = 0
prefixes_counter = 0
... | Parse the content of a PLIST file from country-files.com return the
parsed values in dictionaries.
Country-files.com provides Prefixes and Exceptions |
337,061 | def check_image_evaluation(self, image, show_history=False, detail=False, tag=None, policy=None):
itype, _, image_digest = self._discover_inputimage(image)
if not image_digest:
return [False, "could not get image record from anchore"]
if not tag and itype != :
re... | **Description**
Check the latest policy evaluation for an image
**Arguments**
- image: Input image can be in the following formats: registry/repo:tag
- show_history: Show all previous policy evaluations
- detail: Show detailed policy evaluation report
... |
337,062 | def write_chapter(self):
self.paragraphs = []
self.paragraphs.append()
for x in range(randint(0, 50)):
p = Paragraph(self.model)
self.paragraphs.append(p.get_paragraph())
self.paragraphs.append()
return self.paragraphs | Create a chapter
that contains a random number
of paragraphs |
337,063 | def builtin(self, name):
builtin_name = ast.Name("@py_builtins", ast.Load())
return ast.Attribute(builtin_name, name, ast.Load()) | Return the builtin called *name*. |
337,064 | def save_response_content(response, filename=, destination=os.path.curdir, chunksize=32768):
chunksize = chunksize or 32768
if os.path.sep in filename:
full_destination_path = filename
else:
full_destination_path = os.path.join(destination, filename)
full_destination_path = expand_f... | For streaming response from requests, download the content one CHUNK at a time |
337,065 | def bind_to_constructor(self, cls, constructor):
self._check_class(cls)
if constructor is None:
raise InjectorException( % cls)
self._bindings[cls] = _ConstructorBinding(constructor)
logger.debug(, cls, constructor)
return self | Bind a class to a callable singleton constructor. |
337,066 | def download(names):
s easier to
use this function by using list_updates and setting install=True.
Args:
names (str, list):
A single update or a list of updates to download. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
... | .. versionadded:: 2017.7.0
Downloads updates that match the list of passed identifiers. It's easier to
use this function by using list_updates and setting install=True.
Args:
names (str, list):
A single update or a list of updates to download. This can be any
combination o... |
337,067 | def _apply_conv(self, inputs, w):
tiled_weights = tf.tile(w, [1, 1, self._input_channels, 1])
outputs = tf.nn.depthwise_conv2d(inputs,
tiled_weights,
strides=self.stride,
padding=self._conv_op_pad... | Apply a depthwise_conv2d operation on `inputs` using variable `w`.
Args:
inputs: A Tensor of shape `data_format` and of type `tf.float16`,
`tf.bfloat16` or `tf.float32`.
w: A weight matrix of the same type as `inputs`.
Returns:
outputs: The result of the convolution operation on `i... |
337,068 | def show_service(kwargs=None, conn=None, call=None):
if call != :
raise SaltCloudSystemExit(
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if not in kwargs:
raise SaltCloudSystemExit()
data = conn.get_hosted_service_pro... | .. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service |
337,069 | def readDB(self):
self.dm = DataModel(directory = tools.getConfigDir())
if (self.first_start):
print(pre, "readDB : first start")
self.dm.clearAll()
self.dm.saveAll()
if not self.dm.checkCameraCollection():
self.dm.clearCameraCol... | Datamodel includes the following files: config.dat, devices.dat |
337,070 | def cardinality(gym_space):
if (gym_space.dtype == np.float32) or (gym_space.dtype == np.float64):
tf.logging.error("Returning None for a float gym space's cardinality: ",
gym_space)
return None
if isinstance(gym_space, Discrete):
return gym_space.n
if isinstance(gym_space, ... | Number of elements that can be represented by the space.
Makes the most sense for Discrete or Box type with integral dtype, ex: number
of actions in an action space.
Args:
gym_space: The gym space.
Returns:
np.int64 number of observations that can be represented by this space, or
returns None whe... |
337,071 | def fix_trim_curves(obj):
if obj.pdimension != 2:
raise GeomdlException("Input geometry must be a surface")
for o in obj:
trims = o.trims
if not trims:
continue
parbox = get_par_box(o.domain, True)
updated_trims = []
... | Fixes direction, connectivity and similar issues of the trim curves.
This function works for surface trim curves consisting of a single curve.
:param obj: input surface
:type obj: abstract.Surface |
337,072 | def _regexp(expr, item):
reg = re.compile(expr)
return reg.search(item) is not None | REGEXP function for Sqlite |
337,073 | def sense(self):
cmd_name = random.choice(self.senses)
command = getattr(self, cmd_name)
self.state[] = cmd_name
command() | Launches a few "sensing" commands such as 'ls', or 'pwd'
and updates the current bait state. |
337,074 | def find_matches_by_distance(cos_vects, cut_dist):
dist_rad = np.radians(cut_dist)
cos_t_cut = np.cos(dist_rad)
nsrc = cos_vects.shape[1]
match_dict = {}
for i, v1 in enumerate(cos_vects.T):
cos_t_vect = (v1 * cos_vects.T).sum(1)
cos_t_vect[cos_t_vect < -1.0] = -1.0
cos_... | Find all the pairs of sources within a given distance of each
other.
Parameters
----------
cos_vects : np.ndarray(e,nsrc)
Directional cosines (i.e., x,y,z component) values of all the
sources
cut_dist : float
Angular cut in degrees that will be used to select pairs ... |
337,075 | def zero_width_split(pattern, string):
splits = list((m.start(), m.end()) for m in regex.finditer(pattern, string, regex.VERBOSE))
starts = [0] + [i[1] for i in splits]
ends = [i[0] for i in splits] + [len(string)]
return [string[start:end] for start, end in zip(starts, ends)] | Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array |
337,076 | def _get_docstring(self):
left = self.position
while left:
if self.source_code[left: left + 3] in [, "' | Find the docstring we are currently in. |
337,077 | def uniprot_mapping_and_metadata(self, model_gene_source, custom_gene_mapping=None, outdir=None,
set_as_representative=False, force_rerun=False):
if custom_gene_mapping:
genes_to_map = list(custom_gene_mapping.values())
else:
... | Map all genes in the model to UniProt IDs using the UniProt mapping service.
Also download all metadata and sequences.
Args:
model_gene_source (str): the database source of your model gene IDs.
See: http://www.uniprot.org/help/api_idmapping
Common model gene ... |
337,078 | def send_request(self, *args, **kwargs):
try:
return self.session.request(*args, **kwargs)
except ConnectionError:
self.session.close()
return self.session.request(*args, **kwargs) | Wrapper for session.request
Handle connection reset error even from pyopenssl |
337,079 | def get_algo(self, args: argparse.Namespace, algo: str) -> object:
if algo == :
return NearestNeighbor(args.nnk) | Returns machine learning algorithm based on arguments |
337,080 | def _download(self):
min_x, max_x, min_y, max_y = self.gssha_grid.bounds(as_geographic=True)
if self.era_download_data == :
log.info("Downloading ERA5 data ...")
download_era5_for_gssha(self.lsm_input_folder_path,
self.downloa... | download ERA5 data for GSSHA domain |
337,081 | def get_modification_by_hash(self, sha512: str) -> Optional[Modification]:
return self.session.query(Modification).filter(Modification.sha512 == sha512).one_or_none() | Get a modification by a SHA512 hash. |
337,082 | def skip_item_key(self, item, key):
if "skip" in item:
item["skip"].append(key)
else:
item["skip"] = [key]
return item | Add the key to the item's "skip" list |
337,083 | def status(name, sig=None):
*
if sig:
return bool(__salt__[](sig))
cmd = .format(_cmd(), name)
return not __salt__[](cmd) | Return the status for a service, returns a bool whether the service is
running.
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> |
337,084 | def get_last_weekday(self, including_today=False):
weekday = self.date_time.weekday()
return Weekday.get_last(weekday, including_today=including_today) | Gets last week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of last monday, tuesday .. |
337,085 | def _rewrite_f(self, q):
if isinstance(q, models.F):
q.name = rewrite_lookup_key(self.model, q.name)
return q
if isinstance(q, Node):
q.children = list(map(self._rewrite_f, q.children))
if hasattr(q, ):
q.lhs = self._rewrite_f(q.l... | Rewrite field names inside F call. |
337,086 | def send(self, stat, value, rate=1):
if rate < 1:
value = "%s|@%s" % (value, rate)
return super().send(stat, value, rate) | Send message to backend. |
337,087 | def blk_1d_short(blk, shape):
maxpix, _ = blk_coverage_1d(blk, shape)
for i in range(0, maxpix, blk):
yield slice(i, i + blk) | Iterate through the slices that recover a line.
This function is used by :func:`blk_nd_short` as a base 1d case.
The function stops yielding slices when the size of
the remaining slice is lesser than `blk`.
:param blk: the size of the block
:param shape: the size of the array
:return: a gener... |
337,088 | def updatecache(filename, module_globals=None):
if filename in cache:
del cache[filename]
if not filename or (filename.startswith() and filename.endswith()):
return []
fullname = filename
try:
stat = os.stat(fullname)
except OSError:
basename = filename
... | Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list. |
337,089 | def report(self, account_id, status_ids = None, comment = None, forward = False):
account_id = self.__unpack_id(account_id)
if not status_ids is None:
if not isinstance(status_ids, list):
status_ids = [status_ids]
status_ids = list(map(lambda x: self... | Report statuses to the instances administrators.
Accepts a list of toot IDs associated with the report, and a comment.
Set forward to True to forward a report of a remote user to that users
instance as well as sending it to the instance local administrators.
Returns a `report ... |
337,090 | def build_collate_fn(batch_first=False, parallel=True, sort=False):
def collate_seq(seq):
lengths = [len(s) for s in seq]
batch_length = max(lengths)
shape = (batch_length, len(seq))
seq_tensor = torch.full(shape, config.PAD, dtype=torch.int64)
for i, s in enu... | Factory for collate_fn functions.
:param batch_first: if True returns batches in (batch, seq) format, if
False returns in (seq, batch) format
:param parallel: if True builds batches from parallel corpus (src, tgt)
:param sort: if True sorts by src sequence length within each batch |
337,091 | def source(self):
source, source64, = "", ""
for line in self.SLACKBUILDS_TXT.splitlines():
if line.startswith(self.line_name):
sbo_name = line[17:].strip()
if line.startswith(self.line_down):
if sbo_name == self.name and line[21:].strip()... | Grab sources downloads links |
337,092 | def ecdh(self, identity, pubkey):
assert pubkey[:1] == b
peer = ecdsa.VerifyingKey.from_string(
pubkey[1:],
curve=ecdsa.curves.NIST256p,
hashfunc=hashlib.sha256)
shared = ecdsa.VerifyingKey.from_public_point(
point=(peer.pubkey.point * sel... | Get shared session key using Elliptic Curve Diffie-Hellman. |
337,093 | def one_step(self, current_state, previous_kernel_results):
@tfp.mcmc.internal.util.make_innermost_setter
def set_num_leapfrog_steps(kernel_results, num_leapfrog_steps):
return kernel_results._replace(
accepted_results=kernel_results.accepted_results._replace(
num_leapfrog_st... | Runs one iteration of NeuTra.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`.
previous_kernel_results: `collections... |
337,094 | def bear(a1, b1, a2, b2):
tol = 1e-15
v1 = CartesianVector.from_spherical(1.0, a1, b1)
v2 = CartesianVector.from_spherical(1.0, a2, b2)
v0 = CartesianVector.from_spherical(r=1.0, alpha=0.0, delta=d2r(90.0))
if abs(v1.cross(v0).mod) < tol... | Find bearing/position angle between two points on a unit sphere.
Parameters
----------
a1, b1 : float
Longitude-like and latitude-like angles defining the first
point. Both are in radians.
a2, b2 : float
Longitude-like and latitude-like angles defining the second
point.... |
337,095 | def set(self, is_on=None, brightness=None, cancel_transition=True):
if cancel_transition:
self._cancel_active_transition()
if is_on is not None:
self._is_on = is_on
if brightness is not None:
self._assert_is_brightness(brightness)
self._... | Set properties of the led simultaneously before updating pwm values.
:param is_on: On-off state of the led.
:param brightness: Brightness of the led.
:param cancel_transition: Cancel active transitions. |
337,096 | def string_to_bytes(string):
if string == :
return 0
import re
match = re.match(, string)
if not match:
raise RuntimeError(.format(string))
if match.group(3):
raise RuntimeError(.format(match.group(3)))
value = float(match.group(1))
if match.group(2) is None:
... | Returns the amount of bytes in a human readable form up to Yottabytes (YB).
:param string: integer with suffix (b, k, m, g, t, p, e, z, y)
:return: amount of bytes in string representation
>>> string_to_bytes('1024')
1024
>>> string_to_bytes('1024k')
1048576
>>> string_to_bytes('4 G')
4... |
337,097 | def print_tree(graph, tails, node_id_map):
wa... | Print out a tree of blocks starting from the common ancestor. |
337,098 | def parse_a_hall(self, hall):
if hall not in self.hall_to_link:
return None
page = requests.get(self.hall_to_link[hall], timeout=60)
soup = BeautifulSoup(page.content, )
soup.prettify()
washers = {"open": 0, "running": 0, "out_of_order": 0, "offline": 0, "t... | Return names, hall numbers, and the washers/dryers available for a certain hall.
:param hall:
The ID of the hall to retrieve data for.
:type hall: int |
337,099 | def mavlink_packet(self, msg):
type = msg.get_type()
master = self.master
if type in [ ]:
ilock = self.get_rc_input(msg, self.interlock_channel)
if ilock <= 0:
self.console.set_status(, , fg=, row=4)
elif ilock >= 1800:
... | handle an incoming mavlink packet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.