text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_latitude(self, ip):
''' Get latitude '''
rec = self.get_all(ip)
return rec and rec.latitude | 0.01626 |
def _link_user(self, userid):
"""Link an existing user to the current Contact
"""
# check if we have a selected user from the search-list
if userid:
try:
self.context.setUser(userid)
self.add_status_message(
_("User linked t... | 0.003656 |
def convert_widgets(self):
"""
During form initialization, some widgets have to be replaced by a counterpart suitable to
be rendered the AngularJS way.
"""
for field in self.base_fields.values():
try:
new_widget = field.get_converted_widget()
... | 0.006508 |
def config_generator(search_space, max_search, rng, shuffle=True):
"""Generates config dicts from the given search space
Args:
search_space: (dict) A dictionary of parameters to search over.
See note below for more details.
max_search: (int) The maximum number of... | 0.001181 |
def status_bar(python_input):
"""
Create the `Layout` for the status bar.
"""
TB = 'class:status-toolbar'
@if_mousedown
def toggle_paste_mode(mouse_event):
python_input.paste_mode = not python_input.paste_mode
@if_mousedown
def enter_history(mouse_event):
python_input.e... | 0.00398 |
def _shape(self):
"""Return the tensor shape of the matrix operator"""
return tuple(reversed(self.output_dims())) + tuple(
reversed(self.input_dims())) | 0.011173 |
def dispatch(self,request,*args,**kwargs):
'''
Check that a valid Invoice ID has been passed in session data,
and that said invoice is marked as paid.
'''
paymentSession = request.session.get(INVOICE_VALIDATION_STR, {})
self.invoiceID = paymentSession.get('invoiceID')
... | 0.014192 |
def rename_feature(self, mapobject_type_name, name, new_name):
'''Renames a feature.
Parameters
----------
mapobject_type_name: str
name of the segmented objects type
name: str
name of the feature that should be renamed
new_name: str
n... | 0.001842 |
def passwd_check(hashed_passphrase, passphrase):
"""Verify that a given passphrase matches its hashed version.
Parameters
----------
hashed_passphrase : str
Hashed password, in the format returned by `passwd`.
passphrase : str
Passphrase to validate.
Returns
-------
val... | 0.002595 |
def start(self):
"""Starts the worker threads"""
if self.working:
return
self.working = True
for i in range(self.num_workers):
w = threading.Thread(
name="Worker Thread #{i}".format(i=i),
target=self._worker,
)
... | 0.005013 |
def _register(self, assignment): # type: (Assignment) -> None
"""
Registers an Assignment in _positive or _negative.
"""
name = assignment.dependency.name
old_positive = self._positive.get(name)
if old_positive is not None:
self._positive[name] = old_positive... | 0.003096 |
def __telnet_event_listener(self, ip, callback):
"""creates a telnet connection to the lightpad"""
tn = telnetlib.Telnet(ip, 2708)
self._last_event = ""
self._telnet_running = True
while self._telnet_running:
try:
raw_string = tn.read_until(b'.\n', 5)... | 0.003922 |
def classify_intersection9(s, curve1, curve2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
surface1 = bezier.Surface.from_nodes(
np.asfortranarray(
[
[0.0, 20.0, 40.0, 10.0, 30.0, 20.0],
[0.0, 40... | 0.000602 |
def parse(self, fileobj, name_hint='', parser=None):
"""Fill from a file-like object."""
self.current_block = None # Reset current block
parser = parser or Parser()
for line in parser.parse(fileobj, name_hint=name_hint):
self.handle_line(line) | 0.006944 |
def _find_coeffs(orig_pts:Points, targ_pts:Points)->Tensor:
"Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/)."
matrix = []
#The equations we'll need to solve.
for p1, p2 in zip(targ_pts, orig_pts):
matrix.append([p1[0], p1[1], 1,... | 0.015203 |
def _save_results(self, output_dir, label, results, ngrams, type_label):
"""Saves `results` filtered by `label` and `ngram` to `output_dir`.
:param output_dir: directory to save results to
:type output_dir: `str`
:param label: catalogue label of results, used in saved filename
:... | 0.002252 |
def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the producer of a named rate.
This is a convenience wrapper around ``register_value_producer`` that makes sure
rate data is appropriately scaled to the size of the ... | 0.008782 |
def syscall(self, state, allow_unsupported=True):
"""
Given a state, return the procedure corresponding to the current syscall.
This procedure will have .syscall_number, .display_name, and .addr set.
:param state: The state to get the syscall number from
:param all... | 0.00604 |
def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True... | 0.00188 |
def recvProtocolVersion(self, data):
"""
Read handshake packet
If protocol receive from client is unknown
try best version of protocol version (ProtocolVersion.RFB003008)
@param data: Stream
"""
self.readProtocolVersion(data)
if self._version.value == Pro... | 0.011792 |
def data_log_encode(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6):
'''
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
fl_3 ... | 0.004658 |
def parse_params(self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
... | 0.004112 |
def add_classdiff_optgroup(parser):
"""
option group specific to class checking
"""
g = parser.add_argument_group("Class Checking Options")
g.add_argument("--ignore-version-up", action="store_true",
default=False)
g.add_argument("--ignore-version-down", action="store_true", ... | 0.000714 |
def get_by_wiki(citiao):
'''
Get the wiki record by title.
'''
q_res = TabWiki.select().where(TabWiki.title == citiao)
the_count = q_res.count()
if the_count == 0 or the_count > 1:
return None
else:
MWiki.update_view_count(citiao)
... | 0.005865 |
def get_results_file_name(boundaries_id, labels_id, config,
annotator_id):
"""Based on the config and the dataset, get the file name to store the
results."""
utils.ensure_dir(msaf.config.results_dir)
file_name = os.path.join(msaf.config.results_dir, "results")
file_name += ... | 0.001272 |
def yn2Kn2Der(nu, y, n=0, tol=5e-4, nterms=1, nu_step=0.001):
r"""Computes the function :math:`y^{\nu/2} K_{\nu}(y^{1/2})` and its derivatives.
Care has been taken to handle the conditions at :math:`y=0`.
For `n=0`, uses a direct evaluation of the expression, replacing points
where `y=0` with ... | 0.004745 |
def percent_point(self, U):
"""Given a cumulated distribution value, returns a value in original space.
Arguments:
U: `np.ndarray` of shape (n, 1) and values in [0,1]
Returns:
`np.ndarray`: Estimated values in original space.
"""
self.check_fit()
... | 0.008108 |
def is_ready(self):
"""Is thread & ioloop ready.
:returns bool:
"""
if not self._thread:
return False
if not self._ready.is_set():
return False
return True | 0.008696 |
def _col_widths2xls(self, worksheets):
"""Writes col_widths to xls file
Format: <col>\t<tab>\t<value>\n
"""
xls_max_cols, xls_max_tabs = self.xls_max_cols, self.xls_max_tabs
dict_grid = self.code_array.dict_grid
for col, tab in dict_grid.col_widths:
if co... | 0.003676 |
def incoming_copying_manipulators(self):
"""**DEPRECATED**: All incoming SON copying manipulators.
.. versionchanged:: 3.5
Deprecated.
.. versionadded:: 2.0
"""
warnings.warn("Database.incoming_copying_manipulators() is deprecated",
DeprecationWa... | 0.004338 |
def run(cls, command, cwd=".", **kwargs):
"""
Make a subprocess call, collect its output and returncode.
Returns CommandResult instance as ValueObject.
"""
assert isinstance(command, six.string_types)
command_result = CommandResult()
command_result.command = comma... | 0.005181 |
def load_keys(key_file, origin_passphrase, stash, passphrase, backend):
"""Load all keys from an exported key file to the stash
`KEY_FILE` is the exported stash file to load keys from
"""
stash = _get_stash(backend, stash, passphrase)
click.echo('Importing all keys from {0}...'.format(key_file))
... | 0.002463 |
def unregister_editorstack(self, editorstack):
"""Removing editorstack only if it's not the last remaining"""
self.remove_last_focus_editorstack(editorstack)
if len(self.editorstacks) > 1:
index = self.editorstacks.index(editorstack)
self.editorstacks.pop(index)
... | 0.004706 |
def p_bound(p):
""" bound : expr
"""
p[0] = make_bound(make_number(OPTIONS.array_base.value,
lineno=p.lineno(1)), p[1], p.lexer.lineno) | 0.005525 |
def annual_heating_design_day_990(self):
"""A design day object representing the annual 99.0% heating design day."""
if bool(self._winter_des_day_dict) is True:
return DesignDay.from_ashrae_dict_heating(
self._winter_des_day_dict, self.location, True,
self._st... | 0.007979 |
def write_single_coil(self, bit_addr, bit_value):
"""Modbus function WRITE_SINGLE_COIL (0x05)
:param bit_addr: bit address (0 to 65535)
:type bit_addr: int
:param bit_value: bit value to write
:type bit_value: bool
:returns: True if write ok or None if fail
:rtyp... | 0.002793 |
def _internal_add(self, pattern: Pattern, label, renaming) -> int:
"""Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
... | 0.007201 |
def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | 0.015152 |
def partition_by_vid(self, ref):
"""A much faster way to get partitions, by vid only"""
from ambry.orm import Partition
p = self.session.query(Partition).filter(Partition.vid == str(ref)).first()
if p:
return self.wrap_partition(p)
else:
return None | 0.009554 |
def add_node(self, node_name, dataframe=False):
""" Add a single node to the network. """
if node_name is None:
return None
return self.add_nodes([node_name], dataframe=dataframe) | 0.009302 |
def _polarBreaks(self):
"""Determine where breaks in a polar orbiting satellite orbit occur.
Looks for sign changes in latitude (magnetic or geographic) as well as
breaks in UT.
"""
if self.orbit_index is None:
raise ValueError('Orbit properties must be defined at ... | 0.002424 |
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={},
style={}, options={}, **kwargs):
"""
Get Chartjs html
"""
try:
xdata = list(self.df[xcol])
except Exception as e:
self.err(e, self._get_chartjs_chart,
... | 0.002408 |
def update_from_devices(self):
"""Retrieve a list of &devices and values."""
# _LOGGER.warning("update from devices")
try:
rest = requests.get(URL_DEVICES.format(self._url))
if rest.status_code != 200:
_LOGGER.error("Devices returned %s", rest.status_code)... | 0.003091 |
def DbGetDeviceAliasList(self, argin):
""" Get device alias name with a specific filter
:param argin: The filter
:type: tango.DevString
:return: Device alias list
:rtype: tango.DevVarStringArray """
self._log.debug("In DbGetDeviceAliasList()")
if not argin:
... | 0.004454 |
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} ... | 0.003676 |
def step_impl13(context, runs):
"""Check called apps / files.
:param runs: expected number of records.
:param context: test context.
"""
executor_ = context.fuzz_executor
stats = executor_.stats
count = stats.cumulated_counts()
assert count == runs, "VERIFY: Number of recorded runs."
... | 0.002358 |
def envCheckFilter(self, name, attr):
"""Check if a specific graph attribute is enabled or disabled through
the use of a filter based on include_<name> and exclude_<name>
environment variables.
@param name: Name of the Filter.
@param attr: Name of the Attribute.
... | 0.012411 |
def mass_3d(self, r, kwargs, bool_list=None):
"""
computes the mass within a 3d sphere of radius r
:param r: radius (in angular units)
:param kwargs: list of keyword arguments of lens model parameters matching the lens model classes
:param bool_list: list of bools that are part ... | 0.008677 |
def delete_namespaced_network_policy(self, name, namespace, **kwargs):
"""
delete a NetworkPolicy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_network_policy(name, name... | 0.003837 |
def draw_pegasus(G, crosses=False, **kwargs):
"""Draws graph G in a Pegasus topology.
If `linear_biases` and/or `quadratic_biases` are provided, these
are visualized on the plot.
Parameters
----------
G : NetworkX graph
Should be a Pegasus graph or a subgraph of a Pegasus graph,
... | 0.000593 |
def _get_range_timestamp_key(self, start: Key, end: Key,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a TIMESTAMP key.
"""
r... | 0.011561 |
def multi_token_match(stream_item, aligner_data):
'''
iterate through tokens looking for near-exact matches to strings
in si.ratings...mentions
'''
tagger_id = _get_tagger_id(stream_item, aligner_data)
sentences = stream_item.body.sentences.get(tagger_id)
if not sentences:
return... | 0.005376 |
def write_as_json(blob, dest, indent=0, sort_keys=True):
"""Writes `blob` as JSON to the filepath `dest` or the filestream `dest` (if it isn't a string)
uses utf-8 encoding if the filepath is given (does not change the encoding if dest is already open).
"""
opened_out = False
if is_str_type(dest):
... | 0.00491 |
def process_stencil(cookbook, cookbook_name, template_pack,
force_argument, stencil_set, stencil, written_files):
"""Process the stencil requested, writing any missing files as needed.
The stencil named 'stencilset_name' should be one of
templatepack's stencils.
"""
# force can ... | 0.000412 |
def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff | 0.008772 |
def desired_destination(self, network, edge):
"""Returns the agents next destination given their current
location on the network.
An ``Agent`` chooses one of the out edges at random. The
probability that the ``Agent`` will travel along a specific
edge is specified in the :class:... | 0.001244 |
def _find_unprocessed(config):
"""Find any finished directories that have not been processed.
"""
reported = _read_reported(config["msg_db"])
for dname in _get_directories(config):
if os.path.isdir(dname) and dname not in reported:
if _is_finished_dumping(dname):
yiel... | 0.003058 |
def load_plugins(config, plugin_kwargs):
"""
Discover and instantiate plugins.
Args:
config (dict): loaded configuration for the Gordon service.
plugin_kwargs (dict): keyword arguments to give to plugins
during instantiation.
Returns:
Tuple of 3 lists: list of names ... | 0.000825 |
def cufflinks(args):
"""
%prog cufflinks folder reference
Run cufflinks on a folder containing tophat results.
"""
p = OptionParser(cufflinks.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) !=... | 0.000683 |
def _process_content_body(self, channel, payload):
"""Process Content Body frames"""
partial = self.partial_messages[channel]
partial.add_payload(payload)
if partial.complete:
#
# Stick the message in the queue and go back to
# waiting for method frame... | 0.00365 |
def get_report_interpreted(year, report_type):
"""Download, exract, and interpret a CO-TRACER report.
Generate a URL for the given report, download the corresponding archive,
extract the CSV report, and interpret it using TRACER-specific logic.
@param year: The year for which data should be downloaded... | 0.000975 |
def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in client.execute_paged_query('list', {}):
for project in page.get('projects', []):
if project['lifecycleState'] ... | 0.002516 |
def frustum(left, right, bottom, top, znear, zfar):
"""Create view frustum matrix."""
assert right != left
assert bottom != top
assert znear != zfar
M = np.zeros((4, 4), dtype=np.float32)
M[0, 0] = +2.0 * znear / (right - left)
M[2, 0] = (right + left) / (right - left)
M[1, 1] = +2.0 * znear / (top - b... | 0.028455 |
def parse(ifp, pb_cls, **kwargs):
"""Parse a stream.
Args:
ifp (string or file-like object): input stream.
pb_cls (protobuf.message.Message.__class__): The class object of
the protobuf message type encoded in the stream.
"""
mode = 'rb'
if isinstance(ifp, str):
i... | 0.001757 |
def _get_xfstyle(self, worksheets, key):
"""Gets XFStyle for cell key"""
row, col, tab = key
dict_grid = self.code_array.dict_grid
dict_grid.cell_attributes._update_table_cache()
pys_style = dict_grid.cell_attributes[key]
pys_style_above = dict_grid.cell_attributes[row ... | 0.001767 |
def run(self, endpoint, data=None, headers=None, extra_options=None):
"""
Performs the request
:param endpoint: the endpoint to be called i.e. resource/v1/query?
:type endpoint: str
:param data: payload to be uploaded or request parameters
:type data: dict
:param... | 0.002092 |
def delete_post(apikey, post_id, username, password, publish):
"""
blogger.deletePost(api_key, post_id, username, password, 'publish')
=> boolean
"""
user = authenticate(username, password, 'zinnia.delete_entry')
entry = Entry.objects.get(id=post_id, authors=user)
entry.delete()
return T... | 0.003096 |
def _add_to_ngcorpus(self, corpus, words, count):
"""Build up a corpus entry recursively.
Parameters
----------
corpus : Corpus
The corpus
words : [str]
Words to add to the corpus
count : int
Count of words
"""
if word... | 0.003724 |
def _find_lib_path():
"""Find mxnet library."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so')
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path):
lib_path... | 0.006061 |
def synthesize(self, duration):
"""
Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound
"""
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=... | 0.004988 |
def json(self, align_threshold: float = 0.0) -> Dict:
"""
Returns a dictionary suitable for json.dumps() representing all
the information in the class. It is initialized with any keys
present in the corresponding `TranslatorInput` object's pass_through_dict.
Keys from here that a... | 0.004739 |
def _set_number_of_plots(self, n):
"""
Adjusts number of plots & curves to the desired value the gui.
"""
# multi plot, right number of plots and curves = great!
if self.button_multi.is_checked() \
and len(self._curves) == len(self.plot_widgets) \
a... | 0.009479 |
def cache_mappings(file_path):
"""
Make a full mapping for 2 --> 3 columns.
Output the mapping to json in the specified file_path.
Note: This file is currently called maps.py,
full path is PmagPy/pmagpy/mapping/maps.py.
Parameters
----------
file_path : string with full file path to dum... | 0.001498 |
def with_stmt__26(self, with_loc, context, with_var, colon_loc, body):
"""(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite"""
if with_var:
as_loc, optional_vars = with_var
item = ast.withitem(context_expr=context, optional_vars=optional_vars,
... | 0.005706 |
def console_save_asc(con: tcod.console.Console, filename: str) -> bool:
"""Save a console to a non-delimited ASCII `.asc` file."""
return bool(
lib.TCOD_console_save_asc(_console(con), filename.encode("utf-8"))
) | 0.00431 |
def _parse_remote_response(self, response):
"""
Parse simple JWKS or signed JWKS from the HTTP response.
:param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri'
endpoint
:return: response parsed as JSON or None
"""
# Check if the content type ... | 0.001561 |
def find_by_fields(self, table, queryset={}):
'''
从数据库里查询 符合多个条件的记录
Args:
table: 表名字 str
queryset : key 字段 value 值 dict
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息
'''
querys = ""
for k, v in que... | 0.007722 |
def show_discrete_data(values, grid, title=None, method='',
force_show=False, fig=None, **kwargs):
"""Display a discrete 1d or 2d function.
Parameters
----------
values : `numpy.ndarray`
The values to visualize.
grid : `RectGrid` or `RectPartition`
Grid of th... | 0.000074 |
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Set the title and add the legend
self.s... | 0.002869 |
def killServices(self, services, error=False):
"""
:param dict services: Maps service jobStoreIDs to the communication flags for the service
"""
for serviceJobStoreID in services:
serviceJob = services[serviceJobStoreID]
if error:
self.jobStore.del... | 0.007075 |
def iter_tex_documents(base_dir="."):
"""Iterate through all .tex documents in the current directory."""
for path, dirlist, filelist in os.walk(base_dir):
for name in fnmatch.filter(filelist, "*.tex"):
yield os.path.join(path, name) | 0.003846 |
def cli_command_restart(self, msg):
"""\
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if its started we set our state to RUNNING, else we set it to WAITING
:par... | 0.007032 |
def dictify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python dictionary. """
try:
if isinstance(device_object['info']['description']['meta'], str) or \
isinstance(device_object['in... | 0.005102 |
def errinfo(msmt):
"""Return (limtype, repval, errval1, errval2). Like m_liminfo, but also
provides error bar information for values that have it."""
if isinstance(msmt, Textual):
msmt = msmt.unwrap()
if np.isscalar(msmt):
return 0, msmt, msmt, msmt
if isinstance(msmt, Uval):
... | 0.001678 |
def make_call_positionals(stack_builders, count):
"""
Make the args entry for an ast.Call node.
"""
out = [make_expr(stack_builders) for _ in range(count)]
out.reverse()
return out | 0.004902 |
def museval(inargs=None):
"""
Commandline interface for museval evaluation tools
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'estimates_dir',
type=str
)
parser.add_argument('-o', help='output_dir')
parser.add_argument('--cpu', type=int, help='number of ... | 0.000767 |
def append_segment(self, apdu):
"""This function appends the apdu content to the end of the current
APDU being built. The segmentAPDU is the context."""
if _debug: SSM._debug("append_segment %r", apdu)
# check for no context
if not self.segmentAPDU:
raise RuntimeErr... | 0.006881 |
def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cur... | 0.002181 |
def intersection(*argv):
"""Returns the intersection of multiple sets.
Items are ordered by set1, set2, ...
**中文文档**
求多个有序集合的交集, 按照第一个集合, 第二个, ..., 这样的顺序。
"""
res = OrderedSet(argv[0])
for ods in argv:
res = ods & res
return res | 0.009554 |
def do_commit(repo, message_template, branch_name, hexsha):
"Do a commit if modified/untracked files"
repo.git.add(repo.working_tree_dir)
if not repo.git.diff(staged=True):
_LOGGER.warning('No modified files in this Autorest run')
return False
checkout_and_create_branch(repo, branch_na... | 0.00211 |
def summary(self, raw):
"""Use the Backscatter.io summary data to create a view."""
taxonomies = list()
level = 'info'
namespace = 'Backscatter.io'
if self.service == 'observations':
summary = raw.get('results', dict()).get('summary', dict())
taxonomies =... | 0.007199 |
def hash_from_algo(algo):
"""
Return a :mod:`hashlib` hash given the :xep:`300` `algo`.
:param algo: The algorithm identifier as defined in :xep:`300`.
:type algo: :class:`str`
:raises NotImplementedError: if the hash algortihm is not supported by
:mod:`hashlib`.
:raises ValueError: if ... | 0.000902 |
def login(self, username=None, password=None, android_id=None):
"""Authenticate the gmusicapi Mobileclient instance.
Parameters:
username (Optional[str]): Your Google Music username. Will be prompted if not given.
password (Optional[str]): Your Google Music password. Will be prompted if not given.
andro... | 0.025 |
def switch_psm_to_peptable_fields(oldheader):
"""Returns a dict map with old to new header fields"""
return {old: new for old, new in zip([mzidtsvdata.HEADER_PEPTIDE,
mzidtsvdata.HEADER_PROTEIN,
mzidtsvdata.HEADER_PEPTIDE_Q,
... | 0.00149 |
def get_qcos_client(self, app_uri):
"""获得资源管理客户端
缓存,但不是线程安全的
"""
client = self.qcos_clients.get(app_uri)
if (client is None):
client = self.create_qcos_client(app_uri)
self.qcos_clients[app_uri] = client
return client | 0.006873 |
def write_data(self, buf):
"""Send data to the device.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
data = ''.join(map(chr, buf))
size = len(data)
if hidapi.hid_write(self.device, ctypes.c_char_p... | 0.00432 |
def _get_crud_params(compiler, stmt, **kw):
""" extract values from crud parameters
taken from SQLAlchemy's crud module (since 1.0.x) and
adapted for Crate dialect"""
compiler.postfetch = []
compiler.insert_prefetch = []
compiler.update_prefetch = []
compiler.re... | 0.00082 |
def table_from_file(source, ifo=None, columns=None, selection=None,
loudest=False, extended_metadata=True):
"""Read a `Table` from a PyCBC live HDF5 file
Parameters
----------
source : `str`, `h5py.File`, `h5py.Group`
the file path of open `h5py` object from which to read th... | 0.000453 |
def continuous_eval(self):
"""Evaluate until checkpoints stop being produced."""
for ckpt_path in next_checkpoint(self._hparams.model_dir,
self._hparams.eval_timeout_mins):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_path(ckpt_path)
if tra... | 0.011655 |
def _transform(xsl_filename, xml, **kwargs):
"""Transforms the xml using the specifiec xsl file."""
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | 0.005464 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.