Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
12,200 | def visited(self):
try:
binfo = self.binfo
except AttributeError:
pass
else:
self.ninfo.update(self)
SCons.Node.store_info_map[self.store_info](self) | Called just after this node has been visited (with or
without a build). |
12,201 | def save_csv(p, sheet):
with p.open_text(mode=) as fp:
cw = csv.writer(fp, **csvoptions())
colnames = [col.name for col in sheet.visibleCols]
if .join(colnames):
cw.writerow(colnames)
for r in Progress(sheet.rows, ):
cw.writerow([col.getDisplayValue(r) fo... | Save as single CSV file, handling column names as first line. |
12,202 | def main():
desc =
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
,
dest=,
default=,
help=
)
parser.add_argument(
,
dest=,
default=,
help=
)
parser.add_argument(
,
dest=,
de... | The main function of the script |
12,203 | def cat(src_filename, dst_file):
(dev, dev_filename) = get_dev_and_path(src_filename)
if dev is None:
with open(dev_filename, ) as txtfile:
for line in txtfile:
dst_file.write(line)
else:
filesize = dev.remote_eval(get_filesize, dev_filename)
return d... | Copies the contents of the indicated file to an already opened file. |
12,204 | def _create_messages(self, names, data, isDms=False):
chats = {}
empty_dms = []
formatter = SlackFormatter(self.__USER_DATA, data)
for name in names:
dir_path = os.path.join(self._PATH, name)
messages = []
day_file... | Creates object of arrays of messages from each json file specified by the names or ids
:param [str] names: names of each group of messages
:param [object] data: array of objects detailing where to get the messages from in
the directory structure
:param bool isDms: boolean value used t... |
12,205 | def _settle_message(self, message_number, response):
if not response or isinstance(response, errors.MessageAlreadySettled):
return
if isinstance(response, errors.MessageAccepted):
self._receiver.settle_accepted_message(message_number)
elif isinstance(response, er... | Send a settle dispostition for a received message.
:param message_number: The delivery number of the message
to settle.
:type message_number: int
:response: The type of disposition to respond with, e.g. whether
the message was accepted, rejected or abandoned.
:type res... |
12,206 | def positions(self, word):
right = len(word) - self.right
return [i for i in self.hd.positions(word) if self.left <= i <= right] | Returns a list of positions where the word can be hyphenated.
See also Hyph_dict.positions. The points that are too far to
the left or right are removed. |
12,207 | def setup(self, config_file=None, aws_config=None, gpg_config=None,
decrypt_gpg=True, decrypt_kms=True):
if aws_config is not None:
self.aws_config = aws_config
if gpg_config is not None:
self.gpg_config = gpg_config
if decrypt_kms is not None:
... | Make setup easier by providing a constructor method.
Move to config_file
File can be located with a filename only, relative path, or absolute path.
If only name or relative path is provided, look in this order:
1. current directory
2. `~/.config/<file_name>`
3. `/etc/<f... |
12,208 | def delete(gandi, resource, background, force):
resource = sorted(tuple(set(resource)))
possible_resources = gandi.ip.resource_list()
for item in resource:
if item not in possible_resources:
gandi.echo( % item)
gandi.echo( %
possible_resource... | Delete one or more IPs (after detaching them from VMs if necessary).
resource can be an ip id or ip. |
12,209 | def dataframe(self, force_refresh=False):
if force_refresh:
self.clear_cache()
if self._dataframe is None:
self._dataframe = self._fetch_dataframe()
return self._dataframe | A pandas dataframe with lots of interesting results about this object.
Created by calling SageMaker List and Describe APIs and converting them into
a convenient tabular summary.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API. |
12,210 | def require(method):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not getattr(args[0], callmethod):
getattr(args[0], method)()
setattr(args[0], callmethod, True)
return func(*args, **kwargs)
retur... | Decorator for managing chained dependencies of different class
properties. The @require decorator allows developers to specify
that a function call must be operated on before another property
or function call is accessed, so that data and processing for an
entire class can be evaluated in a lazy way (i.... |
12,211 | def get_python_logger():
global _python_logger
if _python_logger is None:
fn = "a99.log"
l = logging.Logger("a99", level=a99.logging_level)
if a99.flag_log_file:
add_file_handler(l, fn)
if a99.flag_log_console:
ch = logging.StreamHandler()
... | Returns logger to receive Python messages (as opposed to Fortran).
At first call, _python_logger is created. At subsequent calls, _python_logger is returned.
Therefore, if you want to change `a99.flag_log_file` or `a99.flag_log_console`, do so
before calling get_python_logger(), otherwise these chang... |
12,212 | def generate_main_h(directory, xml):
f = open(os.path.join(directory, xml.basename + ".h"), mode=)
t.write(f, , xml)
f.close() | generate main header per XML file |
12,213 | def module_path(name, path):
define = Define(name, path)
assert os.path.isdir(path), "%r doesn't exist" % path
name = "malcolm.modules.%s" % name
import_package_from_path(name, path)
return define | Load an external malcolm module (e.g. ADCore/etc/malcolm) |
12,214 | def _add_vertex_attributes(self, genes: List[Gene],
disease_associations: Optional[dict] = None) -> None:
self._set_default_vertex_attributes()
self._add_vertex_attributes_by_genes(genes)
up_regulated = self.get_upregulated_genes()
down_r... | Add attributes to vertices.
:param genes: A list of genes containing attribute information. |
12,215 | def _blocks_to_samples(sig_data, n_samp, fmt):
if fmt == :
if n_samp % 2:
n_samp += 1
added_samps = 1
sig_data = np.append(sig_data, np.zeros(1, dtype=))
else:
added_samps = 0
sig_data = sig_data.astype()
sig = np.zeros(n... | Convert uint8 blocks into signal samples for unaligned dat formats.
Parameters
----------
sig_data : numpy array
The uint8 data blocks.
n_samp : int
The number of samples contained in the bytes
Returns
-------
signal : numpy array
The numpy array of digital samples |
12,216 | def get_xml_parser(encoding=None):
parser = etree.ETCompatXMLParser(
huge_tree=True,
remove_comments=True,
strip_cdata=False,
remove_blank_text=True,
resolve_entities=False,
encoding=encoding
)
return parser | Returns an ``etree.ETCompatXMLParser`` instance. |
12,217 | def _set_sample_rate_cpu(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={: []}, int_size=32), restriction_dict={: [u]}), is_leaf=True, yang_name="sample-rate-cpu", res... | Setter method for sample_rate_cpu, mapped from YANG variable /resource_monitor/cpu/sample_rate_cpu (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_sample_rate_cpu is considered as a private
method. Backends looking to populate this variable should
do so via call... |
12,218 | def delete_feature_base(dbpath, set_object, name):
engine = create_engine( + dbpath)
session_cl = sessionmaker(bind=engine)
session = session_cl()
tmp_object = session.query(set_object).get(1)
if tmp_object.features is not None and name in tmp_object.features:
for i in session.query(set... | Generic function which deletes a feature from a database
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
name : string, name of the feature to be deleted
Returns
-------
None |
12,219 | def execute_process_synchronously_or_raise(self, execute_process_request, name, labels=None):
fallible_result = self.execute_process_synchronously_without_raising(execute_process_request, name, labels)
return fallible_to_exec_result_or_raise(
fallible_result,
execute_process_request
) | Execute process synchronously, and throw if the return code is not 0.
See execute_process_synchronously for the api docs. |
12,220 | def bz2_pack(source):
import bz2, base64
out = ""
out += base64.b64encode(compressed_source).decode()
out += "')))\n"
return out | Returns 'source' as a bzip2-compressed, self-extracting python script.
.. note::
This method uses up more space than the zip_pack method but it has the
advantage in that the resulting .py file can still be imported into a
python program. |
12,221 | def _set_overlay_gateway(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",overlay_gateway.overlay_gateway, yang_name="overlay-gateway", rest_name="overlay-gateway", parent=self, is_container=, user_ordered=False, path_helper=self._p... | Setter method for overlay_gateway, mapped from YANG variable /overlay_gateway (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_gateway is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_overla... |
12,222 | def merge_odd_even_csu_configurations(conf_odd, conf_even):
merged_conf = deepcopy(conf_odd)
for i in range(EMIR_NBARS):
ibar = i + 1
if ibar % 2 == 0:
merged_conf._csu_bar_left[i] = conf_even._csu_bar_left[i]
merged_conf._csu_bar_right[i] = con... | Merge CSU configuration using odd- and even-numbered values.
The CSU returned CSU configuration include the odd-numbered values
from 'conf_odd' and the even-numbered values from 'conf_even'.
Parameters
----------
conf_odd : CsuConfiguration instance
CSU configuration corresponding to odd-n... |
12,223 | def get_station_year_text(WMO, WBAN, year):
if WMO is None:
WMO = 999999
if WBAN is None:
WBAN = 99999
station = str(int(WMO)) + + str(int(WBAN))
gsod_year_dir = os.path.join(data_dir, , str(year))
path = os.path.join(gsod_year_dir, station + )
if os.path.exists(path):
... | Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Navy (WBAN) weather station identifier, [-]
year ... |
12,224 | def default(self, o):
if isinstance(o, Atom) or isinstance(o, Bond):
return o._ctab_data
else:
return o.__dict__ | Default encoder.
:param o: Atom or Bond instance.
:type o: :class:`~ctfile.ctfile.Atom` or :class:`~ctfile.ctfile.Bond`.
:return: Dictionary that contains information required for atom and bond block of ``Ctab``.
:rtype: :py:class:`collections.OrderedDict` |
12,225 | def timeout(delay, handler=None):
delay = int(delay)
if handler is None:
def default_handler(signum, frame):
raise RuntimeError("{:d} seconds timeout expired".format(delay))
handler = default_handler
prev_sigalrm_handler = signal.getsignal(signal.SIGALRM)
signal.signal(s... | Context manager to run code and deliver a SIGALRM signal after `delay` seconds.
Note that `delay` must be a whole number; otherwise it is converted to an
integer by Python's `int()` built-in function. For floating-point numbers,
that means rounding off to the nearest integer from below.
If the optiona... |
12,226 | def bounds(self, pixelbuffer=0):
left = self._left
bottom = self._bottom
right = self._right
top = self._top
if pixelbuffer:
offset = self.pixel_x_size * float(pixelbuffer)
left -= offset
bottom -= offset
right += offset
... | Return Tile boundaries.
- pixelbuffer: tile buffer in pixels |
12,227 | def fit(self, X):
D = self._initialize(X)
for i in range(self.max_iter):
gamma = self._transform(D, X)
e = np.linalg.norm(X - gamma.dot(D))
if e < self.tol:
break
D, gamma = self._update_dict(X, D, gamma)
self.components_ ... | Parameters
----------
X: shape = [n_samples, n_features] |
12,228 | def completed_work_items(self):
"Iterable of `(work-item, result)`s for all completed items."
completed = self._conn.execute(
"SELECT * FROM work_items, results WHERE work_items.job_id == results.job_id"
)
return ((_row_to_work_item(result), _row_to_work_result(result))
... | Iterable of `(work-item, result)`s for all completed items. |
12,229 | def get_requirements(*args):
requirements = set()
contents = get_contents(*args)
for line in contents.splitlines():
line = re.sub(r, , line)
if line and not line.isspace():
requirements.add(re.sub(r, , line))
return sorted(requirements) | Get requirements from pip requirement files. |
12,230 | def grad_local_log_likelihood(self, x):
C, D, u, y = self.C, self.D, self.inputs, self.data
psi = x.dot(C.T) + u.dot(D.T)
p = 1. / (1 + np.exp(-psi))
return (y - p).dot(C) | d/d \psi y \psi - log (1 + exp(\psi))
= y - exp(\psi) / (1 + exp(\psi))
= y - sigma(psi)
= y - p
d \psi / dx = C
d / dx = (y - sigma(psi)) * C |
12,231 | def add_conversion_steps(self, converters: List[Converter], inplace: bool = False):
check_var(converters, var_types=list, min_len=1)
if inplace:
for converter in converters:
self.add_conversion_step(converter, inplace=True)
else:
new = copy(self)
... | Utility method to add converters to this chain. If inplace is True, this object is modified and
None is returned. Otherwise, a copy is returned
:param converters: the list of converters to add
:param inplace: boolean indicating whether to modify this object (True) or return a copy (False)
... |
12,232 | def linear(X, n, *args, **kwargs):
hyper_deriv = kwargs.pop(, None)
m = scipy.asarray(args[:-1])
b = args[-1]
if sum(n) > 1:
return scipy.zeros(X.shape[0])
elif sum(n) == 0:
if hyper_deriv is not None:
if hyper_deriv < len(m):
return X[:, hyper_deriv]... | Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`.
The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`.
Parameters
----------
X : array, (`M`, `D`)
The points to evaluate the model at.
n : array of non-negative int, (`D`)
... |
12,233 | def main():
check_python_version()
check_python_modules()
check_executables()
home = os.path.expanduser("~")
print("\033[1mCheck files\033[0m")
rcfile = os.path.join(home, ".hwrtrc")
if os.path.isfile(rcfile):
print("~/.hwrtrc... %sFOUND%s" %
(Bcolors.OKGREEN, Bcol... | Execute all checks. |
12,234 | def available_actions(self, obs):
available_actions = set()
hide_specific_actions = self._agent_interface_format.hide_specific_actions
for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE):
if func.avail_fn(obs):
available_actions.add(i)
for a in obs.abilities:
if a.ability_... | Return the list of available action ids. |
12,235 | def extract_edges(self, feature_angle=30, boundary_edges=True,
non_manifold_edges=True, feature_edges=True,
manifold_edges=True, inplace=False):
surf = self.extract_surface()
return surf.extract_edges(feature_angle, boundary_edges,
... | Extracts edges from the surface of the grid. From vtk documentation:
These edges are either
1) boundary (used by one polygon) or a line cell;
2) non-manifold (used by three or more polygons)
3) feature edges (edges used by two triangles and whose
dihedral ang... |
12,236 | def mk_token(self, load):
if not self.authenticate_eauth(load):
return {}
if self._allow_custom_expire(load):
token_expire = load.pop(, self.opts[])
else:
_ = load.pop(, None)
token_expire = self.opts[]
tdata = {: time.time(),
... | Run time_auth and create a token. Return False or the token |
12,237 | def flatten(self):
for key in self.keys:
try:
arr = self.__dict__[key]
shape = arr.shape
if shape[2] == 1:
self.__dict__[key] = arr.reshape(shape[0], shape[1])
except:
pass | Flattens any np.array of column vectors into 1D arrays. Basically,
this makes data readable for humans if you are just inspecting via
the REPL. For example, if you have saved a KalmanFilter object with 89
epochs, self.x will be shape (89, 9, 1) (for example). After flatten
is run, self.x... |
12,238 | def shifted(self, rows, cols):
shifted_block_tl = \
[(row + rows, col + cols) for row, col in self.block_tl]
shifted_block_br = \
[(row + rows, col + cols) for row, col in self.block_br]
shifted_rows = [row + rows for row in self.rows]
shifted_cols = [co... | Returns a new selection that is shifted by rows and cols.
Negative values for rows and cols may result in a selection
that addresses negative cells.
Parameters
----------
rows: Integer
\tNumber of rows that the new selection is shifted down
cols: Integer
... |
12,239 | def update_role(self, service_name, deployment_name, role_name,
os_virtual_hard_disk=None, network_config=None,
availability_set_name=None, data_virtual_hard_disks=None,
role_size=None, role_type=,
resource_extension_references=None,
... | Updates the specified virtual machine.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
role_name:
The name of the role.
os_virtual_hard_disk:
Contains the parameters Windows Azure uses to create the oper... |
12,240 | def processData(config, stats):
if not in stats or not in stats:
stats.total_time = [0.0]
stats.total_clock = [0.0]
stats.total_time = sum([float(number) for number in stats.total_time])
stats.total_clock = sum([float(number) for number in stats.total_clock])
collatedSt... | Collate the stats and report |
12,241 | def rhymes(word):
phones = phones_for_word(word)
combined_rhymes = []
if phones:
for element in phones:
combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part(
element), []) if w != word])
combined_rhymes = list(chain.from_iterab... | Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhymes("conditioner")
... |
12,242 | def fromtimestamp(cls, ts, tzi=None):
if tzi is None:
tzi = MinutesFromUTC(cls.get_local_utcoffset())
return cls(datetime.fromtimestamp(ts, tzi)) | Factory method that returns a new :class:`~pywbem.CIMDateTime` object
from a POSIX timestamp value and optional timezone information.
A POSIX timestamp value is the number of seconds since "the epoch",
i.e. 1970-01-01 00:00:00 UTC. Thus, a POSIX timestamp value is
unambiguous w.r.t. the... |
12,243 | def update(self, track=values.unset, publisher=values.unset, kind=values.unset,
status=values.unset):
data = values.of({: track, : publisher, : kind, : status, })
payload = self._version.update(
,
self._uri,
data=data,
)
retur... | Update the SubscribedTrackInstance
:param unicode track: The track
:param unicode publisher: The publisher
:param SubscribedTrackInstance.Kind kind: The kind
:param SubscribedTrackInstance.Status status: The status
:returns: Updated SubscribedTrackInstance
:rtype: twili... |
12,244 | def to_array(self):
array = super(StickerMessage, self).to_array()
if isinstance(self.sticker, InputFile):
array[] = self.sticker.to_array()
elif isinstance(self.sticker, str):
array[] = u(self.sticker)
else:
raise TypeError()
... | Serializes this StickerMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
12,245 | def installedRequirements(self, target):
myDepends = dependentsOf(self.__class__)
for dc in self.store.query(_DependencyConnector,
_DependencyConnector.target == target):
if dc.installee.__class__ in myDepends:
yield dc.installee | Return an iterable of things installed on the target that this
item requires. |
12,246 | def minimum_needs_extractor(impact_report, component_metadata):
context = {}
extra_args = component_metadata.extra_args
analysis_layer = impact_report.analysis
analysis_keywords = analysis_layer.keywords[]
use_rounding = impact_report.impact_function.use_rounding
header = resolve_from_dict... | Extracting minimum needs of the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information a... |
12,247 | def _readLoop(self):
try:
readTermSeq = list(self.RX_EOL_SEQ)
readTermLen = len(readTermSeq)
rxBuffer = []
while self.alive:
data = self.serial.read(1)
if data != :
rxBuffer.append(... | Read thread main loop
Reads lines from the connected device |
12,248 | def _standardize_data(
model: pd.DataFrame,
data: pd.DataFrame,
batch_key: str,
) -> Tuple[pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray]:
batch_items = model.groupby(batch_key).groups.items()
batch_levels, batch_info = zip(*batch_items)
n_batch = len(batch_info)
n_batches = ... | Standardizes the data per gene.
The aim here is to make mean and variance be comparable across batches.
Parameters
--------
model
Contains the batch annotation
data
Contains the Data
batch_key
Name of the batch column in the model matrix
Returns
--------
s_... |
12,249 | def plot_fit(self, **kwargs):
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get(,(10,7))
if self.latent_variables.estimated is False:
raise Exception("No latent variables estimated!")
else:
date_index = self.index.copy(... | Plots the fit of the model
Notes
----------
Intervals are bootstrapped as follows: take the filtered values from the
algorithm (thetas). Use these thetas to generate a pseudo data stream from
the measurement density. Use the GAS algorithm and estimated latent variables to
... |
12,250 | def partial_to_complete_sha_hex(self, partial_hexsha):
try:
hexsha, typename, size = self._git.get_object_header(partial_hexsha)
return hex_to_bin(hexsha)
except (GitCommandError, ValueError):
raise BadObject(partial_hexsha) | :return: Full binary 20 byte sha from the given partial hexsha
:raise AmbiguousObjectName:
:raise BadObject:
:note: currently we only raise BadObject as git does not communicate
AmbiguousObjects separately |
12,251 | def clean(self, point_merging=True, merge_tol=None, lines_to_points=True,
polys_to_lines=True, strips_to_polys=True, inplace=False):
clean = vtk.vtkCleanPolyData()
clean.SetConvertLinesToPoints(lines_to_points)
clean.SetConvertPolysToLines(polys_to_lines)
clean.Set... | Cleans mesh by merging duplicate points, remove unused
points, and/or remove degenerate cells.
Parameters
----------
point_merging : bool, optional
Enables point merging. On by default.
merge_tol : float, optional
Set merging tolarance. When enabled me... |
12,252 | def QA_util_sql_async_mongo_setting(uri=):
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return AsyncIOMotorClient(uri, io_loop=loop) | 异步mongo示例
Keyword Arguments:
uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'})
Returns:
[type] -- [description] |
12,253 | def sg_init(sess):
r
sess.run(tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())) | r""" Initializes session variables.
Args:
sess: Session to initialize. |
12,254 | def import_ohm(filename, verbose=False, reciprocals=False):
if verbose:
print(("Reading in %s... \n" % filename))
file = open(filename)
eleccount = int(file.readline().split("
elecs_str = file.readline().split("
elecs_dim = len(elecs_str.split())
elecs_ix = elecs_str.split()
e... | Construct pandas data frame from BERT`s unified data format (.ohm).
Parameters
----------
filename : string
File path to .ohm file
verbose : bool, optional
Enables extended debug output
reciprocals : int, optional
if provided, then assume that this is a reciprocal measuremen... |
12,255 | def get_single_review_comments(self, id):
assert isinstance(id, (int, long)), id
return github.PaginatedList.PaginatedList(
github.PullRequestComment.PullRequestComment,
self._requester,
self.url + "/reviews/" + str(id) + "/comments",
None
... | :calls: `GET /repos/:owner/:repo/pulls/:number/review/:id/comments <https://developer.github.com/v3/pulls/reviews/>`_
:param id: integer
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestComment.PullRequestComment` |
12,256 | def kill(self):
try:
logger.info()
self.process.terminate()
time_waited_seconds = 0
while self.process.poll() is None and time_waited_seconds < CONSTANTS.SECONDS_TO_KILL_AFTER_SIGTERM:
time.sleep(0.5)
time_waited_seconds += 0.5
if self.process.poll() is None:
... | If run_step needs to be killed, this method will be called
:return: None |
12,257 | def lookup_by_number(errno):
for key, val in globals().items():
if errno == val:
print(key) | Used for development only |
12,258 | def sum_from(zero: T1 = None) -> Callable[[ActualIterable[T1]], T1]:
def _(collection: Iterable[T1]) -> T1:
if zero is None:
collection = iter(collection)
_zero = next(collection)
return builtins.sum(collection, _zero)
return builtins.sum(collection, zero)
... | >>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [1, 2, 3]
>>> x = Flow(lst)[Traversal.sum_from(0)].unbox
>>> assert x is 6
>>> x = Flow(lst)[Traversal.sum_from()].unbox
>>> assert x is 6 |
12,259 | def parse_identifier(source, start, throw=True):
start = pass_white(source, start)
end = start
if not end < len(source):
if throw:
raise SyntaxError()
return None
if source[end] not in IDENTIFIER_START:
if throw:
raise SyntaxError( % source[end])
... | passes white space from start and returns first identifier,
if identifier invalid and throw raises SyntaxError otherwise returns None |
12,260 | def copy_file_to_remote(self, local_path, remote_path):
sftp_client = self.transport.open_sftp_client()
LOG.debug(
%
{: local_path, : remote_path})
try:
sftp_client.put(local_path, remote_path)
except Exception as ex:
... | scp the local file to remote folder.
:param local_path: local path
:param remote_path: remote path |
12,261 | def add_handler(self, name=, level=, formatter=, **kwargs):
if name == and not in kwargs:
kwargs.update({: self.logfilename})
if name == and not in kwargs:
kwargs.update({: StringIO.StringIO()})
handler = types[name](**kwargs)
self... | Add another handler to the logging system if not present already.
Available handlers are currently: ['console-bw', 'console-color', 'rotating-log'] |
12,262 | def splitext(self):
filename, ext = self.module.splitext(self)
return self._next_class(filename), ext | p.splitext() -> Return ``(p.stripext(), p.ext)``.
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from ``'.'`` to the end of the
last path segment. This has the property that if
``(a, b) == p.splitext... |
12,263 | def _compileRegExp(string, insensitive, minimal):
flags = 0
if insensitive:
flags = re.IGNORECASE
string = string.replace(, )
string = string.replace(, )
string = string.replace(, )
try:
return re.compile(string, flags)
except (... | Compile regular expression.
Python function, used by C code
NOTE minimal flag is not supported here, but supported on PCRE |
12,264 | def convert2geojson(jsonfile, src_srs, dst_srs, src_file):
if os.path.exists(jsonfile):
os.remove(jsonfile)
if sysstr == :
exepath = % sys.exec_prefix
else:
exepath = FileClass.get_executable_fullpath()
s = % (
exepath, ... | convert shapefile to geojson file |
12,265 | def get_token(self):
token = None
if self.token_path.exists():
with self.token_path.open() as token_file:
token = self.token_constructor(self.serializer.load(token_file))
self.token = token
return token | Retrieves the token from the File System
:return dict or None: The token if exists, None otherwise |
12,266 | def search():
pattern = flask.request.args.get(, "*").strip().lower()
collections = [c["name"].lower() for c in current_app.kwdb.get_collections()]
words = []
filters = []
if pattern.startswith("name:"):
pattern = pattern[5:].strip()
mode = "name"
else:
... | Show all keywords that match a pattern |
12,267 | def compute_stats2(arrayNR, stats, weights):
newshape = list(arrayNR.shape)
if newshape[1] != len(weights):
raise ValueError( %
(len(weights), newshape[1]))
newshape[1] = len(stats)
newarray = numpy.zeros(newshape, arrayNR.dtype)
data = [arrayNR[:, i] for i in... | :param arrayNR:
an array of (N, R) elements
:param stats:
a sequence of S statistic functions
:param weights:
a list of R weights
:returns:
an array of (N, S) elements |
12,268 | def generate_login(self, min_length=6, max_length=10, digits=True):
chars = string.ascii_lowercase
if digits:
chars += string.digits
length = random.randint(min_length, max_length)
return .join(random.choice(chars) for x in range(length)) | Generate string for email address login with defined length and
alphabet.
:param min_length: (optional) min login length.
Default value is ``6``.
:param max_length: (optional) max login length.
Default value is ``10``.
:param digits: (optional) use digits in login genera... |
12,269 | def delete_local_docker_cache(docker_tag):
history_cmd = [, , , docker_tag]
try:
image_ids_b = subprocess.check_output(history_cmd)
image_ids_str = image_ids_b.decode().strip()
layer_ids = [id.strip() for id in image_ids_str.split() if id != ]
delete_cmd = [, , , ]
... | Delete the local docker cache for the entire docker image chain
:param docker_tag: Docker tag
:return: None |
12,270 | def move(self, target):
if isinstance(target, Folder):
target_id = target.object_id
elif isinstance(target, Drive):
root_folder = target.get_root_folder()
if not root_folder:
return False
target_id = root_folder.objec... | Moves this DriveItem to another Folder.
Can't move between different Drives.
:param target: a Folder, Drive item or Item Id string.
If it's a drive the item will be moved to the root folder.
:type target: drive.Folder or DriveItem or str
:return: Success / Failure
:rtyp... |
12,271 | def _ring_2d(m, n):
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i // m) for i in range(n * m)]
ret = [(0, 0)]
for i in range(m // 2):
for j in range(1, n):
ret.append((... | Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs |
12,272 | def vol_tetra(vt1, vt2, vt3, vt4):
vol_tetra = np.abs(np.dot((vt1 - vt4),
np.cross((vt2 - vt4), (vt3 - vt4)))) / 6
return vol_tetra | Calculate the volume of a tetrahedron, given the four vertices of vt1,
vt2, vt3 and vt4.
Args:
vt1 (array-like): coordinates of vertex 1.
vt2 (array-like): coordinates of vertex 2.
vt3 (array-like): coordinates of vertex 3.
vt4 (array-like): coordinates of vertex 4.
Returns:
... |
12,273 | def get_bgp_config(self, group="", neighbor=""):
bgp_config = {}
def build_prefix_limit(af_table, limit, prefix_percent, prefix_timeout):
prefix_limit = {}
inet = False
inet6 = False
preifx_type = "inet"
if isinstance(af_table, list)... | Parse BGP config params into a dict
:param group='':
:param neighbor='': |
12,274 | def get_core(self):
if self.maplesat and self.status == False:
return pysolvers.maplesat_core(self.maplesat) | Get an unsatisfiable core if the formula was previously
unsatisfied. |
12,275 | def _add_element(self, element, parent_node):
if element.tag == :
element_node_id = element.attrib[]++element.attrib[]
node_layers = {self.ns, self.ns+, self.ns++element.attrib[]}
elif element.tag == :
element_node_id = element.attrib[]+
node_laye... | add an element (i.e. a unit/connective/discourse or modifier)
to the docgraph. |
12,276 | def loadRecords(self, records):
self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
self._loaded = True
if records is None:
return
if self._nextLevels and RecordSet.typecheck(records):
level = self._nextLe... | Loads the inputed records as children to this item.
:param records | [<orb.Table>, ..] || {<str> sub: <variant>, .. } |
12,277 | def get_listing(path):
if path != ".":
listing = sorted([] + os.listdir(path))
else:
listing = sorted(os.listdir(path))
return listing | Returns the list of files and directories in a path.
Prepents a ".." (parent directory link) if path is not current dir. |
12,278 | def mins(self):
return np.array([self.x_min, self.y_min, self.z_min]) | Returns de minimum values of x, y, z as a numpy array |
12,279 | def find_vulnerabilities(
cfg_list,
blackbox_mapping_file,
sources_and_sinks_file,
interactive=False,
nosec_lines=defaultdict(set)
):
vulnerabilities = list()
definitions = parse(sources_and_sinks_file)
with open(blackbox_mapping_file) as infile:
blackbox_mapping = json.loa... | Find vulnerabilities in a list of CFGs from a trigger_word_file.
Args:
cfg_list(list[CFG]): the list of CFGs to scan.
blackbox_mapping_file(str)
sources_and_sinks_file(str)
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
Returns... |
12,280 | def raw(self, from_, to, body):
if isinstance(to, string_types):
raise TypeError()
return self._session.post(.format(self._url), json={
: from_,
: to,
: body,
}).json() | Send a raw MIME message. |
12,281 | def absent(name, user=None, signal=None):
ret = {: name,
: {},
: False,
: }
if __opts__[]:
running = __salt__[](name, user=user)
ret[] = None
if running:
ret[] = (
).format(len(running))
else:
... | Ensures that the named command is not running.
name
The pattern to match.
user
The user to which the process belongs
signal
Signal to send to the process(es). |
12,282 | def multi_plot_time(DataArray, SubSampleN=1, units=, xlim=None, ylim=None, LabelArray=[], show_fig=True):
unit_prefix = units[:-1]
if LabelArray == []:
LabelArray = ["DataSet {}".format(i)
for i in _np.arange(0, len(DataArray), 1)]
fig = _plt.figure(figsize=properties[])
... | plot the time trace for multiple data sets on the same axes.
Parameters
----------
DataArray : array-like
array of DataObject instances for which to plot the PSDs
SubSampleN : int, optional
Number of intervals between points to remove (to sub-sample data so
that you effectively ... |
12,283 | def set_membership(self, membership):
_c_leiden._MutableVertexPartition_set_membership(self._partition, list(membership))
self._update_internal_membership() | Set membership. |
12,284 | def infer_shape(self, *args, **kwargs):
try:
res = self._infer_shape_impl(False, *args, **kwargs)
if res[1] is None:
arg_shapes, _, _ = self._infer_shape_impl(True, *args, **kwargs)
arg_names = self.list_arguments()
unknowns = []
... | Infers the shapes of all arguments and all outputs given the known shapes of
some arguments.
This function takes the known shapes of some arguments in either positional way
or keyword argument way as input. It returns a tuple of `None` values
if there is not enough information to deduce... |
12,285 | def get_below_threshold(umi_quals, quality_encoding, quality_filter_threshold):
umi_quals = [x - RANGES[quality_encoding][0] for x in map(ord, umi_quals)]
below_threshold = [x < quality_filter_threshold for x in umi_quals]
return below_threshold | test whether the umi_quals are below the threshold |
12,286 | def apply_patch(self, patch):
history_file = File(self.__history_file)
patches_history = history_file.cache() and [line.strip() for line in history_file.content] or []
if patch.uid not in patches_history:
LOGGER.debug("> Applying patch!".format(patch.name))
if... | Applies given patch.
:param patch: Patch.
:type patch: Patch
:return: Method success.
:rtype: bool |
12,287 | def log_state(self, state):
results = []
for field_idx, field in enumerate(self.fields):
parent, stat = None, state
for f in field:
parent, stat = stat, stat[f]
results.append(stat)
self.log(*results) | Gathers the stats from self.trainer.stats and passes them into
self.log, as a list |
12,288 | def sort_trigger_set(triggers, exclude_previous=True, say=None):
if say is None:
say = lambda x: x
trigger_object_list = []
for index, trig in enumerate(triggers):
if exclude_previous and trig[1]["previous"]:
continue
pattern = trig[0]
... | Sort a group of triggers in optimal sorting order.
The optimal sorting order is, briefly:
* Atomic triggers (containing nothing but plain words and alternation
groups) are on top, with triggers containing the most words coming
first. Triggers with equal word counts are sorted by length, and then
... |
12,289 | def cycle_app(parser, cmd, args):
parser.add_argument(, , type=int, default=4, help=)
parser.add_argument(, type=int, help=)
args = parser.parse_args(args)
return cycle(args.length, args.width) | Generate a de Bruijn sequence of a given length. |
12,290 | def get_env_dirs(self):
repo_dirs = next(os.walk(self.env_root))[1]
if in repo_dirs:
repo_dirs.remove()
return repo_dirs | Return list of directories in env_root. |
12,291 | def build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate:
if isinstance(pmids, str):
@edge_predicate
def pmid_exclusion_filter(data: EdgeData) -> bool:
return has_pubmed(data) and data[CITATION][CITATION_REFERENCE] != pmids
elif isinstance(pmids, Iterable):... | Fail for edges with citations whose references are one of the given PubMed identifiers.
:param pmids: A PubMed identifier or list of PubMed identifiers to filter against |
12,292 | def get_header(headers, name, default=None):
name = name.lower()
for header in headers:
if header[0].lower() == name:
return header[1]
return default | Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively. |
12,293 | def get_room_history(
self,
room_id,
oldest=None,
latest=datetime.now(),
inclusive=False,
count=20,
unreads=False,
**kwa... | Get various history of specific channel/room
:param room_id:
:param kwargs:
:return: |
12,294 | def _pquery(scheduler, data, ndata, ndim, leafsize,
x, nx, d, i, k, eps, p, dub, ierr):
try:
_data = shmem_as_nparray(data).reshape((ndata, ndim))
_x = shmem_as_nparray(x).reshape((nx, ndim))
_d = shmem_as_nparray(d).reshape((nx, k))
_i = shmem_as_nparray(i).reshape(... | Function that parallelly queries the K-D tree based on chunks of data returned by the scheduler |
12,295 | def validate(self, value):
try:
length = len(value)
except TypeError:
length = 0
if self.min_length is not None:
min_length = self.min_length() if callable(self.min_length) else self.min_length
if length < min_length:
rais... | Validate the length of a list.
:param value: List of values.
:raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than
minimum or greater than maximum. |
12,296 | def is_base64(string):
return (not re.match(, string)) and \
(len(string) % 4 == 0) and \
re.match(, string) | Determines whether or not a string is likely to
be base64 encoded binary nonsense |
12,297 | def efficiency(self):
mywaveunits = self.waveunits.name
self.convert()
wave = self.wave
thru = self.throughput
self.convert(mywaveunits)
ans = self.trapezoidIntegration(wave, thru/wave)
return ans | Calculate :ref:`pysynphot-formula-qtlam`.
Returns
-------
ans : float
Bandpass dimensionless efficiency. |
12,298 | def _save_trace(self):
stack_trace = stack()
try:
self.trace = []
for frm in stack_trace[5:]:
self.trace.insert(0, frm[1:])
finally:
del stack_trace | Save current stack trace as formatted string. |
12,299 | async def fire(self, name, payload=None, *,
dc=None, node=None, service=None, tag=None):
params = {
"dc": dc,
"node": extract_pattern(node),
"service": extract_pattern(service),
"tag": extract_pattern(tag)
}
payload = en... | Fires a new event
Parameters:
name (str): Event name
payload (Payload): Opaque data
node (Filter): Regular expression to filter by node name
service (Filter): Regular expression to filter by service
tag (Filter): Regular expression to filter by servic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.