Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
100 | def data(self):
try:
data = self._data
except AttributeError:
data = self._data = json.loads(self.json)
return data | Returns self.json loaded as a python object. |
101 | def dbmin10years(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
self._dbmin10years = value | Corresponds to IDD Field `dbmin10years`
10-year return period values for minimum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmin10years`
Unit: C
if `value` is None it will not be checked against the
specification a... |
102 | def build_java_worker_command(
java_worker_options,
redis_address,
plasma_store_name,
raylet_name,
redis_password,
temp_dir,
):
assert java_worker_options is not None
command = "java ".format(java_worker_options)
if redis_address is not None:
com... | This method assembles the command used to start a Java worker.
Args:
java_worker_options (str): The command options for Java worker.
redis_address (str): Redis address of GCS.
plasma_store_name (str): The name of the plasma store socket to connect
to.
raylet_name (str): T... |
103 | def clean_course(self):
course_id = self.cleaned_data[self.Fields.COURSE].strip()
if not course_id:
return None
try:
client = EnrollmentApiClient()
return client.get_course_details(course_id)
except (HttpClientError, HttpServerError):
... | Verify course ID and retrieve course details. |
104 | def decrease_frequency(self, frequency=None):
if frequency is None:
javabridge.call(self.jobject, "decreaseFrequency", "()V")
else:
javabridge.call(self.jobject, "decreaseFrequency", "(I)V", frequency) | Decreases the frequency.
:param frequency: the frequency to decrease by, 1 if None
:type frequency: int |
105 | def _process_response_xml(self, response_xml):
result = {}
xml = ElementTree.fromstring(response_xml)
if xml.tag == :
logger.error(
u +
% response_xml)
errors_message = u
for error in xml.findall():
err... | Processa o xml de resposta e caso não existam erros retorna um
dicionario com o codigo e data.
:return: dictionary |
106 | def purge(self, queue, nowait=True, ticket=None, cb=None):
nowait = nowait and self.allow_nowait() and not cb
args = Writer()
args.write_short(ticket or self.default_ticket).\
write_shortstr(queue).\
write_bit(nowait)
self.send_frame(MethodFrame(self.cha... | Purge all messages in a queue. |
107 | def parallel_map(task, values, task_args=tuple(), task_kwargs={},
num_processes=CPU_COUNT):
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
Publisher().publish("terra.parallel.start", len(values))
nfinished = [0]
def _callback(_):
nfinis... | Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
... |
108 | def clone(self):
self.config[] = self.config[].lower()
self.config[] = int(self.config[] * 1024)
print("Cloning %s to new host %s with %sMB RAM..." % (
self.config[],
self.config[],
self.config[]
))
ip_settings = list()
... | Command Section: clone
Clone a VM from a template |
109 | def boxes_intersect(box1, box2):
xmin1, xmax1, ymin1, ymax1 = box1
xmin2, xmax2, ymin2, ymax2 = box2
if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \
interval_intersection_width(ymin1, ymax1, ymin2, ymax2):
return True
else:
return False | Determines if two rectangles, each input as a tuple
(xmin, xmax, ymin, ymax), intersect. |
110 | def difference(self, other, sort=None):
self._validate_sort_keyword(sort)
self._assert_can_do_setop(other)
other, result_names = self._convert_can_do_setop(other)
if len(other) == 0:
return self
if self.equals(other):
return MultiIndex(levels=se... | Compute set difference of two MultiIndex objects
Parameters
----------
other : MultiIndex
sort : False or None, default None
Sort the resulting MultiIndex if possible
.. versionadded:: 0.24.0
.. versionchanged:: 0.24.1
Changed the de... |
111 | def enable_external_loaders(obj):
for name, loader in ct.EXTERNAL_LOADERS.items():
enabled = getattr(
obj, "{}_ENABLED_FOR_DYNACONF".format(name.upper()), False
)
if (
enabled
and enabled not in false_values
and loader not in obj.LOADERS_F... | Enable external service loaders like `VAULT_` and `REDIS_`
looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` |
112 | def fit(self):
self._mcmcfit = self.mcmcsetup.run()
self._mcmcfit.burnin(self.burnin)
dmin = min(self._mcmcfit.depth_segments)
dmax = max(self._mcmcfit.depth_segments)
self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments)
self._depth = np.arange(dmin, dm... | Fit MCMC AgeDepthModel |
113 | def _netstat_route_sunos():
ret = []
cmd =
out = __salt__[](cmd, python_shell=True)
for line in out.splitlines():
comps = line.split()
ret.append({
: ,
: comps[0],
: comps[1],
: ,
: comps[2],
: comps[5] if len(... | Return netstat routing information for SunOS |
114 | def read_snapshots(path, comments="
nodetype=None, timestamptype=None, encoding=, keys=False):
ids = None
lines = (line.decode(encoding) for line in path)
if keys:
ids = read_ids(path.name, delimiter=delimiter, timestamptype=timestamptype)
return parse_snapshots(lines, c... | Read a DyNetx graph from snapshot graph list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter |
115 | def request(self, method, url, **kwargs):
resp = super(CookieSession, self).request(method, url, **kwargs)
if not self._auto_renew:
return resp
is_expired = any((
resp.status_code == 403 and
response_to_json_dict(resp).get() == ,
resp.st... | Overrides ``requests.Session.request`` to renew the cookie and then
retry the original request (if required). |
116 | def _iter_restrict(self, zeros, ones):
inputs = list(self.inputs)
unmapped = dict()
for i, v in enumerate(self.inputs):
if v in zeros:
inputs[i] = 0
elif v in ones:
inputs[i] = 1
else:
unmapped[v] = i
... | Iterate through indices of all table entries that vary. |
117 | def _setup_states(state_definitions, prev=()):
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
"The attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
... | Create a StateList object from a 'states' Workflow attribute. |
118 | def resolve(self, geoid, id_only=False):
level, code, validity = geoids.parse(geoid)
qs = self(level=level, code=code)
if id_only:
qs = qs.only()
if validity == :
result = qs.latest()
else:
result = qs.valid_at(validity).first()
... | Resolve a GeoZone given a GeoID.
The start date is resolved from the given GeoID,
ie. it find there is a zone valid a the geoid validity,
resolve the `latest` alias
or use `latest` when no validity is given.
If `id_only` is True,
the result will be the resolved GeoID
... |
119 | def handle_no_document(self, item_session: ItemSession) -> Actions:
self._waiter.reset()
action = self.handle_response(item_session)
if action == Actions.NORMAL:
item_session.set_status(Status.skipped)
return action | Callback for successful responses containing no useful document.
Returns:
A value from :class:`.hook.Actions`. |
120 | def _constrain_pan(self):
if self.xmin is not None and self.xmax is not None:
p0 = self.xmin + 1. / self._zoom[0]
p1 = self.xmax - 1. / self._zoom[0]
p0, p1 = min(p0, p1), max(p0, p1)
self._pan[0] = np.clip(self._pan[0], p0, p1)
if self.ymin is n... | Constrain bounding box. |
121 | def predict(self, t):
t = np.asarray(t)
return self._predict(np.ravel(t)).reshape(t.shape) | Predict the smoothed function value at time t
Parameters
----------
t : array_like
Times at which to predict the result
Returns
-------
y : ndarray
Smoothed values at time t |
122 | def send(self, value):
if not self.block and self._stdin is not None:
self.writer.write("{}\n".format(value))
return self
else:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE) | Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chaining |
123 | def kth_to_last_dict(head, k):
if not (head and k > -1):
return False
d = dict()
count = 0
while head:
d[count] = head
head = head.next
count += 1
return len(d)-k in d and d[len(d)-k] | This is a brute force method where we keep a dict the size of the list
Then we check it for the value we need. If the key is not in the dict,
our and statement will short circuit and return False |
124 | def listunspent(self, address: str) -> list:
try:
return cast(dict, self.ext_fetch( + address))[]
except KeyError:
raise InsufficientFunds() | Returns unspent transactions for given address. |
125 | def get_next_event(event, now):
year = now.year
month = now.month
day = now.day
e_day = event[0].l_start_date.day
e_end_day = event[0].l_end_date.day
good_today = True if event[0].l_start_date.time() >= now.time() else False
if event[0].starts_same_year_month_as(year, month) and \
... | Returns the next occurrence of a given event, relative to 'now'.
The 'event' arg should be an iterable containing one element,
namely the event we'd like to find the occurrence of.
The reason for this is b/c the get_count() function of CountHandler,
which this func makes use of, expects an iterable.
... |
126 | def _set_active_policy(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=active_policy.active_policy, is_container=, presence=False, yang_name="active-policy", rest_name="active-policy", parent=self, path_helper=self._path_helper, extmethods=self._extme... | Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling... |
127 | def ellipse(self, x,y,w,h,style=):
"Draw a ellipse"
if(style==):
op=
elif(style== or style==):
op=
else:
op=
cx = x + w/2.0
cy = y + h/2.0
rx = w/2.0
ry = h/2.0
lx = 4.0/3.0*(math.sqrt(2)-1)*rx
ly = 4.0... | Draw a ellipse |
128 | def _construct_from_json(self, rec):
self.delete()
for required_key in [, ]:
setattr(self, required_key, rec[required_key])
for job_json in rec.get(, []):
self._add_job_from_spec(job_json)
self.commit(cascade=True) | Construct this Dagobah instance from a JSON document. |
129 | def _sync_string_to(bin_or_str, string):
if isinstance(string, type(bin_or_str)):
return string
elif isinstance(string, binary_type):
return string.decode(DEFAULT_ENCODING)
else:
return string.encode(DEFAULT_ENCODING) | Python 3 compliance: ensure two strings are the same type (unicode or binary) |
130 | def get_grades(self):
return GradeList(
self._my_map[],
runtime=self._runtime,
proxy=self._proxy) | Gets the grades in this system ranked from highest to lowest.
return: (osid.grading.GradeList) - the list of grades
raise: IllegalState - ``is_based_on_grades()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented... |
131 | def _do_search(self):
if self._results_cache is None:
response = self.raw()
results = self.to_python(response.get(, {}).get(, []))
self._results_cache = DictSearchResults(
self.type, response, results, None)
return self._results_cache | Perform the mlt call, then convert that raw format into a
SearchResults instance and return it. |
132 | def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
raise NotImplementedError | Add an entry to the system crontab. |
133 | def get_tc_api(self, host, headers=None, cert=None, logger=None):
if logger is None and self.logger:
logger = self.logger
return Api(host, headers, cert, logger) | Gets HttpApi wrapped into a neat little package that raises TestStepFail
if expected status code is not returned by the server.
Default setting for expected status code is 200. Set expected to None when calling methods
to ignore the expected status code parameter or
set raiseException = ... |
134 | def torecarray(*args, **kwargs):
import numpy as np
return toarray(*args, **kwargs).view(np.recarray) | Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. |
135 | def shader_substring(body, stack_frame=1):
line_count = len(body.splitlines(True))
line_number = inspect.stack()[stack_frame][2] + 1 - line_count
return % (line_number, textwrap.dedent(body)) | Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in two ways:
1) Insert #line number declaration
2) un-indents
The line number information can help debug glsl compile errors.
The unindenting allows you to type the s... |
136 | def schedule_task(self, task_id):
task = self.registry.get(task_id)
job_args = self._build_job_arguments(task)
archiving_cfg = task.archiving_cfg
fetch_from_archive = False if not archiving_cfg else archiving_cfg.fetch_from_archive
queue = Q_ARCHIVE_JOBS if f... | Schedule a task.
:param task_id: identifier of the task to schedule
:raises NotFoundError: raised when the requested task is not
found in the registry |
137 | def parse_row(self, row, row_index, cell_mode=CellMode.cooked):
return [self.parse_cell(cell, (col_index, row_index), cell_mode) \
for col_index, cell in enumerate(row)] | Parse a row according to the given cell_mode. |
138 | def timeseries(X, **kwargs):
pl.figure(figsize=(2*rcParams[][0], rcParams[][1]),
subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
timeseries_subplot(X, **kwargs) | Plot X. See timeseries_subplot. |
139 | def parse_filename_meta(filename):
common_pattern = "_%s_%s" % (
"(?P<product>[a-zA-Z]{3}[a-zA-Z]?-[a-zA-Z0-9]{2}[a-zA-Z0-9]?-[a-zA-Z0-9]{4}[a-zA-Z0-9]?)",
"(?P<platform>[gG][1-9]{2})"
)
patterns = {
"l2_pattern": re.compile("%s_s(?P<... | taken from suvi code by vhsu
Parse the metadata from a product filename, either L1b or l2.
- file start
- file end
- platform
- product
:param filename: string filename of product
:return: (start datetime, end datetime, platform) |
140 | def _pi_id(self):
pi_rev_code = self._pi_rev_code()
if pi_rev_code:
for model, codes in _PI_REV_CODES.items():
if pi_rev_code in codes:
return model
return None | Try to detect id of a Raspberry Pi. |
141 | def format_seq(self, outstream=None, linewidth=70):
if linewidth == 0 or len(self.seq) <= linewidth:
if outstream is None:
return self.seq
else:
print(self.seq, file=outstream)
return
i = 0
seq =
while i <... | Print a sequence in a readable format.
:param outstream: if `None`, formatted sequence is returned as a
string; otherwise, it is treated as a file-like
object and the formatted sequence is printed to the
outstream
:param line... |
142 | def html_visit_inheritance_diagram(self, node):
graph = node[]
graph_hash = get_graph_hash(node)
name = % graph_hash
graphviz_output_format = self.builder.env.config.graphviz_output_format.upper()
current_filename = self.builder.current_docname + self.builder.out_suffix
urls = ... | Output the graph for HTML. This will insert a PNG with clickable
image map. |
143 | def remove_udp_port(self, port):
if port in self._used_udp_ports:
self._used_udp_ports.remove(port) | Removes an associated UDP port number from this project.
:param port: UDP port number |
144 | def timeout_selecting(self):
logger.debug(,
self.current_state)
if len(self.offers) >= MAX_OFFERS_COLLECTED:
logger.debug(
)
raise self.REQUESTING()
if self.discover_attempts >= MAX_ATTEMPTS_DISCOVER:
lo... | Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`. |
145 | def delete(self, docids):
self.check_session()
result = self.session.delete(docids)
if self.autosession:
self.commit()
return result | Delete documents from the current session. |
146 | def _build_dictionary(self, results):
foreign = self._foreign_key
dictionary = {}
for result in results:
key = getattr(result.pivot, foreign)
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(result)
ret... | Build model dictionary keyed by the relation's foreign key.
:param results: The results
:type results: Collection
:rtype: dict |
147 | def normalize_surfs(in_file, transform_file, newpath=None):
img = nb.load(in_file)
transform = load_transform(transform_file)
pointset = img.get_arrays_from_intent()[0]
coords = pointset.data.T
c_ras_keys = (, , )
ras = np.array([[float(pointset.metadata[key])]
for key ... | Re-center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces, add MidThickness metadata
Coordinate update based on:
https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91
and
https://github.com/Washington-Univ... |
148 | def calculate_average_scores_on_graph(
graph: BELGraph,
key: Optional[str] = None,
tag: Optional[str] = None,
default_score: Optional[float] = None,
runs: Optional[int] = None,
use_tqdm: bool = False,
):
subgraphs = generate_bioprocess_mechanisms(graph, key=key)
... | Calculate the scores over all biological processes in the sub-graph.
As an implementation, it simply computes the sub-graphs then calls :func:`calculate_average_scores_on_subgraphs` as
described in that function's documentation.
:param graph: A BEL graph with heats already on the nodes
:param key: The... |
149 | def add_suffix(fullname, suffix):
name, ext = os.path.splitext(fullname)
return name + + suffix + ext | Add suffix to a full file name |
150 | def get_num_processes():
cpu_count = multiprocessing.cpu_count()
if config.NUMBER_OF_CORES == 0:
raise ValueError(
)
if config.NUMBER_OF_CORES > cpu_count:
log.info(,
config.NUMBER_OF_CORES, cpu_count)
return cpu_count
if config.NUMBER_OF_CORE... | Return the number of processes to use in parallel. |
151 | def destination(self, point, bearing, distance=None):
point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if distance is None:
distance = self
if isi... | TODO docs. |
152 | def eintr_retry(exc_type, f, *args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except exc_type as exc:
if exc.errno != EINTR:
raise
else:
break | Calls a function. If an error of the given exception type with
interrupted system call (EINTR) occurs calls the function again. |
153 | def _get_bonds(self, mol):
num_atoms = len(mol)
if self.ignore_ionic_bond:
covalent_atoms = [i for i in range(num_atoms) if mol.species[i].symbol not in self.ionic_element_list]
else:
covalent_atoms = list(range(num_atoms))
all_pairs = list(itert... | Find all the bond in a molcule
Args:
mol: the molecule. pymatgen Molecule object
Returns:
List of tuple. Each tuple correspond to a bond represented by the
id of the two end atoms. |
154 | def now(self, when=None):
if when is None:
when = _TaskManager().get_time()
tup = time.localtime(when)
self.value = (tup[0]-1900, tup[1], tup[2], tup[6] + 1)
return self | Set the current value to the correct tuple based on the seconds
since the epoch. If 'when' is not provided, get the current time
from the task manager. |
155 | def profile(request, status=200):
if request.method == :
if request.GET.get("username", False):
try:
user_profile = User.objects.get(username=request.GET.get("username"),
userprofile__public=True).userprofile
except... | Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (only for users with public profile)
stats... |
156 | def visit(self, node):
for pattern, replace in know_pattern:
check = Check(node, dict())
if check.visit(pattern):
node = PlaceholderReplace(check.placeholders).visit(replace())
self.update = True
return super(PatternTransform, self).visit(... | Try to replace if node match the given pattern or keep going. |
157 | def tf_initialize(self, x_init, b):
if x_init is None:
x_init = [tf.zeros(shape=util.shape(t)) for t in b]
initial_args = super(ConjugateGradient, self).tf_initialize(x_init)
conjugate = residual = [t - fx for t, fx in zip(b, self.fn_x(x_init... | Initialization step preparing the arguments for the first iteration of the loop body:
$x_0, 0, p_0, r_0, r_0^2$.
Args:
x_init: Initial solution guess $x_0$, zero vector if None.
b: The right-hand side $b$ of the system of linear equations.
Returns:
Initial... |
158 | def gen_locale(locale, **kwargs):
**en_IE.UTF-8 UTF-8
on_debian = __grains__.get() ==
on_ubuntu = __grains__.get() ==
on_gentoo = __grains__.get() ==
on_suse = __grains__.get() ==
on_solaris = __grains__.get() ==
if on_solaris:
return locale in __salt__[]()
locale_info =... | Generate a locale. Options:
.. versionadded:: 2014.7.0
:param locale: Any locale listed in /usr/share/i18n/locales or
/usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions,
which require the charmap to be specified as part of the locale
when generating it.
verbose
... |
159 | def _set_collector(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("collector_name",collector.collector, yang_name="collector", rest_name="collector", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_key... | Setter method for collector, mapped from YANG variable /telemetry/collector (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_collector() di... |
160 | def _get_dvs_infrastructure_traffic_resources(dvs_name,
dvs_infra_traffic_ress):
log.trace(%s\
, dvs_name)
res_dicts = []
for res in dvs_infra_traffic_ress:
res_dict = {: res.key,
: res.allocationInfo.limit,
... | Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic resources |
161 | def get_user_groups(name, sid=False):
if name == :
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_grou... | Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids |
162 | def parse_text(document, container, element):
"Parse text element."
txt = None
alternate = element.find(_name())
if alternate is not None:
parse_alternate(document, container, alternate)
br = element.find(_name())
if br is not None:
if _name() in br.attrib:
_type... | Parse text element. |
163 | def response(self, msgid, error, result):
if error:
self.requests[msgid].errback(Exception(str(error)))
else:
self.requests[msgid].callback(result)
del self.requests[msgid] | Handle a results message given to the proxy by the protocol object. |
164 | def load(self, args):
self._queue.append(tc.CMD_LOAD)
self._string += struct.pack("!BiB", 0, 1 + 4 + 1 + 1 + 4 + sum(map(len, args)) + 4 * len(args), tc.CMD_LOAD)
self._packStringList(args)
self._sendExact() | Load a simulation from the given arguments. |
165 | def reverseCommit(self):
col = self.cursorPos[1]
for ii, text in enumerate(self.insertedText):
line = ii + self.cursorPos[0]
self.qteWidget.setSelection(line, col, line, col + len(text))
self.baseClass.removeSelec... | Re-insert the previously deleted line. |
166 | def call_binop(self, context, operator, left, right):
return self.binop_table[operator](left, right) | For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6 |
167 | def consume_message(self, header, message):
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
if header:
logmessage["header"] = (
json.dumps(header, indent=2) + "\n" + "----------------... | Consume a message |
168 | def start_adc(self, channel, gain=1, data_rate=None):
assert 0 <= channel <= 3,
return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_CONTINUOUS) | Start continuous ADC conversions on the specified channel (0-3). Will
return an initial conversion result, then call the get_last_result()
function to read the most recent conversion result. Call stop_adc() to
stop conversions. |
169 | def parse(self, fp, headersonly=False):
fp = TextIOWrapper(fp, encoding=, errors=)
with fp:
return self.parser.parse(fp, headersonly) | Create a message structure from the data in a binary file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the en... |
170 | def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None,
success:bool=None, result_code:str=None, properties:Dict[str, object]=None,
measurements:Dict[str, object]=None, dependency_id:str=None):
raise NotImplemen... | Sends a single dependency telemetry that was captured for the application.
:param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.
:param data: the command initiated by this dependency call. Examples are S... |
171 | def _check_infinite_flows(self, steps, flows=None):
if flows is None:
flows = []
for step in steps.values():
if "flow" in step:
flow = step["flow"]
if flow == "None":
continue
if flow in flows:
... | Recursively loop through the flow_config and check if there are any cycles.
:param steps: Set of step definitions to loop through
:param flows: Flows already visited.
:return: None |
172 | def _OpenPathSpec(self, path_specification, ascii_codepage=):
if not path_specification:
return None
file_entry = self._file_system.GetFileEntryByPathSpec(path_specification)
if file_entry is None:
return None
file_object = file_entry.GetFileObject()
if file_object is None:
... | Opens the Windows Registry file specified by the path specification.
Args:
path_specification (dfvfs.PathSpec): path specification.
ascii_codepage (Optional[str]): ASCII string codepage.
Returns:
WinRegistryFile: Windows Registry file or None. |
173 | def create_widget(self):
d = self.declaration
self.widget = CheckBox(self.get_context(), None,
d.style or "@attr/checkboxStyle") | Create the underlying widget. |
174 | def get_licenses(self):
url_parameters = dict()
return github.PaginatedList.PaginatedList(
github.License.License,
self.__requester,
"/licenses",
url_parameters
) | :calls: `GET /licenses <https://developer.github.com/v3/licenses/#list-all-licenses>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.License.License` |
175 | def get_object(self, item):
if isinstance(item, six.string_types):
item = self.object_manager.get(item)
return item | Returns a StorageObject matching the specified item. If no such object
exists, a NotFound exception is raised. If 'item' is not a string, that
item is returned unchanged. |
176 | def _readconfig():
config = ConfigParser.SafeConfigParser()
try:
found = config.read(littlechef.CONFIGFILE)
except ConfigParser.ParsingError as e:
abort(str(e))
if not len(found):
try:
found = config.read([, ])
except ConfigParser.ParsingError as e:
... | Configures environment variables |
177 | def servicegroup_server_exists(sg_name, s_name, s_port=None, **connection_args):
*serviceGroupNameserverNameserverPort
return _servicegroup_get_server(sg_name, s_name, s_port, **connection_args) is not None | Check if a server:port combination is a member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort' |
178 | def compute_effsize(x, y, paired=False, eftype=):
if not _check_eftype(eftype):
err = "Could not interpret input ".format(eftype)
raise ValueError(err)
x = np.asarray(x)
y = np.asarray(y)
if x.size != y.size and paired:
warnings.warn("x and y have unequal sizes. Switc... | Calculate effect size between two set of observations.
Parameters
----------
x : np.array or list
First set of observations.
y : np.array or list
Second set of observations.
paired : boolean
If True, uses Cohen d-avg formula to correct for repeated measurements
(Cumm... |
179 | def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]:
rval = []
if self._members:
for member in self._members:
rval += member.members_entries(all_are_optional)
elif self._choices:
for choice in self._choices:
... | Return an ordered list of elements for the _members section
:param all_are_optional: True means we're in a choice situation so everything is optional
:return: |
180 | def p_expression_And(self, p):
p[0] = And(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression AND expression |
181 | def func_call_as_str(name, *args, **kwds):
return .format(
name,
.join(itertools.chain(
map(.format, args),
map(.format, sorted(kwds.items()))))) | Return arguments and keyword arguments as formatted string
>>> func_call_as_str('f', 1, 2, a=1)
'f(1, 2, a=1)' |
182 | def copy(self, src, dst, other_system=None):
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_oss_error():
bucket = self._get_bucket(copy_destination)
bucket.copy_object(
source_bucket_name=copy... | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused. |
183 | def to_int(self, number, default=0):
try:
return int(number)
except (KeyError, ValueError):
return self.to_int(default, 0) | Returns an integer |
184 | def elect(self, candidate_aggregates, candidate_id):
assert(candidate_id not in self.candidates_elected)
elected_no = len(self.candidates_elected) + 1
self.candidates_elected[candidate_id] = True
transfer_value = 0
excess_votes = paper_count = None
if... | Elect a candidate, updating internal state to track this.
Calculate the paper count to be transferred on to other candidates,
and if required schedule a distribution fo papers. |
185 | def LoadExclusions(self, snps):
snp_names = []
if len(snps) == 1 and os.path.isfile(snps[0]):
snp_names = open(snps).read().strip().split()
else:
snp_names = snps
for snp in snp_names:
if len(snp.strip()) > 0:
self.ignored_rs.... | Load locus exclusions.
:param snps: Can either be a list of rsids or a file containing rsids.
:return: None
If snps is a file, the file must only contain RSIDs separated
by whitespace (tabs, spaces and return characters). |
186 | def _prepare_calls(result_file, out_dir, data):
sample = dd.get_sample_name(data)
out_file = os.path.join(out_dir, "%s-optitype.csv" % (sample))
if not utils.file_uptodate(out_file, result_file):
hla_truth = bwakit.get_hla_truthset(data)
with file_transaction(data, out_file) as tx_out_f... | Write summary file of results of HLA typing by allele. |
187 | def from_dict(cls, operation, client, **caller_metadata):
operation_pb = json_format.ParseDict(operation, operations_pb2.Operation())
result = cls(operation_pb.name, client, **caller_metadata)
result._update_state(operation_pb)
result._from_grpc = False
return result | Factory: construct an instance from a dictionary.
:type operation: dict
:param operation: Operation as a JSON object.
:type client: :class:`~google.cloud.client.Client`
:param client: The client used to poll for the status of the operation.
:type caller_metadata: dict
... |
188 | def _query_entities(self, table_name, filter=None, select=None, max_results=None,
marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
property_resolver=None, timeout=None, _context=None):
_validate_not_none(, table_name)
_validate_not_no... | Returns a list of entities under the specified table. Makes a single list
request to the service. Used internally by the query_entities method.
:param str table_name:
The name of the table to query.
:param str filter:
Returns only entities that satisfy the specified fil... |
189 | def pretty_str(self, indent=0):
indent = * indent
if self.value is not None:
return .format(indent, self.name, pretty_str(self.value))
return indent + self.name | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. |
190 | def cmd_host(verbose):
if verbose:
logging.basicConfig(level=logging.INFO, format=)
print("Gather information about the host...", file=sys.stderr)
result = gather_details()
if result:
print(json.dumps(result, indent=4))
else:
print("[X] Unable to gather information... | Collect information about the host where habu is running.
Example:
\b
$ habu.host
{
"kernel": [
"Linux",
"demo123",
"5.0.6-200.fc29.x86_64",
"#1 SMP Wed Apr 3 15:09:51 UTC 2019",
"x86_64",
"x86_64"
],
"dist... |
191 | def current_rev_reg_id(base_dir: str, cd_id: str) -> str:
tags = [int(rev_reg_id2tag(basename(f))) for f in Tails.links(base_dir)
if cd_id in basename(f)]
if not tags:
raise AbsentTails(.format(cd_id))
return rev_reg_id(cd_id, str(max(tags))) | Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:param base_dir: base directory for tails files, thereafter split by cred def id
... |
192 | def merge_configs(config: Dict[str, Any], default_config: Dict[str, Any]) -> Dict[str, Any]:
for key in default_config:
if key in config:
if isinstance(config[key], dict) and isinstance(default_config[key], dict):
merge_configs(config[key], default_config[key])
else:... | Merges a `default` config with DAG config. Used to set default values
for a group of DAGs.
:param config: config to merge in default values
:type config: Dict[str, Any]
:param default_config: config to merge default values from
:type default_config: Dict[str, Any]
:returns: dict with merged co... |
193 | def userpass(self, dir="ppcoin"):
source = os.path.expanduser("~/.{0}/{0}.conf").format(dir)
dest = open(source, "r")
with dest as conf:
for line in conf:
if line.startswith("rpcuser"):
username = line.split("=")[1].strip()
... | Reads config file for username/password |
194 | def get(self, mail):
users = (v for v in self.list() if v.get() == mail)
for i in users:
self.log.debug(i)
return i
return None | Get one document store into LinShare. |
195 | def t_NATIVEPHP(t):
r
lineNoInc(t)
t.value = t.value[6:].lstrip()
pos2 = t.value.rfind()
t.value = t.value[0:pos2].rstrip()
return t | r'<\?php((?!<\?php)[\s\S])*\?>[ \t]*(?=\n) |
196 | def cos_zen(utc_time, lon, lat):
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
r_a, dec = sun_ra_dec(utc_time)
h__ = _local_hour_angle(utc_time, lon, r_a)
return (np.sin(lat) * np.sin(dec) + np.cos(lat) * np.cos(dec) * np.cos(h__)) | Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*.
utc_time: datetime.datetime instance of the UTC time
lon and lat in degrees. |
197 | def __collect_interfaces_return(interfaces):
acc = []
for (interfaceName, interfaceData) in interfaces.items():
signalValues = interfaceData.get("signals", {})
for (signalName, signalValue) in signalValues.items():
pinName = "{0}.{1}".format(interfaceName... | Collect new style (44.1+) return values to old-style kv-list |
198 | def find_satisfied_condition(conditions, ps):
assert is_iterable_typed(conditions, property_set.PropertySet)
assert isinstance(ps, property_set.PropertySet)
for condition in conditions:
found_all = True
for i in condition.all():
if i.value:
found = i.value... | Returns the first element of 'property-sets' which is a subset of
'properties', or an empty list if no such element exists. |
199 | def update_model_cache(table_name):
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex)
model_cache_backend.share_model_cache_info(model_cache_info) | Updates model cache by generating a new key for the model |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.