text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _send_command(self, command, raw_text=False):
"""
Wrapper for NX-API show method.
Allows more code sharing between NX-API and SSH.
"""
return self.device.show(command, raw_text=raw_text) | 0.008658 |
def get_temperature_from_humidity(self):
"""
Returns the temperature in Celsius from the humidity sensor
"""
self._init_humidity() # Ensure humidity sensor is initialised
temp = 0
data = self._humidity.humidityRead()
if (data[2]): # Temp valid
temp ... | 0.005731 |
def _select_nonblock(sockets, remain=None):
"""This function is called during sendrecv() routine to select
the available sockets.
"""
# pcap sockets aren't selectable, so we return all of them
# and ask the selecting functions to use nonblock_recv instead of recv
def _sleep_nonblock_recv(self):
... | 0.001767 |
def conditional_expected_number_of_purchases_up_to_time(self, t, frequency, recency, T):
"""
Conditional expected number of repeat purchases up to time t.
Calculate the expected number of repeat purchases up to time t for a
randomly choose individual from the population, given they have... | 0.00318 |
def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... | 0.003806 |
def get_location(self, location_id: int, timeout: int=None):
"""Get a location information
Parameters
----------
location_id: int
A location ID
See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json
for a list of acceptable locatio... | 0.009191 |
def module_set_id(self) -> str:
"""Compute unique id of YANG modules comprising the data model.
Returns:
String consisting of hexadecimal digits.
"""
fnames = sorted(["@".join(m) for m in self.schema_data.modules])
return hashlib.sha1("".join(fnames).encode("ascii"))... | 0.006024 |
def rotateInZMat(theta_deg):
"""Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If... | 0.00907 |
def _delete_json(self, instance, space=None, rel_path=None, extra_params=None, id_field=None, append_to_path=None):
"""
Base level method for removing data from the API
"""
model = type(instance)
# Only API.spaces and API.event should not provide
# the `space argument
... | 0.001618 |
def to_si(self, values, from_unit):
"""Return values in SI and the units to which the values have been converted."""
if from_unit in self._si_units:
return values, from_unit
elif from_unit == 'degF-hours':
return self.to_unit(values, 'degC-hours', from_unit), 'degC-hours'... | 0.007299 |
def place_order(self, amount, price, side, ord_type, symbol='btcusd', exchange='bitfinex'):
"""
Submit a new order.
:param amount:
:param price:
:param side:
:param ord_type:
:param symbol:
:param exchange:
:return:
"""
payload = {
... | 0.005663 |
def add_chapter(self, title):
'''
Adds a new chapter to the report.
:param str title: Title of the chapter.
'''
chap_id = 'chap%s' % self.chap_counter
self.chap_counter += 1
self.sidebar += '<a href="#%s" class="list-group-item">%s</a>\n' % (
chap_id,... | 0.005115 |
def should_be_hidden_as_cause(exc):
""" Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """
# reduced traceback in case of HasWrongType (instance_of checks)
from valid8.validation_lib.types import HasWrongType, IsWrongType
return isinstance(exc, (H... | 0.00578 |
def _single_orbit_find_actions(orbit, N_max, toy_potential=None,
force_harmonic_oscillator=False):
"""
Find approximate actions and angles for samples of a phase-space orbit,
`w`, at times `t`. Uses toy potentials with known, analytic action-angle
transformations to approx... | 0.000911 |
def merge_groups(self, indices):
"""Extend the lists within the DICOM groups dictionary.
The indices will indicate which list have to be extended by which
other list.
Parameters
----------
indices: list or tuple of 2 iterables of int, bot having the same len
... | 0.002116 |
def form_valid(self, post_form, attachment_formset, poll_option_formset, **kwargs):
""" Processes valid forms. """
save_poll_option_formset = poll_option_formset is not None \
and not self.preview
valid = super().form_valid(
post_form, attachment_formset, poll_option_for... | 0.009227 |
def dependency_of_targets(targets, op):
"""
Check that op is in the subgraph induced by the dependencies of targets.
The result is memoized.
This is useful if some SessionRunHooks should be run only together with certain ops.
Args:
targets: a tuple of ops or tensors. The targets to find de... | 0.003597 |
def assembly_length(self):
"""
Use SeqIO.parse to extract the total number of bases in each assembly file
"""
for sample in self.metadata:
# Only determine the assembly length if is has not been previously calculated
if not GenObject.isattr(sample, 'assembly_lengt... | 0.006527 |
def apply_transform(
t: Union[List[List[float]], np.ndarray],
pos: Tuple[float, float, float],
with_offsets=True) -> Tuple[float, float, float]:
"""
Change of base using a transform matrix. Primarily used to render a point
in space in a way that is more readable for the user.
:p... | 0.001309 |
def modulePath(self):
"""
Returns the module path information for this proxy plugin. This path
will represent the root module that will be imported when the instance
is first created of this plugin.
:return <str>
"""
base_path = os.path.dirname(self.... | 0.005051 |
def received_sig_option_changed(self, option, value):
"""
Called when sig_option_changed is received.
If option being changed is autosave_mapping, then synchronize new
mapping with all editor stacks except the sender.
"""
if option == 'autosave_mapping':
... | 0.003831 |
def fetch(self, request, spider):
"""download_func"""
info = self._extract_key_info(request)
ret = self.store.fetch_file(request.url, info['key'], info['bucket'])
return Response(request.url, body=json.dumps(ret)) | 0.00813 |
def load_entry_point_actions(self, entry_point_group):
"""Load actions from an entry point group.
:param entry_point_group: The entrypoint for extensions.
"""
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_action(ep.load()) | 0.006601 |
def parse_md_code_options(options):
"""Parse 'python class key="value"' into [('python', None), ('class', None), ('key', 'value')]"""
metadata = []
while options:
name_and_value = re.split(r'[\s=]+', options, maxsplit=1)
name = name_and_value[0]
# Equal sign in between name and wha... | 0.002427 |
def results(self, times='all', t_precision=12, **kwargs):
r"""
Fetches the calculated quantity from the algorithm and returns it as
an array.
Parameters
----------
times : scalar or list
Time steps to be returned. The default value is 'all' which results
... | 0.000975 |
def _write_packed_data(self, data_out, table):
"""This is kind of legacy function - this functionality may be useful for some people, so even though
now the default of writing CSV is writing unpacked data (divided by independent variable) this method is
still available and accessible if ```pack`... | 0.007874 |
def _init_tag_params(self, tag, params):
"""
Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTML tag as... | 0.0032 |
def update_tags(self, idlist, tags_add=None, tags_remove=None):
"""
Updates the 'tags' field for a bug.
"""
tags = {}
if tags_add:
tags["add"] = self._listify(tags_add)
if tags_remove:
tags["remove"] = self._listify(tags_remove)
d = {
... | 0.004545 |
def chunks(raw):
"""Yield successive EVENT_SIZE sized chunks from raw."""
for i in range(0, len(raw), EVENT_SIZE):
yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE]) | 0.005405 |
def residual_histogram(df, col_true, col_pred=None):
"""
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: s... | 0.002981 |
def get_objective_bank_form_for_create(self, objective_bank_record_types=None):
"""Gets the objective bank form for creating new objective banks.
A new form should be requested for each create transaction.
arg: objectiveBankRecordTypes (osid.type.Type): array of
objective bank... | 0.002804 |
def threaded_quit(self, arg):
""" quit command when several threads are involved. """
threading_list = threading.enumerate()
mythread = threading.currentThread()
for t in threading_list:
if t != mythread:
ctype_async_raise(t, Mexcept.DebuggerQuit)
... | 0.007874 |
def check_connection(host='localhost', port=27017, username=None, password=None,
authdb=None, max_delay=1):
"""Check if a connection could be made to the mongo process specified
Args:
host(str)
port(int)
username(str)
password(str)
authdb (str): data... | 0.007188 |
def from_text(cls, filename, **kwargs):
'''
Create a constellation by reading a catalog in from a text file,
as long as it's formated as in to_text() with identifiers, coordinates, magnitudes.
Parameters
----------
filename : str
The filename to read in.
... | 0.002208 |
def fletcher16_checkbytes(binbuf, offset):
"""Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
Including the bytes into the buffer (at the position marked by offset) the # noqa: E501
global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501
... | 0.00104 |
def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if ... | 0.001776 |
def create_sum(self, bound=1):
"""
Create a totalizer object encoding a cardinality
constraint on the new list of relaxation literals obtained
in :func:`process_sels` and :func:`process_sums`. The
clauses encoding the sum of the relaxation literals are
... | 0.001015 |
def to_shcoeffs(self, nmax=None, normalization='4pi', csphase=1):
"""
Return the spherical harmonic coefficients using the first n Slepian
coefficients.
Usage
-----
s = x.to_shcoeffs([nmax])
Returns
-------
s : SHCoeffs class instance
... | 0.000834 |
def generate_rsa_public_and_private(bits=_DEFAULT_RSA_KEY_BITS):
"""
<Purpose>
Generate public and private RSA keys with modulus length 'bits'. The
public and private keys returned conform to
'securesystemslib.formats.PEMRSA_SCHEMA' and have the form:
'-----BEGIN RSA PUBLIC KEY----- ...'
or
... | 0.009417 |
def run(self):
"""Request client connection and start the main loop."""
if self.args.roster_cache and os.path.exists(self.args.roster_cache):
logging.info(u"Loading roster from {0!r}"
.format(self.args.roster_cache))
try:
... | 0.00531 |
def process_data(self, new_data):
"""
handles incoming data from the `IrcProtocol` connection.
Main data processing/routing is handled by the _process_line
method, inherited from `ServerConnection`
"""
self.buffer.feed(new_data)
# process each non-empty line afte... | 0.003953 |
def doc_to_help(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines.
whitespace_only_line = re... | 0.021277 |
def delete(self, username, napp):
"""Delete a NApp.
Raises:
requests.HTTPError: If 400 <= status < 600.
"""
api = self._config.get('napps', 'api')
endpoint = os.path.join(api, 'napps', username, napp, '')
content = {'token': self._config.get('auth', 'token')... | 0.004598 |
def dispatch(self, request, *args, **kwargs):
"""
Does request processing for return_url query parameter and redirects with it's missing
We can't do that in the get method, as it does not exist in the View base class
and child mixins implementing get do not call super().get
"""
... | 0.004537 |
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root... | 0.001281 |
def randn(*shape, **kwargs):
"""Draw random samples from a normal (Gaussian) distribution.
Samples are distributed according to a normal distribution parametrized
by *loc* (mean) and *scale* (standard deviation).
Parameters
----------
loc : float or NDArray
Mean (centre) of the distri... | 0.003166 |
def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution':
"""Try to create a new substitution with the given variable added.
See :meth:`try_add_variable` for a version of this method that modifies the substitution
in place.
Args:
vari... | 0.005841 |
def create_session(self, alias, url, headers={}, cookies={},
auth=None, timeout=None, proxies=None,
verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
""" Create Session: create a HTTP session to a server
``url`` Base url of the... | 0.004724 |
def receive(self):
""" receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response porti... | 0.002845 |
def create_object(self, alias, *args, **kwargs):
"""Constructs the type with the given alias using the given args and kwargs.
NB: aliases may be the alias' object type itself if that type is known.
:API: public
:param alias: Either the type alias or the type itself.
:type alias: string|type
:... | 0.004292 |
def _process_gradient(self, backward, dmdp):
"""
backward: `callable`
callable that backpropagates the gradient of the model w.r.t to
preprocessed input through the preprocessing to get the gradient
of the model's output w.r.t. the input before preprocessing
d... | 0.003058 |
def GetWindowText(handle: int) -> str:
"""
GetWindowText from Win32.
handle: int, the handle of a native window.
Return str.
"""
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.user32.GetWindowTextW(ctypes.c_void_p(handle), values, MAX_PATH)
return values.val... | 0.006211 |
def mk_external_entity(metamodel, s_ee):
'''
Create a python object from a BridgePoint external entity with bridges
realized as python member functions.
'''
bridges = many(s_ee).S_BRG[19]()
names = [brg.Name for brg in bridges]
EE = collections.namedtuple(s_ee.Key_Lett, names)
funcs = l... | 0.002198 |
def define(cls, name, **kwargs):
"""
Utility to quickly and easily declare Stream classes. Designed
for interactive use such as notebooks and shouldn't replace
parameterized class definitions in source code that is imported.
Takes a stream class name and a set of keywords where ... | 0.001192 |
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_t... | 0.001622 |
def setHeader(self, fileHeader):
"""
Sets the file header
"""
self.technician = fileHeader["technician"]
self.recording_additional = fileHeader["recording_additional"]
self.patient_name = fileHeader["patientname"]
self.patient_additional = fileHeader["patient_addi... | 0.003026 |
def insert_source_info(result):
"""Adds info about source of test result if available."""
comment = result.get("comment")
# don't change comment if it already exists
if comment:
return
source = result.get("source")
job_name = result.get("job_name")
run = result.get("run")
source... | 0.001912 |
def stop_task(cls, task_tag, stop_dependent=True, stop_requirements=False):
""" Stop started task from registry
:param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
:param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
:param stop_requirement... | 0.025594 |
def unlink_rich_menu_from_user(self, user_id, timeout=None):
"""Call unlink rich menu from user API.
https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user
:param str user_id: ID of the user
:param timeout: (optional) How long to wait for the server
... | 0.002967 |
def _build_codes_reverse(
codes: Dict[str, Dict[str, str]]) -> Dict[str, Dict[str, str]]:
""" Build a reverse escape-code to name map, based on an existing
name to escape-code map.
"""
built = {} # type: Dict[str, Dict[str, str]]
for codetype, codemap in codes.items():
for name,... | 0.0016 |
def pairs(args):
"""
%prog pairs pairsfile <fastbfile|fastqfile>
Parse ALLPATHS pairs file, and write pairs IDs and single read IDs in
respective ids files: e.g. `lib1.pairs.fastq`, `lib2.pairs.fastq`,
and single `frags.fastq` (with single reads from lib1/2).
"""
from jcvi.assembly.preproce... | 0.001381 |
def _setup_edge(self, capabilities):
"""Setup Edge webdriver
:param capabilities: capabilities object
:returns: a new local Edge driver
"""
edge_driver = self.config.get('Driver', 'edge_driver_path')
self.logger.debug("Edge driver path given in properties: %s", edge_driv... | 0.007634 |
def update_bios_data_by_post(self, data):
"""Update bios data by post
:param data: default bios config data
"""
bios_settings_data = {
'Attributes': data
}
self._conn.post(self.path, data=bios_settings_data) | 0.007463 |
def process(self, items_block):
"""Return items as they come, updating their metadata__enriched_on field.
:param items_block:
:return: hits blocks as they come, updating their metadata__enriched_on field. Namedtuple containing:
- processed: number of processed hits
- out... | 0.007342 |
def correct(args):
"""
%prog correct *.fastq
Correct reads using ErrorCorrection. Only PE will be used to build the K-mer
table.
"""
p = OptionParser(correct.__doc__)
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
lstfile = ... | 0.001862 |
def media(self):
"""
Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified.
"""
return self.widget.media + self.checkbox.media + Media(self.Media) | 0.007547 |
def __get_username():
""" Returns the effective username of the current process. """
if WINDOWS:
return getpass.getuser()
import pwd
return pwd.getpwuid(os.geteuid()).pw_name | 0.005051 |
def raw(self, raw):
"""
Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object.
:param raw: The raw of this RuntimeRawExtension.
:type: str
"""
if raw is None:
raise ValueError("Invalid value for `raw`, must not b... | 0.015552 |
def string_to_daterange(str_range, delimiter='-', as_dates=False, interval=CLOSED_CLOSED):
"""
Convert a string to a DateRange type. If you put only one date, it generates the
relevant range for just that date or datetime till 24 hours later. You can optionally
use mixtures of []/() around the DateRange... | 0.006017 |
def pause(self):
"""Pauses playback"""
if self.isPlaying is True:
self._execute("pause")
self._changePlayingState(False) | 0.0125 |
def observe(cls, *args, **kwargs):
"""
Mark a method as receiving notifications. Comes in two flavours:
.. method:: observe(name, **types)
:noindex:
A decorator living in the class. Can be applied more than once to
the same method, provided the names differ.
... | 0.000506 |
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), (filename, self.subdir)
return filename[len(self.subdir):].lstrip(r"\/") | 0.023077 |
def _submitQuery(self, gitquery, gitvars={}, verbose=False, rest=False):
"""Send a curl request to GitHub.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
... | 0.00194 |
def DomainsGet(self, parameters = None, domain_id = -1):
"""
This method returns the domains of the current user.
The list also contains the domains to which the users has not yet been accepted.
@param parameters (dictonary) - Dictionary containing the para... | 0.017689 |
def filter(self, **config) -> CallbackDataFilter:
"""
Generate filter
:param config:
:return:
"""
for key in config.keys():
if key not in self._part_names:
raise ValueError(f"Invalid field name '{key}'")
return CallbackDataFilter(self,... | 0.006098 |
def DOM_setFileInputFiles(self, files, **kwargs):
"""
Function path: DOM.setFileInputFiles
Domain: DOM
Method name: setFileInputFiles
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'files' (type: array) -> Array of file paths to set.
Optional argument... | 0.038194 |
def request_param_update(self, var_id):
"""Place a param update request on the queue"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, READ_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', var_id)
... | 0.004158 |
def descendants(self,collapseLists=True):
"""
A more genteel method of accessing an object's children (than self.children)
If collapseLists==True, the returned list is guaranteed not to be a list of lists.
If collapseLists==False, the returned list *may* be a list of lists, [cf. self.children]
in the case of... | 0.033445 |
def insert_sections_some(ol,*secs,**kwargs):
'''
ol = initRange(0,20,1)
ol
loc = 6
rslt = insert_sections_some(ol,['a','a','a'],['c','c','c','c'],index=loc)
rslt
####
'''
if('mode' in kwargs):
mode = kwargs["mode"]
else:
mode = "new"
lo... | 0.015152 |
def start(jar_path=None, nthreads=-1, enable_assertions=True, max_mem_size=None, min_mem_size=None,
ice_root=None, log_dir=None, log_level=None, port="54321+", name=None, extra_classpath=None,
verbose=True, jvm_custom_args=None, bind_to_localhost=True):
"""
Start new H2O serv... | 0.006439 |
def delete(self, path='', **params):
"""
Make a DELETE request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
DELETE requests ask to delete the object represented by this URL.
"""
params = jsonify_p... | 0.004292 |
def run_filter(vrn_file, align_bam, ref_file, data, items):
"""Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants.
Moves damage estimation to INFO field, instead of leaving in FILTER.
"""
if not should_filter(items) or not vcfutils.vcf_has_variants(vrn_file):
... | 0.003937 |
def _dmpaft_cmd(self, time_fields):
'''
issue a command to read the archive records after a known time stamp.
'''
records = []
# convert time stamp fields to buffer
tbuf = struct.pack('2H', *time_fields)
# 1. send 'DMPAFT' cmd
self._cmd('DMPAFT')
... | 0.001153 |
def send(self, messages=None, api_key=None, secure=None, test=None,
**request_args):
'''Send batch request to Postmark API.
Returns result of :func:`requests.post`.
:param messages: Batch messages to send to the Postmark API.
:type messages: A list of :class:`Message`
... | 0.005549 |
def desaturate(self):
"""Desaturates the layer, making it grayscale.
Instantly removes all color information from the layer,
while maintaing its alpha channel.
"""
alpha = self.img.split()[3]
self.img = self.img.convert("L")
self.img = self.img... | 0.01626 |
def Animation_resolveAnimation(self, animationId):
"""
Function path: Animation.resolveAnimation
Domain: Animation
Method name: resolveAnimation
Parameters:
Required arguments:
'animationId' (type: string) -> Animation id.
Returns:
'remoteObject' (type: Runtime.RemoteObject) -> Correspon... | 0.042773 |
def update_parameters(url, parameters, encoding='utf8'):
""" Updates a URL's existing GET parameters.
:param url: a base URL to which to add additional parameters.
:param parameters: a dictionary of parameters, any mix of
unicode and string objects as the parameters and the values.
:parameter encoding: the... | 0.009387 |
def _decode_ctrl_packet(self, version, packet):
"""Decode a control packet into the list of sensors."""
for i in range(5):
input_bit = packet[i]
self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5... | 0.005405 |
def delete_intent(self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Deletes the specified intent.
Example:
>>> import... | 0.002593 |
def construct(parent=None, defaults=None, **kwargs):
"""
Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution ... | 0.000935 |
def create_calc_dh_dv(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the index.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
... | 0.000729 |
def _serialize_iterable(obj):
"""
Only for serializing list and tuples and stuff.
Dicts and Strings/Unicode is treated differently.
String/Unicode normally don't need further serialization and it would cause
a max recursion error trying to do so.
:param obj:
:return:
"""
if isinstanc... | 0.001969 |
def _pwl1_to_poly(self, generators):
""" Converts single-block piecewise-linear costs into linear
polynomial.
"""
for g in generators:
if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2):
g.pwl_to_poly()
return generators | 0.00678 |
def sort(self, *sorting, **kwargs):
"""Sort resources."""
sorting_ = []
for name, desc in sorting:
field = self.meta.model._meta.fields.get(name)
if field is None:
continue
if desc:
field = field.desc()
sorting_.appe... | 0.004587 |
def _program_files_from_executable(self, executable, required_paths, parent_dir=False):
"""
Get a list of program files by expanding a list of path patterns
and interpreting it as relative to the executable.
This method can be used as helper for implementing the method program_files().
... | 0.008432 |
def _run_hooks(self):
"""Calls any registered hooks providing the current state."""
for hook in self.hooks:
getattr(self, hook)(self._state) | 0.011905 |
def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
for filename in files:
if os.path.... | 0.001653 |
def PushPopItem(obj, key, value):
'''
A context manager to replace and restore a value using a getter and setter.
:param object obj: The object to replace/restore.
:param object key: The key to replace/restore in the object.
:param object value: The value to replace.
Example::
with Push... | 0.001616 |
def copy(self, clr=None, d=0.0):
"""
Returns a copy of the range.
Optionally, supply a color to get a range copy
limited to the hue of that color.
"""
cr = ColorRange()
cr.name = self.name
cr.h = deepcopy(self.h)
cr.s = deepcopy(self.s)
c... | 0.004739 |
def get_participants_for_section(section, person=None):
"""
Returns a list of gradebook participants for the passed section and person.
"""
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if ... | 0.001767 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.