Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
9,100 | def workdir_is_clean(self, quiet=False):
self.run(, **RUN_KWARGS)
unchanged = True
try:
self.run(, report_error=False, **RUN_KWARGS)
except exceptions.Failure:
unchanged = False
if not quiet:
notify.warning()... | Check for uncommitted changes, return `True` if everything is clean.
Inspired by http://stackoverflow.com/questions/3878624/. |
9,101 | def load_response_microservices(plugin_path, plugins, internal_attributes, base_url):
response_services = _load_microservices(plugin_path, plugins, _response_micro_service_filter, internal_attributes,
base_url)
logger.info("Loaded response micro services: %s" % [... | Loads response micro services (handling outgoing responses).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.ResponseMicroService
:param plugin_path: Path to t... |
9,102 | def _validate(self, key, cls=None):
if key not in self.manifest:
raise ValueError("Manifest %s requires ."
% (self.manifest_path, key))
if cls:
if not isinstance(self.manifest[key], cls):
raise TypeError("Manifest value shoul... | Verify the manifest schema. |
9,103 | def _rescale_and_convert_field_inplace(self, array, name, scale, zero):
self._rescale_array(array[name], scale, zero)
if array[name].dtype == numpy.bool:
array[name] = self._convert_bool_array(array[name])
return array | Apply fits scalings. Also, convert bool to proper
numpy boolean values |
9,104 | def get_plugin_actions(self):
quit_action = create_action(self, _("&Quit"),
icon=ima.icon(),
tip=_("Quit"),
triggered=self.quit)
self.register_shortcut(quit_action, "_", "Quit", "C... | Return a list of actions related to plugin |
9,105 | def stats_shooting(self, kind=, summary=False):
return self._get_stats_table(, kind=kind, summary=summary) | Returns a DataFrame of shooting stats. |
9,106 | def check_all_servers():
data = datatools.get_data()
for server_id in data["discord"]["servers"]:
is_in_client = False
for client_server in client.servers:
if server_id == client_server.id:
is_in_client = True
break
if not is_in_client:
... | Checks all servers, removing any that Modis isn't part of any more |
9,107 | def _validate_sort_field(self, sort_by):
if (
sort_by not in self.RESPONSE_FIELD_MAP
or not self.RESPONSE_FIELD_MAP[sort_by].is_sort
):
raise InvalidSortFieldException(
.format(sort_by)
) | :param sort_by: string
:raises: pybomb.exceptions.InvalidSortFieldException |
9,108 | def metafetcher(bamfile, metacontig2contig, metatag):
for metacontig in metacontig2contig:
for contig in metacontig2contig[metacontig]:
for read in bamfile.fetch(contig):
read.set_tag(metatag, metacontig)
yield read | return reads in order of metacontigs |
9,109 | def _get_headers(self):
headers = {
: .format(version=sys.version_info[0]),
:
}
if self.access_token:
headers[] = .format(self.access_token)
return headers | Built headers for request to IPinfo API. |
9,110 | def encode_exception(exception):
import sys
return AsyncException(unicode(exception),
exception.args,
sys.exc_info(),
exception) | Encode exception to a form that can be passed around and serialized.
This will grab the stack, then strip off the last two calls which are
encode_exception and the function that called it. |
9,111 | def from_metadata(self, db_path, db_name=):
self.__engine.fromMetadata(db_path, db_name)
return self | Registers in the current session the views of the MetadataSource so the
data is obtained from the metadata database instead of reading the
repositories with the DefaultSource.
:param db_path: path to the folder that contains the database.
:type db_path: str
:param db_name: name ... |
9,112 | def p2th_address(self) -> Optional[str]:
if self.id:
return Kutil(network=self.network,
privkey=bytearray.fromhex(self.id)).address
else:
return None | P2TH address of this deck |
9,113 | def long_description(*filenames):
res = []
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append( + line)
res.append()
res.append()
return EMPTYSTRING.join(res) | Provide a long description. |
9,114 | def _shrink_update(self, rmstart: int, rmstop: int) -> None:
for spans in self._type_to_spans.values():
i = len(spans) - 1
while i >= 0:
s, e = span = spans[i]
if rmstop <= s:
rml... | Update self._type_to_spans according to the removed span.
Warning: If an operation involves both _shrink_update and
_insert_update, you might wanna consider doing the
_insert_update before the _shrink_update as this function
can cause data loss in self._type_to_spans. |
9,115 | def configfield_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
node = pending_configfield_xref(rawsource=text)
return [node], [] | Process a role that references the Task configuration field nodes
created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``,
and ``lsst-task-config-subtasks`` directives.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet,... |
9,116 | def plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)):
sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n,
hopping=[0.5]*2*N, orbital_e=[0]*2*N)
hlog = solve_loop(sl, Uspan, [0.])[1]
f, (ax1, ax2) = plt.subplots(2, sharex=True)
for field in hlog:
fie... | Generates the plot on the convergenge of the mean field in single
site spin hamiltonian under with N degenerate half-filled orbitals |
9,117 | def sanitize_and_wrap(self, task_id, args, kwargs):
dep_failures = []
new_args = []
for dep in args:
if isinstance(dep, Future):
try:
new_args.extend([dep.result()])
except Exception as e:
if s... | This function should be called **ONLY** when all the futures we track have been resolved.
If the user hid futures a level below, we will not catch
it, and will (most likely) result in a type error.
Args:
task_id (uuid str) : Task id
func (Function) : App function
... |
9,118 | def import_keypair(kwargs=None, call=None):
if call != :
log.error(
)
return False
if not kwargs:
kwargs = {}
if not in kwargs:
log.error()
return False
if not in kwargs:
log.error()
return False
params = {: ,
... | Import an SSH public key.
.. versionadded:: 2015.8.3 |
9,119 | def find_sdl_attrs(prefix: str) -> Iterator[Tuple[str, Any]]:
from tcod._libtcod import lib
if prefix.startswith("SDL_"):
name_starts_at = 4
elif prefix.startswith("SDL"):
name_starts_at = 3
else:
name_starts_at = 0
for attr in dir(lib):
if attr.startswith(prefi... | Return names and values from `tcod.lib`.
`prefix` is used to filter out which names to copy. |
9,120 | def read_array(self, key, start=None, stop=None):
import tables
node = getattr(self.group, key)
attrs = node._v_attrs
transposed = getattr(attrs, , False)
if isinstance(node, tables.VLArray):
ret = node[0][start:stop]
else:
dtype = getat... | read an array for the specified node (off of group |
9,121 | def get_range(self):
classes = concrete_descendents(self.class_)
d=OrderedDict((name,class_) for name,class_ in classes.items())
if self.allow_None:
d[]=None
return d | Return the possible types for this parameter's value.
(I.e. return {name: <class>} for all classes that are
concrete_descendents() of self.class_.)
Only classes from modules that have been imported are added
(see concrete_descendents()). |
9,122 | def simple_moving_matrix(x, n=10):
if x.ndim > 1 and len(x[0]) > 1:
x = np.average(x, axis=1)
h = n / 2
o = 0 if h * 2 == n else 1
xx = []
for i in range(h, len(x) - h):
xx.append(x[i-h:i+h+o])
return np.array(xx) | Create simple moving matrix.
Parameters
----------
x : ndarray
A numpy array
n : integer
The number of sample points used to make average
Returns
-------
ndarray
A n x n numpy array which will be useful for calculating confidentail
interval of simple moving ... |
9,123 | def get_templates(self):
use = getattr(self, , )
if isinstance(use, list):
return [n.strip() for n in use if n.strip()]
return [n.strip() for n in use.split() if n.strip()] | Get list of templates this object use
:return: list of templates
:rtype: list |
9,124 | def local_assortativity_wu_sign(W):
n = len(W)
np.fill_diagonal(W, 0)
r_pos = assortativity_wei(W * (W > 0))
r_neg = assortativity_wei(W * (W < 0))
str_pos, str_neg, _, _ = strengths_und_sign(W)
loc_assort_pos = np.zeros((n,))
loc_assort_neg = np.zeros((n,))
for curr_node in ran... | Local assortativity measures the extent to which nodes are connected to
nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014
formula to allowed weighted/signed networks.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
... |
9,125 | def add_message(self, text, type=None):
key = self._msg_key
self.setdefault(key, [])
self[key].append(message(type, text))
self.save() | Add a message with an optional type. |
9,126 | def decode_transformer(encoder_output,
encoder_decoder_attention_bias,
targets,
hparams,
name,
task=None,
causal=True):
orig_hparams = hparams
with tf.variable_scope(name):
... | Original Transformer decoder. |
9,127 | def cover(ctx, html=False):
header()
cmd =
if html:
cmd = .join((cmd, ))
with ctx.cd(ROOT):
ctx.run(cmd, pty=True) | Run tests suite with coverage |
9,128 | def global_maxpooling(attrs, inputs, proto_obj):
new_attrs = translation_utils._add_extra_attributes(attrs, {: True,
: (1, 1),
: })
return , new_attrs, inputs | Performs max pooling on the input. |
9,129 | def buffered_write(self, buf):
if self.closed:
raise ConnectionClosed()
if len(buf) + len(self.write_buffer) > self.max_size:
raise BufferOverflowError()
else:
self.write_buffer.extend(buf) | Appends a bytes like object to the transport write buffer.
Raises BufferOverflowError if buf would cause the buffer to grow beyond
the specified maximum.
buf -- bytes to send |
9,130 | def full_name(self, gender: Optional[Gender] = None,
reverse: bool = False) -> str:
if gender is None:
gender = get_random_item(Gender, rnd=self.random)
if gender and isinstance(gender, Gender):
gender = gender
else:
raise NonEnumer... | Generate a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang. |
9,131 | def index(credentials=None):
user, oauth_access_token = parsecredentials(credentials)
if not settings.ADMINS or user not in settings.ADMINS:
return flask.make_response(,403)
usersprojects = {}
totalsize = {}
for f in glob.glob(settings.ROOT + "projects/*"):
... | Get list of projects |
9,132 | def failover(self, sync=None, force=None):
req_body = self._cli.make_body(sync=sync, force=force)
resp = self.action(, **req_body)
resp.raise_if_err()
return resp | Fails over a replication session.
:param sync: True - sync the source and destination resources before
failing over the asynchronous replication session or keep them in
sync after failing over the synchronous replication session.
False - don't sync.
:param force: Tru... |
9,133 | def process_config(self):
if in self.config:
if isinstance(self.config[], basestring):
self.config[] = self.config[].split()
if in self.config:
self.config[] = str_to_bool(self.config[])
if in self.config:
self.config[] = str_to_b... | Intended to put any code that should be run after any config reload
event |
9,134 | def main(
gpus:Param("The GPUs to use for distributed training", str)=,
script:Param("Script to run", str, opt=False)=,
args:Param("Args to pass to script", nargs=, opt=False)=
):
"PyTorch distributed training launch helper that spawns multiple distributed processes"
current_env = os.environ.co... | PyTorch distributed training launch helper that spawns multiple distributed processes |
9,135 | def _pluck_feature_pacts(pr_body: str) -> FrozenSet[str]:
feature_pact_lines = [line for line in pr_body.split()
if line.startswith()]
if not feature_pact_lines:
return frozenset()
if len(feature_pact_lines) > 1:
raise GithubPrError(f)
return frozenset(feat... | # Returns set with one feature pact if specified
>>> body = 'gitlab: mygitlaburl.com\\r\\nfeature-pacts: zh-feature-a'
>>> _pluck_feature_pacts(body) == frozenset({'zh-feature-a'})
True
# Returns set with multiple feature pacts if specified
>>> body = 'gitlab: mygitlaburl.com\\r\\nfeature-pacts: zh... |
9,136 | def __process_warc_gz_file(self, path_name):
counter_article_total = 0
counter_article_passed = 0
counter_article_discarded = 0
start_time = time.time()
with open(path_name, ) as stream:
for record in ArchiveIterator(stream):
... | Iterates all transactions in one WARC file and for each transaction tries to extract an article object.
Afterwards, each article is checked against the filter criteria and if all are passed, the function
on_valid_article_extracted is invoked with the article object.
:param path_name:
:re... |
9,137 | def _getData(self, data):
if not isinstance(data, dict):
raise ValidationError(
% (str(type(data)),))
return data | Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` if data is missing or wrong type
... |
9,138 | def getAnalogChannelData(self,ChNumber):
if not self.DatFileContent:
print "No data file content. Use the method ReadDataFile first"
return 0
if (ChNumber > self.A):
print "Channel number greater than the total number of channels."
retur... | Returns an array of numbers containing the data values of the channel
number "ChNumber".
ChNumber is the number of the channal as in .cfg file. |
9,139 | def fixLabel(label, maxlen, delim=None, repl=, truncend=True):
if len(label) <= maxlen:
return label
else:
maxlen -= len(repl)
if delim is not None:
if truncend:
end = label.rfind(delim, 0, maxlen)
if end > 0:
return ... | Truncate long graph and field labels.
@param label: Label text.
@param maxlen: Maximum field label length in characters.
No maximum field label length is enforced by default.
@param delim: Delimiter for field labels field labels longer than
... |
9,140 | def get_special_scen_code(regions, emissions):
if sorted(set(PART_OF_SCENFILE_WITH_EMISSIONS_CODE_0)) == sorted(set(emissions)):
scenfile_emissions_code = 0
elif sorted(set(PART_OF_SCENFILE_WITH_EMISSIONS_CODE_1)) == sorted(set(emissions)):
scenfile_emissions_code = 1
else:
msg ... | Get special code for MAGICC6 SCEN files.
At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit
number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions
data is being provided for. The second digit, the 'scenfile_emissions_code', tells
MAGICC which gases are in ... |
9,141 | def update_record(self, name, recordid, content, username, password):
req = requests.put(self.api_server + + name + +
str(recordid), data=json.dumps(content),
auth=(username, password))
return req | Update record |
9,142 | def make_cell(table, span, widths, heights, use_headers):
width = get_span_char_width(span, widths)
height = get_span_char_height(span, heights)
text_row = span[0][0]
text_column = span[0][1]
text = table[text_row][text_column]
lines = text.split("\n")
for i in range(len(lines)):
... | Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [row, column] pairs that make up a span in the table
widths : list of... |
9,143 | def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None,
ndigits=5, unit=, stroke_width=1, fill_opacity=.9,
geojson_properties=None, strdump=False, serialize=True):
polygon_features = []
contourf_idx = 0
for col... | Transform matplotlib.contourf to geojson with overlapping filled contours. |
9,144 | def printData(self, output = sys.stdout):
self.printDatum("Name : ", self.fileName, output)
self.printDatum("Author : ", self.author, output)
self.printDatum("Repository : ", self.repository, output)
self.printDatum("Category : ", self.category, output)
self.printDatum("Downloads ... | Output all the file data to be written to any writable output |
9,145 | async def update_object(obj, only=None):
warnings.warn("update_object() is deprecated, Manager.update() "
"should be used instead",
DeprecationWarning)
field_dict = dict(obj.__data__)
pk_field = obj._meta.primary_key
if o... | Update object asynchronously.
:param obj: object to update
:param only: list or tuple of fields to updata, is `None` then all fields
updated
This function does the same as `Model.save()`_ for already saved object,
but it doesn't invoke ``save()`` method on model class. That is
impo... |
9,146 | def detokenize(self, inputs, delim=):
detok = delim.join([self.idx2tok[idx] for idx in inputs])
detok = detok.replace(self.separator + , )
detok = detok.replace(self.separator, )
detok = detok.replace(config.BOS_TOKEN, )
detok = detok.replace(config.EOS_TOKEN, )
... | Detokenizes single sentence and removes token separator characters.
:param inputs: sequence of tokens
:param delim: tokenization delimiter
returns: string representing detokenized sentence |
9,147 | def perform_request(self, request):
connection = self.get_connection(request)
try:
connection.putrequest(request.method, request.path)
self.send_request_headers(connection, request.headers)
self.send_request_body(connection, request.body)
if DEB... | Sends request to cloud service server and return the response. |
9,148 | def DateStringToDateObject(date_string):
if re.match(, date_string) == None:
return None
try:
return datetime.date(int(date_string[0:4]), int(date_string[4:6]),
int(date_string[6:8]))
except ValueError:
return None | Return a date object for a string "YYYYMMDD". |
9,149 | def _load(self, filename=None):
if not filename:
filename = self.filename
wb_ = open_workbook(filename)
self.rsr = {}
sheet_names = []
for sheet in wb_.sheets():
if sheet.name in [, ]:
continue
ch_name = AHI_BAND_NAMES... | Load the Himawari AHI RSR data for the band requested |
9,150 | def get(remote_file, local_file):
board_files = files.Files(_board)
contents = board_files.get(remote_file)
if local_file is None:
print(contents.decode("utf-8"))
else:
local_file.write(contents) | Retrieve a file from the board.
Get will download a file from the board and print its contents or save it
locally. You must pass at least one argument which is the path to the file
to download from the board. If you don't specify a second argument then
the file contents will be printed to standard ou... |
9,151 | def get_relative_abundance(biomfile):
biomf = biom.load_table(biomfile)
norm_biomf = biomf.norm(inplace=False)
rel_abd = {}
for sid in norm_biomf.ids():
rel_abd[sid] = {}
for otuid in norm_biomf.ids("observation"):
otuname = oc.otu_name(norm_biomf.metadata(otuid, axis="o... | Return arcsine transformed relative abundance from a BIOM format file.
:type biomfile: BIOM format file
:param biomfile: BIOM format file used to obtain relative abundances for each OTU in
a SampleID, which are used as node sizes in network plots.
:type return: Dictionary of dictionar... |
9,152 | def pool(arr, block_size, func, cval=0, preserve_dtype=True):
from . import dtypes as iadt
iadt.gate_dtypes(arr,
allowed=["bool", "uint8", "uint16", "uint32", "int8", "int16", "int32",
"float16", "float32", "float64", "float128"],
... | Resize an array by pooling values within blocks.
dtype support::
* ``uint8``: yes; fully tested
* ``uint16``: yes; tested
* ``uint32``: yes; tested (2)
* ``uint64``: no (1)
* ``int8``: yes; tested
* ``int16``: yes; tested
* ``int32``: yes; tested (2)
... |
9,153 | def decode(self, bytes, raw=False):
code = super(EVRType, self).decode(bytes)
result = None
if raw:
result = code
elif code in self.evrs.codes:
result = self.evrs.codes[code]
else:
result = code
log.warn( % code)
... | decode(bytearray, raw=False) -> value
Decodes the given bytearray according the corresponding
EVR Definition (:class:`EVRDefn`) for the underlying
'MSB_U16' EVR code.
If the optional parameter ``raw`` is ``True``, the EVR code
itself will be returned instead of the EVR Definiti... |
9,154 | def simple_newton(f, x0, lb=None, ub=None, infos=False, verbose=False, maxit=50, tol=1e-8, eps=1e-8, numdiff=True):
precision = x0.dtype
from numpy.linalg import solve
err = 1
it = 0
while err > tol and it <= maxit:
if not numdiff:
[res,dres] = f(x0)
else:
... | Solves many independent systems f(x)=0 simultaneously using a simple gradient descent.
:param f: objective function to be solved with values p x N . The second output argument represents the derivative with
values in (p x p x N)
:param x0: initial value ( p x N )
:return: solution x such that f(x) = 0 |
9,155 | def construct_user_list(raw_users=None):
users = Users(oktypes=User)
for user_dict in raw_users:
public_keys = None
if user_dict.get():
public_keys = [PublicKey(b64encoded=x, raw=None)
for x in user_dict.get()]
u... | Construct a list of User objects from a list of dicts. |
9,156 | def bond_canonical_statistics(
microcanonical_statistics,
convolution_factors,
**kwargs
):
spanning_cluster = (
in microcanonical_statistics.dtype.names
)
ret = np.empty(1, dtype=canonical_statistics_dtype(spanning_cluster))
if spanning_cluster:
ret[] = np.su... | canonical cluster statistics for a single run and a single probability
Parameters
----------
microcanonical_statistics : ndarray
Return value of `bond_microcanonical_statistics`
convolution_factors : 1-D array_like
The coefficients of the convolution for the given probabilty ``p``
... |
9,157 | def _add_to_index(index, obj):
id_set = index.value_map.setdefault(indexed_value(index, obj), set())
if index.unique:
if len(id_set) > 0:
raise UniqueConstraintError()
id_set.add(obj.id) | Adds the given object ``obj`` to the given ``index`` |
9,158 | def highlight_text(text, lexer_name=, **kwargs):
r
lexer_name = {
: ,
: ,
: ,
: ,
}.get(lexer_name.replace(, ), lexer_name)
if lexer_name in [, , , ]:
return color_text(text, lexer_name)
import utool as ut
if ENABLE_COLORS:
try:
... | r"""
SeeAlso:
color_text |
9,159 | def datasets_view(self, owner_slug, dataset_slug, **kwargs):
kwargs[] = True
if kwargs.get():
return self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs)
else:
(data) = self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs)
... | Show details about a dataset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_view(owner_slug, dataset_slug, async_req=True)
>>> result = thread.get()
:param async_r... |
9,160 | def p_expr_LE_expr(p):
p[0] = make_binary(p.lineno(2), , p[1], p[3], lambda x, y: x <= y) | expr : expr LE expr |
9,161 | def __convertRlocToRouterId(self, xRloc16):
routerList = []
routerList = self.__sendCommand(WPANCTL_CMD + )
print routerList
print xRloc16
for line in routerList:
if re.match(, line):
continue
if re.match(WPAN_CARRIER_PROMPT, line... | mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader |
9,162 | def on_menu_exit(self, event):
if self.close_warning:
TEXT = "Data is not saved to a file yet!\nTo properly save your data:\n1) Analysis --> Save current interpretations to a redo file.\nor\n1) File --> Save MagIC tables.\n\n Press OK to exit without saving."
dlg1 = wx.MessageDi... | Runs whenever Thellier GUI exits |
9,163 | def count_function(func):
@use_defaults
@wraps(func)
def wrapper(row, cohort, filter_fn=None, normalized_per_mb=None, **kwargs):
per_patient_data = func(row=row,
cohort=cohort,
filter_fn=filter_fn,
... | Decorator for functions that return a collection (technically a dict of collections) that should be
counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if
not specified. |
9,164 | def index_based_complete(self, text: str, line: str, begidx: int, endidx: int,
index_dict: Mapping[int, Union[Iterable, Callable]],
all_else: Union[None, Iterable, Callable] = None) -> List[str]:
tokens, _ = self.tokens_for_completion(l... | Tab completes based on a fixed position in the input string
:param text: the string prefix we are attempting to match (all returned matches must begin with it)
:param line: the current input line with leading whitespace removed
:param begidx: the beginning index of the prefix text
:param... |
9,165 | def from_record(cls, record, crs):
if not in record:
raise TypeError("The data isn't a valid record.")
return cls(to_shape(record), crs) | Load vector from record. |
9,166 | def prepend(cls, d, s, filter=Filter()):
i = 0
for x in s:
if x in filter:
d.insert(i, x)
i += 1 | Prepend schema object's from B{s}ource list to
the B{d}estination list while applying the filter.
@param d: The destination list.
@type d: list
@param s: The source list.
@type s: list
@param filter: A filter that allows items to be prepended.
@type filter: L{Filt... |
9,167 | def send_document(chat_id, document,
reply_to_message_id=None, reply_markup=None,
**kwargs):
files = None
if isinstance(document, InputFile):
files = [document]
document = None
elif not isinstance(document, str):
raise Exception()
pa... | Use this method to send general files.
:param chat_id: Unique identifier for the message recipient — User or GroupChat id
:param document: File to send. You can either pass a file_id as String to resend a file that is already on
the Telegram servers, or upload a new file using multipart/fo... |
9,168 | def get_login_redirect(self, provider, account):
info = self.model._meta.app_label, self.model._meta.model_name
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse( % i... | Return url to redirect authenticated users. |
9,169 | def delete(self, name, **kwargs):
self.gitlab.http_delete(self.path, query_data={: name}, **kwargs) | Delete a Label on the server.
Args:
name: The name of the label
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request |
9,170 | def _normalize_path(self, path):
norm_path = os.path.normpath(path)
return os.path.relpath(norm_path, start=self._get_working_dir()) | Normalizes a file path so that it returns a path relative to the root repo directory. |
9,171 | def plot(self, series, series_diff=None, label=, color=None, style=None):
color = self.get_color(color)
if series_diff is None and self.autodiffs:
series_diff = series.diff()
if self.stacked:
series += self.running_sum
self.ax1.fill_between(series.ind... | :param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will be plotted in the
bottom part.
:param string label:
The label fo... |
9,172 | def verify(self, tool):
if os.path.isfile(tool[]):
print( + tool[])
return True
else:
print( + tool[])
return False | check that the tool exists |
9,173 | def template(self):
s = Template(self._IPSET_TEMPLATE)
return s.substitute(sets=.join(self.sets),
date=datetime.today()) | Create a rules file in ipset --restore format |
9,174 | def add_training_sample(self, text=u, lang=):
self.trainer.add(text=text, lang=lang) | Initial step for adding new sample to training data.
You need to call `save_training_samples()` afterwards.
:param text: Sample text to be added.
:param lang: Language label for the input text. |
9,175 | async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
adapter_id = self._get_property(conn_id, )
return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payload, timeout) | Send an RPC to a device.
See :meth:`AbstractDeviceAdapter.send_rpc`. |
9,176 | def users_get_avatar(self, user_id=None, username=None, **kwargs):
if user_id:
return self.__call_api_get(, userId=user_id, kwargs=kwargs)
elif username:
return self.__call_api_get(, username=username, kwargs=kwargs)
else:
raise RocketMissingParamExce... | Gets the URL for a user’s avatar. |
9,177 | def _at_if(self, calculator, rule, scope, block):
if block.directive != :
if not in rule.options:
raise SyntaxError("@else with no @if (%s)" % (rule.file_and_line,))
if rule.options[]:
return
condition ... | Implements @if and @else if |
9,178 | def run_in_transaction(self, func, *args, **kw):
if getattr(self._local, "transaction_running", False):
raise RuntimeError("Spanner does not support nested transactions.")
self._local.transaction_running = True
try:
w... | Perform a unit of work in a transaction, retrying on abort.
:type func: callable
:param func: takes a required positional argument, the transaction,
and additional positional / keyword arguments as supplied
by the caller.
:type args: tuple
:par... |
9,179 | def get_album_songs(self, album_id):
url = .format(album_id)
result = self.get_request(url)
songs = result[][]
songs = [Song(song[], song[]) for song in songs]
return songs | Get a album's all songs.
warning: use old api.
:params album_id: album id.
:return: a list of Song object. |
9,180 | def resolve_symbol(self, symbol, bCaseSensitive = False):
if bCaseSensitive:
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName:
return SymbolAddress
else:
symbol = symbol.lower()
fo... | Resolves a debugging symbol's address.
@type symbol: str
@param symbol: Name of the symbol to resolve.
@type bCaseSensitive: bool
@param bCaseSensitive: C{True} for case sensitive matches,
C{False} for case insensitive.
@rtype: int or None
@return: Memor... |
9,181 | def _fix_unsafe(shell_input):
_unsafe = re.compile(r, 256)
try:
if len(_unsafe.findall(shell_input)) == 0:
return shell_input.strip()
else:
clean = "", "\""
return clean
except TypeError:
return None | Find characters used to escape from a string into a shell, and wrap them in
quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module.
:param str shell_input: The input intended for the GnuPG process. |
9,182 | def padded_to_same_length(seq1, seq2, item=0):
len1, len2 = len(seq1), len(seq2)
if len1 == len2:
return (seq1, seq2)
elif len1 < len2:
return (cons.ed(seq1, yield_n(len2-len1, item)), seq2)
else:
return (seq1, cons.ed(seq2, yield_n(len1-len2, item))) | Return a pair of sequences of the same length by padding the shorter
sequence with ``item``.
The padded sequence is a tuple. The unpadded sequence is returned as-is. |
9,183 | def validate(self):
results = []
from ..specs import Join
def recursive_find_loop(task, history):
current = history[:]
current.append(task)
if isinstance(task, Join):
if task in history:
msg = "Found loop with : %s... | Checks integrity of workflow and reports any problems with it.
Detects:
- loops (tasks that wait on each other in a loop)
:returns: empty list if valid, a list of errors if not |
9,184 | def install():
ceph_dir = "/etc/ceph"
if not os.path.exists(ceph_dir):
os.mkdir(ceph_dir)
apt_install(, fatal=True) | Basic Ceph client installation. |
9,185 | def probe_image(self, labels, instance, column_name=None, num_scaled_images=50,
top_percent=10):
if len(self._image_columns) > 1 and not column_name:
raise ValueError( +
)
elif column_name and column_name not in self._image_columns:
... | Get pixel importance of the image.
It performs pixel sensitivity analysis by showing only the most important pixels to a
certain label in the image. It uses integrated gradients to measure the
importance of each pixel.
Args:
labels: labels to compute gradients from.
... |
9,186 | def seek_to_end(self, *partitions):
if not all([isinstance(p, TopicPartition) for p in partitions]):
raise TypeError()
if not partitions:
partitions = self._subscription.assigned_partitions()
assert partitions,
else:
for p in partitions:
... | Seek to the most recent available offset for partitions.
Arguments:
*partitions: Optionally provide specific TopicPartitions, otherwise
default to all assigned partitions.
Raises:
AssertionError: If any partition is not currently assigned, or if
... |
9,187 | def write_header(self, out_strm, delim, f1_num_fields, f2_num_fields,
f1_header=None, f2_header=None, missing_val=None):
mm = f1_header != f2_header
one_none = f1_header is None or f2_header is None
if mm and one_none and missing_val is None:
raise InvalidHeaderError("Cannot ge... | Write the header for a joined file. If headers are provided for one or more
of the input files, then a header is generated for the output file.
Otherwise, this does not output anything.
:param out_strm: write to this stream
:param delim:
:param f1_num_fields: the number of columns in the first file... |
9,188 | def updateFromKwargs(self, kwargs, properties, collector, **kw):
yield self.collectChildProperties(kwargs=kwargs, properties=properties,
collector=collector, **kw)
if self.name:
d = properties.setdefault(self.name,... | By default, the child values will be collapsed into a dictionary. If
the parent is anonymous, this dictionary is the top-level properties. |
9,189 | def md2rst(md_lines):
lvl2header_char = {1: , 2: , 3: }
for md_line in md_lines:
if md_line.startswith():
header_indent, header_text = md_line.split(, 1)
yield header_text
header_char = lvl2header_char[len(header_indent)]
yield header_char * len(heade... | Only converts headers |
9,190 | def overlap(self, x, ctrs, kdtree=None):
q = len(self.within(x, ctrs, kdtree=kdtree))
return q | Check how many balls `x` falls within. Uses a K-D Tree to
perform the search if provided. |
9,191 | def GET_subdomain_ops(self, path_info, txid):
blockstackd_url = get_blockstackd_url()
subdomain_ops = None
try:
subdomain_ops = blockstackd_client.get_subdomain_ops_at_txid(txid, hostport=blockstackd_url)
except ValueError:
return self._reply_json({: }, s... | Get all subdomain operations processed in a given transaction.
Returns the list of subdomains on success (can be empty)
Returns 502 on failure to get subdomains |
9,192 | def create_srv_record(self, name, values, ttl=60):
self._halt_if_already_deleted()
return self._add_record(SRVResourceRecordSet, **values) | Creates a SRV record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the fo... |
9,193 | def pickleFile(self, name, minPartitions=None):
minPartitions = minPartitions or self.defaultMinPartitions
return RDD(self._jsc.objectFile(name, minPartitions), self) | Load an RDD previously saved using L{RDD.saveAsPickleFile} method.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)
>>> sorted(sc.pickleFile(tmpFile.name, 3).collect())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9... |
9,194 | def sort_key_for_numeric_suffixes(path, sep=, suffix_index=-2):
chunks = path.split(sep)
if chunks[suffix_index].isdigit():
return sep.join(chunks[:suffix_index] + chunks[suffix_index+1:]), int(chunks[suffix_index])
return path, 0 | Sort files taking into account potentially absent suffixes like
somefile.dcd
somefile.1000.dcd
somefile.2000.dcd
To be used with sorted(..., key=callable). |
9,195 | def get_sum(path, form=):
*
path = os.path.expanduser(path)
if not os.path.isfile(path):
return
return salt.utils.hashutils.get_hash(path, form, 4096) | Return the checksum for the given file. The following checksum algorithms
are supported:
* md5
* sha1
* sha224
* sha256 **(default)**
* sha384
* sha512
path
path to the file or directory
form
desired sum format
CLI Example:
.. code-block:: bash
s... |
9,196 | def _check_valid(key, val, valid):
if val not in valid:
raise ValueError(
% (key, valid, val)) | Helper to check valid options |
9,197 | def read_group_info(self):
self.groups = []
for i in range(self.tabs.count()):
one_group = self.tabs.widget(i).get_info()
self.groups.append(one_group) | Get information about groups directly from the widget. |
9,198 | async def validate(self, request: web.Request):
parameters = {}
files = {}
errors = self.errors_factory()
body = None
if request.method in request.POST_METHODS:
try:
body = await self._content_receiver.receive(request)
except Valu... | Returns parameters extract from request and multidict errors
:param request: Request
:return: tuple of parameters and errors |
9,199 | def write_training_data(self, features, targets):
assert len(features) == len(targets)
data = dict(zip(features, targets))
with open(os.path.join(self.repopath, ), ) as fp:
pickle.dump(data, fp) | Writes data dictionary to filename |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.