Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
364,700 | def set_up(self):
self.path.state = self.path.gen.joinpath("state")
if self.path.state.exists():
self.path.state.rmtree(ignore_errors=True)
self.path.state.mkdir()
for script in self.given.get("scripts", []):
script_path = self.path.state.joinpath(script... | Set up your applications and the test environment. |
364,701 | def distance_matrix(client, origins, destinations,
mode=None, language=None, avoid=None, units=None,
departure_time=None, arrival_time=None, transit_mode=None,
transit_routing_preference=None, traffic_model=None, region=None):
params = {
"ori... | Gets travel distance and time for a matrix of origins and destinations.
:param origins: One or more locations and/or latitude/longitude values,
from which to calculate distance and time. If you pass an address as
a string, the service will geocode the string and convert it to a
latitude/lon... |
364,702 | def check_views(view_set, max_views=3):
if not isinstance(view_set, Iterable):
view_set = tuple([view_set, ])
if len(view_set) > max_views:
raise ValueError(.format(max_views))
return [check_int(view, , min_value=0, max_value=max_views - 1) for view in view_set] | Ensures valid view/dimensions are selected. |
364,703 | def bindata(data, maxbins = 30, reduction = 0.1):
tole = 0.01
N = len(data)
assert N > 20
vmin = min(data)
vmax = max(data)
DV = vmax - vmin
tol = tole*DV
vmax += tol
if vmin >= 0:
vmin -= tol
vmin = max(0.0,vmin)
else:
vmin -= tol
n = min(maxbins... | data must be numeric list with a len above 20
This function counts the number of data points in a reduced array |
364,704 | def parse(self, string, parent, module=True, filepath=None):
if module:
result = self._parse_modules(string, parent, filepath)
else:
result = self._parse_programs(string, parent, filepath)
return result | Extracts modules *and* programs from a fortran code file.
:arg string: the contents of the fortran code file.
:arg parent: the instance of CodeParser that will own the return Module.
:arg module: when true, the code file will be searched for modules; otherwise
it will be searched for ... |
364,705 | def weibo_url(self):
if self.url is None:
return None
else:
tmp = self.soup.find(
, class_=)
return tmp[] if tmp is not None else | 获取用户微博链接.
:return: 微博链接地址,如没有则返回 ‘unknown’
:rtype: str |
364,706 | def removeRef(self, doc):
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlRemoveRef(doc__o, self._o)
return ret | Remove the given attribute from the Ref table maintained
internally. |
364,707 | def attached(name, force=False):
ret = {: name,
: {},
: None,
: }
zones = __salt__[](installed=True, configured=True)
if name in zones:
if zones[name][] == :
if __opts__[]:
res_attach = {: True}
else:
res_... | Ensure zone is attached
name : string
name of the zone
force : boolean
force attach the zone |
364,708 | def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, TM):
r
first_layer = lsrc == 0
last_layer = lsrc == depth.size-1
if lsrc != depth.size-1:
ds = depth[lsrc+1]-depth[lsrc]
dp = depth[lsrc+1]-zsrc
dm = zsrc-depth[lsrc]
Rmp = Rm
Rpm = Rp
if TM:
... | r"""Calculate Pu+, Pu-, Pd+, Pd-.
This is a modified version of empymod.kernel.fields(). See the original
version for more information. |
364,709 | def var_explained(y_true, y_pred):
y_true, y_pred = _mask_nan(y_true, y_pred)
var_resid = np.var(y_true - y_pred)
var_y_true = np.var(y_true)
return 1 - var_resid / var_y_true | Fraction of variance explained. |
364,710 | def get_flanker(group, query):
group.sort()
pos = bisect_left(group, (query, 0))
left_flanker = group[0] if pos == 0 else group[pos-1]
right_flanker = group[-1] if pos == len(group) else group[pos]
if abs(query - left_flanker[0]) < abs(query - right_flanker[0]):
flanker, other = le... | >>> get_flanker([(370, 15184), (372, 15178), (373, 15176), (400, 15193)], 385)
((373, 15176), (400, 15193), True)
>>> get_flanker([(124, 13639), (137, 13625)], 138)
((137, 13625), (137, 13625), False) |
364,711 | def set_link(self, prop, value):
if not isinstance(value, URIRef):
value = URIRef(value)
self.metadata.add(prop, value) | Set given link in CTS Namespace
.. example::
collection.set_link(NAMESPACES.CTS.about, "urn:cts:latinLit:phi1294.phi002")
:param prop: Property to set (Without namespace)
:param value: Value to set for given property |
364,712 | def _get_rsa_public_key(cert):
openssl_pkey = cert.get_pubkey()
openssl_lib = _util.binding.lib
ffi = _util.binding.ffi
buf = ffi.new("unsigned char **")
rsa = openssl_lib.EVP_PKEY_get1_RSA(openssl_pkey._pkey)
length = openssl_lib.i2d_RSAPublicKey(rsa, buf)
... | PyOpenSSL does not provide a public method to export the public key from a certificate as a properly formatted
ASN.1 RSAPublicKey structure. There are 'hacks' which use dump_privatekey(crypto.FILETYPE_ASN1, <public_key>),
but this dumps the public key within a PrivateKeyInfo structure which is not suita... |
364,713 | def run(self):
ReplicationLagLogger(self, 30).start()
LOG.debug("OplogThread: Run thread started")
while self.running is True:
LOG.debug("OplogThread: Getting cursor")
cursor, cursor_empty = retry_until_ok(self.init_cursor)
if last_ts is ... | Start the oplog worker. |
364,714 | def _contents(self):
stories = [
"ghosts.md",
"cricket.md",
"moochi.md",
"outwit.md",
"raid.md",
"species.md",
"tennis.md",
"vagabond.md"
]
story = random.choice(stories)
with open("s... | Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents(). |
364,715 | def patch_memcache():
def _init(self, servers, *k, **kw):
self._old_init(servers, *k, **kw)
nodes = {}
for server in self.servers:
conf = {
: server.ip,
: server,
: server.port,
: server.weight
}
... | Monkey patch python-memcached to implement our consistent hashring
in its node selection and operations. |
364,716 | def p_sens_all_paren(self, p):
p[0] = SensList(
(Sens(None, , lineno=p.lineno(1)),), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | senslist : AT LPAREN TIMES RPAREN |
364,717 | def handshake_peers(self):
pstr =
pstrlen = len(pstr)
info_hash = self.hash_string
peer_id = self.peer_id
packet = .join([chr(pstrlen), pstr, chr(0) * 8, info_hash,
peer_id])
print "Herem talking
... | pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string |
364,718 | def do_fit(self, event):
if event:
event.Skip()
self.main_sizer.Fit(self)
disp_size = wx.GetDisplaySize()
actual_size = self.GetSize()
rows = self.grid.GetNumberRows()
if disp_size[1] - 75 < actual_size[1]:
self.... | Re-fit the window to the size of the content. |
364,719 | def make_blastdb(self):
db = os.path.splitext(self.formattedprimers)[0]
nhr = .format(db=db)
if not os.path.isfile(str(nhr)):
command = \
.format(primerfile=self.formattedprimers,
outfile=db)
run_sub... | Create a BLAST database of the primer file |
364,720 | def inet_to_str(inet):
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueError:
return socket.inet_ntop(socket.AF_INET6, inet) | Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address |
364,721 | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
if depth == 0:
position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
self._initalize_tree(position, momentum, slice_var, direction * stepsi... | Recursively builds a tree for proposing new position and momentum |
364,722 | def add_edge_configuration(self, param_name, edge, param_value):
if param_name not in self.config[]:
self.config[][param_name] = {edge: param_value}
else:
self.config[][param_name][edge] = param_value | Set a parameter for a given edge
:param param_name: parameter identifier (as specified by the chosen model)
:param edge: edge identifier
:param param_value: parameter value |
364,723 | def _registered(self):
registry_domain = self._bindDomain(domain_name=,
create=False,
block=False)
if registry_domain is None:
return False
else:
for attempt i... | A optional boolean property indidcating whether this job store is registered. The
registry is the authority on deciding if a job store exists or not. If True, this job
store exists, if None the job store is transitioning from True to False or vice versa,
if False the job store doesn't exist.
... |
364,724 | def make_iterable(obj, default=None):
if obj is None:
return default or []
if isinstance(obj, (compat.string_types, compat.integer_types)):
return [obj]
return obj | Ensure obj is iterable. |
364,725 | def get_filename(self):
if self.filename is None or not os.path.exists(self.filename):
tf = tempfile.mktemp() + self._default_file_extension
self.save(tf)
yield tf
os.remove(tf)
else:
yield self.filename | Return the source filename of the current Stim. |
364,726 | def insert_attribute(self, att, index):
javabridge.call(self.jobject, "insertAttributeAt", "(Lweka/core/Attribute;I)V", att.jobject, index) | Inserts the attribute at the specified location.
:param att: the attribute to insert
:type att: Attribute
:param index: the index to insert the attribute at
:type index: int |
364,727 | def rmdir(self, pathobj):
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: " % str(pathobj))
url = str(pathobj) +
text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if code ... | Removes a directory |
364,728 | def _proc_pax(self, filetar):
buf = filetar.fileobj.read(self._block(self.size))
if self.type == tarfile.XGLTYPE:
pax_headers = filetar.pax_headers
else:
pax_headers = filetar.pax_headers.copy()
regex = re.compile(r"(\d+) ([^=]+)=", re.U)
... | Process an extended or global header as described in POSIX.1-2001. |
364,729 | def add(env, securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max, port_min, protocol):
mgr = SoftLayer.NetworkManager(env.client)
ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group,
direction, ethertype, port_max,
... | Add a security group rule to a security group.
\b
Examples:
# Add an SSH rule (TCP port 22) to a security group
slcli sg rule-add 384727 \\
--direction ingress \\
--protocol tcp \\
--port-min 22 \\
--port-max 22
\b
# Add a ping rule (... |
364,730 | def get_atlas_summary_df(self):
all_info = []
for g in self.reference_gempro.genes_with_a_representative_sequence:
info = {}
info[] = g.id
info[] = g.name
p = g.protein
info[] = len(p.sequences)
info[] = len(p... | Create a single data frame which summarizes all genes per row.
Returns:
DataFrame: Pandas DataFrame of the results |
364,731 | def extract(fileobj, keywords, comment_tags, options):
encoding = options.get(, )
original_position = fileobj.tell()
text = fileobj.read().decode(encoding)
if django.VERSION[:2] >= (1, 9):
tokens = Lexer(text).tokenize()
else:
tokens = Lexer(text, None).tokenize()
vars =... | Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, written according to
http://babel.pocoo.org/docs/messages/#wr... |
364,732 | def speakerDiarization(filename, n_speakers, mt_size=2.0, mt_step=0.2,
st_win=0.05, lda_dim=35, plot_res=False):
[fs, x] = audioBasicIO.readAudioFile(filename)
x = audioBasicIO.stereo2mono(x)
duration = len(x) / fs
[classifier_1, MEAN1, STD1, classNames1, mtWin1, mtStep1, s... | ARGUMENTS:
- filename: the name of the WAV file to be analyzed
- n_speakers the number of speakers (clusters) in the recording (<=0 for unknown)
- mt_size (opt) mid-term window size
- mt_step (opt) mid-term window step
- st_win (opt) short-term window size
... |
364,733 | def encode(self, X, seed=None):
if not X:
return
if not isinstance(X, str):
raise InvalidInputException()
if seed is not None and len(seed) != 8:
raise InvalidSeedLength(+str(len(seed)))
ciphertext = self._encrypter.encrypt(X)
ma... | Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n``
is the the maximum number of bytes that can be unranked w.r.t. the
capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input
``dfa``. |
364,734 | def log_tensor_stats(self, tensor, name):
if (isinstance(tensor, tuple) or isinstance(tensor, list)):
while (isinstance(tensor, tuple) or isinstance(tensor, list)) and (isinstance(tensor[0], tuple) or isinstance(tensor[0], list)):
tensor = [item for sublist in tens... | Add distribution statistics on a tensor's elements to the current History entry |
364,735 | def get(self, language: str=None, default: str=None) -> str:
language = language or settings.LANGUAGE_CODE
value = super().get(language, default)
return value if value is not None else default | Gets the underlying value in the specified or
primary language.
Arguments:
language:
The language to get the value in.
Returns:
The value in the current language, or
the primary language in case no language
was specified. |
364,736 | def _to_s(val, sep=", "):
if anyconfig.utils.is_iterable(val):
return sep.join(str(x) for x in val)
return str(val) | Convert any to string.
:param val: An object
:param sep: separator between values
>>> _to_s([1, 2, 3])
'1, 2, 3'
>>> _to_s("aaa")
'aaa' |
364,737 | def reset_statistics(stat, frequencies, reset_cumulative, recalculate=False):
stats = ensure_list(stat)
frequencies = ensure_list(frequencies)
for s in stats:
for f in frequencies:
if not s.cumulative or reset_cumulative:
print "Resetting %s (%s)..." % (s.__name__,... | Resets the specified statistic's data (deletes it) for the given
frequency/ies. |
364,738 | def GetPageInfo(self):
return self.first_tab, self.last_tab, self.first_tab, self.last_tab | Returns page information
What is the page range available, and what is the selected page range. |
364,739 | def reset(self):
self._undo_stack.clear()
self._spike_clusters = self._spike_clusters_base
self._new_cluster_id = self._new_cluster_id_0 | Reset the clustering to the original clustering.
All changes are lost. |
364,740 | def transform(self, X, y=None, sample_weight=None):
check_ts_data(X, y)
Xt, Xc = get_ts_data_parts(X)
yt = y
swt = sample_weight
N = len(Xt)
D = Xt[0].shape[1] - 1
t = [Xt[i][:, 0] for i in np.arange(N)]
t_lin = [np.arange(Xt[i][0, ... | Transforms the time series data with linear direct value interpolation
If y is a time series and passed, it will be transformed as well
The time dimension is removed from the data
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (option... |
364,741 | def exists(self, dataset_id):
from google.api_core.exceptions import NotFound
try:
self.client.get_dataset(self.client.dataset(dataset_id))
return True
except NotFound:
return False
except self.http_error as ex:
self.process_http_... | Check if a dataset exists in Google BigQuery
Parameters
----------
dataset_id : str
Name of dataset to be verified
Returns
-------
boolean
true if dataset exists, otherwise false |
364,742 | def copy_unit_spike_features(self, sorting, unit_ids=None):
if unit_ids is None:
unit_ids = sorting.get_unit_ids()
if isinstance(unit_ids, int):
curr_feature_names = sorting.get_unit_spike_feature_names(unit_id=unit_ids)
for curr_feature_name in curr_feature_... | Copy unit spike features from another sorting extractor to the current
sorting extractor.
Parameters
----------
sorting: SortingExtractor
The sorting extractor from which the spike features will be copied
unit_ids: (array_like, int)
The list (or single va... |
364,743 | def find_outputs_in_range(self, ifo, current_segment, useSplitLists=False):
currsegment_list = segments.segmentlist([current_segment])
overlap_files = self.find_all_output_in_range(ifo, current_segment,
useSplitLists=useSplitLists)
... | Return the list of Files that is most appropriate for the supplied
time range. That is, the Files whose coverage time has the
largest overlap with the supplied time range.
Parameters
-----------
ifo : string
Name of the ifo (or ifos) that the File should correspond to... |
364,744 | def save_info(self, dirn):
with current_directory(dirn):
info()
with open(, ) as fileh:
json.dump({: self.ctx.dist_name,
: self.ctx.bootstrap.name,
: [arch.arch for arch in self.ctx.archs],
... | Save information about the distribution in its dist_dir. |
364,745 | def direction(self):
libfn = utils.get_lib_fn(%self._libsuffix)
return libfn(self.pointer) | Get image direction
Returns
-------
tuple |
364,746 | def amplitude_by_welch(self, data_frame):
frq, Pxx_den = signal.welch(data_frame.filtered_signal.values, self.sampling_frequency, nperseg=self.window)
freq = frq[Pxx_den.argmax(axis=0)]
ampl = sum(Pxx_den[(frq > self.lower_frequency) & (frq < self.upper_frequency)])
logging.deb... | This methods uses the Welch method :cite:`Welch1967` to obtain the power spectral density, this is a robust
alternative to using fft_signal & amplitude
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return: the ampl
:rtype ampl: float
... |
364,747 | def X(self) -> Optional[Union[np.ndarray, sparse.spmatrix, ArrayView]]:
if self.isbacked:
if not self.file.isopen: self.file.open()
X = self.file[]
if self.isview:
X = X[self._oidx, self._vidx]
return X
else:
if self.n_... | Data matrix of shape :attr:`n_obs` × :attr:`n_vars`. |
364,748 | def run(self, lines):
text = "\n".join(lines)
while 1:
m = FENCED_BLOCK_RE.search(text)
if not m:
break
lang = m.group()
linenums = bool(m.group())
html = highlight_syntax(m.group(), lang, linenums=linenums)
... | Match and store Fenced Code Blocks in the HtmlStash. |
364,749 | def get_unique_filename(filename, new_filename=None, new_extension=None):
if new_extension:
extension = new_extension
else:
extension = splitext(filename)[1][1:]
if not new_filename:
now = real_datetime.now()
return % (unicode(now.hour).zfill(2), unicode(now.minute).zfi... | Génère un nouveau nom pour un fichier en gardant son extension
Soit le nouveau nom est généré à partir de la date
(heures+minutes+secondes+microsecondes) soit un nouveau nom est spécifié et on
l'utilise tel quel.
:type filename: string
:param filename: Nom du fichier original
:t... |
364,750 | def progressbar(stream, prefix=, width=0.5, **options):
size = len(stream)
if not size:
return stream
if not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options[] = width
with ProgressBar(max=size, prefix=prefix, **options) as... | Generator filter to print a progress bar. |
364,751 | def set_(key, value, profile=None):
if in key:
__utils__[](
,
(
),
)
path, key = key.split()
else:
path, key = key.rsplit(, 1)
try:
url = .format(path)
data = {key: value}
res... | Set a key/value pair in the vault service |
364,752 | def calcsize(values, sizerange=(2,70), inds=None, plaw=3):
if inds:
smax = max([abs(values[i]) for i in inds])
smin = min([abs(values[i]) for i in inds])
else:
smax = max([abs(val) for val in values])
smin = min([abs(val) for val in values])
return [sizerange[0] + sizer... | Use set of values to calculate symbol size.
values is a list of floats for candidate significance.
inds is an optional list of indexes to use to calculate symbol size.
Scaling of symbol size min max set by sizerange tuple (min, max).
plaw is powerlaw scaling of symbol size from values |
364,753 | def get_adaptive_threshold(threshold_method, image, threshold,
mask = None,
adaptive_window_size = 10,
**kwargs):
image_size = np.array(image.shape[:2],dtype=int)
nblocks = image_size // adaptive_window_size
... | Given a global threshold, compute a threshold per pixel
Break the image into blocks, computing the threshold per block.
Afterwards, constrain the block threshold to .7 T < t < 1.5 T.
Block sizes must be at least 50x50. Images > 500 x 500 get 10x10
blocks. |
364,754 | def _refreshNodeFromTarget(self):
for key, value in self.viewBox.state.items():
if key != "limits":
childItem = self.childByNodeName(key)
childItem.data = value
else:
for limitKey, limitValue in value.items():
... | Updates the config settings |
364,755 | def write(self, *args, **kwargs):
if args:
kwargs = dict(zip(self.header, args))
for header in kwargs:
cell = kwargs[header]
if not isinstance(cell, tuple):
cell = (cell,)
self.write_cell(self._row, self.header.index(header), *cel... | :param args: tuple(value, style), tuple(value, style)
:param kwargs: header=tuple(value, style), header=tuple(value, style)
:param args: value, value
:param kwargs: header=value, header=value |
364,756 | def inspect(self):
policy = self.policy
config_id = self.config_id
if self.config_id.config_type == ItemType.VOLUME:
if self.container_map.use_attached_parent_name:
container_name = policy.aname(config_id.map_name, config_id.instance_name, config_id.config_na... | Fetches information about the container from the client. |
364,757 | def top_x_bleu(query_dic, mark, x=1):
all_total = 0.0
with open(top_bleu_path + mark, ) as writer:
for k in query_dic:
candidate_lst = query_dic[k]
top_x = sorted(candidate_lst, key=lambda a: a[0], reverse=True)[:x]
total = 0
for t in top_x:
... | Calculate the top x average bleu value predictions ranking by item, x default is set above
:param query_dic: dict, key is qid, value is (item, bleu) tuple list, which will be ranked by 'item' as key
:param mark:string, which indicates which method is evaluated, also used as output file name here.
:param ... |
364,758 | def tt_avg(self, print_output=True, output_file="tt.csv"):
avg = self.tt.mean(axis=2)
if print_output:
np.savetxt(output_file, avg, delimiter=",")
return avg | Compute average term-topic matrix, and print to file if
print_output=True. |
364,759 | def is_done(self):
return self.position.is_game_over() or self.position.n >= FLAGS.max_game_length | True if the last two moves were Pass or if the position is at a move
greater than the max depth. |
364,760 | def remove_whitespace(s):
ignores = {}
for ignore in html_ignore_whitespace_re.finditer(s):
name = "{}{}{}".format(r"{}", uuid.uuid4(), r"{}")
ignores[name] = ignore.group()
s = s.replace(ignore.group(), name)
s = whitespace_re(r, s).strip()
for name, val in ignores.items():... | Unsafely attempts to remove HTML whitespace. This is not an HTML parser
which is why its considered 'unsafe', but it should work for most
implementations. Just use on at your own risk.
@s: #str
-> HTML with whitespace removed, ignoring <pre>, script, textarea and code
tags |
364,761 | def dispatch(self, request, *args, **kwargs):
self._add_next_and_user(request)
return super(DeleteImageView, self).dispatch(request, *args, **kwargs) | Adds useful objects to the class. |
364,762 | def all_terminated():
instances_found = False
for i in all_instances():
instances_found = True
if i.state not in (remote_dispatcher.STATE_TERMINATED,
remote_dispatcher.STATE_DEAD):
return False
return instances_found | For each remote shell determine if its terminated |
364,763 | def list(self):
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | List collection items. |
364,764 | def stream(self, page, limit=None, page_limit=None):
current_record = 1
current_page = 1
while page is not None:
for record in page:
yield record
current_record += 1
if limit and limit is not values.unset and limit < current_r... | Generates records one a time from a page, stopping at prescribed limits.
:param Page page: The page to stream.
:param int limit: The max number of records to read.
:param int page_imit: The max number of pages to read. |
364,765 | def populate_requirement_set(requirement_set, args, options, finder,
session, name, wheel_cache):
for req in args:
requirement_set.add_requirement(
InstallRequirement.from_line(
req, None, isolated=options.isolated_mode,
... | Marshal cmd line args into a requirement set. |
364,766 | def fill_superseqs(data, samples):
io5 = h5py.File(data.clust_database, )
superseqs = io5["seqs"]
splits = io5["splits"]
snames = [i.name for i in samples]
LOGGER.info("snames %s", snames)
maxlen = data._hackersonly["max_fragment_length"] + 20
LOGGER.info("maxlen insid... | Fills the superseqs array with seq data from cat.clust
and fill the edges array with information about paired split locations. |
364,767 | def lsp_server_ready(self, language, configuration):
for editorstack in self.editorstacks:
editorstack.notify_server_ready(language, configuration) | Notify all stackeditors about LSP server availability. |
364,768 | def relabel(self, label=None, group=None, depth=1):
return super(HoloMap, self).relabel(label=label, group=group, depth=depth) | Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to wh... |
364,769 | def terminate(self, signal_chain=KILL_CHAIN, kill_wait=KILL_WAIT_SEC, purge=True):
alive = self.is_alive()
if alive:
logger.debug(.format(self._name))
for signal_type in signal_chain:
pid = self.pid
try:
logger.debug(.format(signal_type, pid))
self._kill(sign... | Ensure a process is terminated by sending a chain of kill signals (SIGTERM, SIGKILL). |
364,770 | def _validate(self, writing=False):
if ((len(self.bits_per_component) != len(self.signed)) or
(len(self.signed) != self.palette.shape[1])):
msg = ("The length of the and the "
"members must equal the number of columns of the palette.")
self._... | Verify that the box obeys the specifications. |
364,771 | def keys(self, remote=False):
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() | Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote... |
364,772 | def quick_report(report_type, change, options):
report = report_type(None, options)
if options.output:
with open(options.output, "w") as out:
report.run(change, None, out)
else:
report.run(change, None, sys.stdout) | writes a change report via report_type to options.output or
sys.stdout |
364,773 | def _trj_check_version(self, version, python, force):
curr_python = pypetconstants.python_version_string
if (version != VERSION or curr_python != python) and not force:
raise pex.VersionMismatchError(
... | Checks for version mismatch
Raises a VersionMismatchError if version of loaded trajectory and current pypet version
do not match. In case of `force=True` error is not raised only a warning is emitted. |
364,774 | def add_debug(parser):
parser.add_argument(
, , action=, const=logging.DEBUG, default=logging.INFO, help=) | Add a `debug` flag to the _parser_. |
364,775 | def XXX_REMOVEME(func):
@wraps(func)
def decorator(self, *args, **kwargs):
msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format(
self.__class__.__name__, func.func_name)
raise RuntimeError(msg)
return func(self, *args, **kwargs)
return decorator | Decorator for dead code removal |
364,776 | def graph(self, as_dot=False):
if not self.has_graph:
return None
if not as_dot:
if self.graph_ is None:
self.graph_ = read_graph_from_string(self.graph_string)
return self.graph_
if self.graph_string:
if... | Get the resolve graph.
Args:
as_dot: If True, get the graph as a dot-language string. Otherwise,
a pygraph.digraph object is returned.
Returns:
A string or `pygraph.digraph` object, or None if there is no graph
associated with the resolve. |
364,777 | def get_disk_statistics(self):
result = {}
if os.access(, os.R_OK):
self.proc_diskstats = True
fp = open()
try:
for line in fp:
try:
columns = line.split()
... | Create a map of disks in the machine.
http://www.kernel.org/doc/Documentation/iostats.txt
Returns:
(major, minor) -> DiskStatistics(device, ...) |
364,778 | def dayname(year, month, day):
legal_date(year, month, day)
yearday = (month - 1) * 28 + day
if isleap(year + YEAR_EPOCH - 1):
dname = data.day_names_leap[yearday - 1]
else:
dname = data.day_names[yearday - 1]
return MONTHS[month - 1], dname | Give the name of the month and day for a given date.
Returns:
tuple month_name, day_name |
364,779 | def electric_field_amplitude_intensity(s0,Omega=1.0e6):
e0=hbar*Omega/(e*a0)
I0=2.50399
I0=1.66889451102868
I0=I0/1000*(100**2)
r_ciclic=4.226983616875483
gamma_D2=2*Pi*6.065e6/Omega
E0_sat=gamma_D2/r_ciclic/sqrt(2.0)
E0_sat=E0_sat*e0
I0=E0_sat**2/2/c/mu0
return sqrt(2*c*mu0*s0*I... | This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light. |
364,780 | def download(cls, filename, input_dir, dl_dir=None):
file_info = cls.parse_remote(filename)
if not dl_dir:
dl_dir = os.path.join(input_dir, file_info.bucket,
os.path.dirname(file_info.key))
utils.safe_makedir(dl_dir)
out_file = ... | Provide potentially streaming download from S3 using gof3r
or the AWS CLI. |
364,781 | def import_module(dotted_path):
import importlib
module_parts = dotted_path.split()
module_path = .join(module_parts[:-1])
module = importlib.import_module(module_path)
return getattr(module, module_parts[-1]) | Imports the specified module based on the
dot notated import path for the module. |
364,782 | def has_value(key, value=None):
*
if not isinstance(key, six.string_types):
log.debug(key\%s\, __name__, key)
return False
try:
cur_val = os.environ[key]
if value is not None:
if cur_val == value:
return True
else:
retur... | Determine whether the key exists in the current salt process
environment dictionary. Optionally compare the current value
of the environment against the supplied value string.
key
Must be a string. Used as key for environment lookup.
value:
Optional. If key exists in the environment, c... |
364,783 | def get_remembered_position(self):
if not self._able_to_format:
return self._original_position
accrued_input_index = 0
current_output_index = 0
while (accrued_input_index < self._position_to_remember and
current_output_index < len(self._current_output)... | Returns the current position in the partially formatted phone
number of the character which was previously passed in as the
parameter of input_digit(remember_position=True). |
364,784 | def getGolangPackages(self):
packages = {}
url = "%s/packages" % self.base_url
params = {"pattern": "golang-*", "limit": 200}
response = requests.get(url, params=params)
if response.status_code != requests.codes.ok:
return {}
data = response.json()
for package in data["packages"]:
packages[... | Get a list of all golang packages for all available branches |
364,785 | def catch(do, my_exception=TypeError, hints=, do_raise=None, prt_tb=True):
if not hasattr(do, ):
def dec(fn):
@wraps(fn)
def wrapper_(*args, **kwargs):
if not do:
return fn(*args, **kwargs)
try:
return fn(*... | 防止程序出现 exception后异常退出,
但是这里的异常捕获机制仅仅是为了防止程序退出, 无法做相应处理
可以支持有参数或者无参数模式
- ``do == True`` , 则启用捕获异常
- 无参数也启用 try-catch
.. code:: python
@catch
def fnc():
pass
- 在有可能出错的函数前添加, 不要在最外层添加,
- 这个catch 会捕获从该函数开始的所有异常, 会隐藏下一级函数调用的错误.
- 但是如果在内层的函数也有捕获... |
364,786 | def _ExtractPathSpecsFromDirectory(self, file_entry, depth=0):
if depth >= self._MAXIMUM_DEPTH:
raise errors.MaximumRecursionDepth()
| Extracts path specification from a directory.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the directory.
depth (Optional[int]): current depth where 0 represents the file system
root.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the directory... |
364,787 | def _check_lib(self, remake, compiler, debug, profile):
from os import path
if self.link is None or not path.isfile(self.link):
self.makelib(remake, True, compiler, debug, profile) | Makes sure that the linked library with the original code exists. If it doesn't
the library is compiled from scratch. |
364,788 | def winning_name(self):
if self.winner == HOME:
return self._home_name.text()
return self._away_name.text() | Returns a ``string`` of the winning team's name, such as 'Houston
Astros'. |
364,789 | def run(self, inputRecord):
predictionNumber = self._numPredictions
self._numPredictions += 1
result = opf_utils.ModelResult(predictionNumber=predictionNumber,
rawInput=inputRecord)
return result | Run one iteration of this model.
:param inputRecord: (object)
A record object formatted according to
:meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or
:meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict`
result format.
:returns: (:... |
364,790 | def shard_stores(self, index=None, params=None):
return self.transport.perform_request(
"GET", _make_path(index, "_shard_stores"), params=params
) | Provides store information for shard copies of indices. Store
information reports on which nodes shard copies exist, the shard copy
version, indicating how recent they are, and any exceptions encountered
while opening the shard index or from earlier engine failure.
`<http://www.elastic.c... |
364,791 | def save_template(self, name, unlocked=False):
if isinstance(unlocked, basestring):
unlocked = unlocked.lower() !=
template = self._get_message_template()
if not unlocked:
template.set_as_saved()
self._message_templates[name] = (template, self._field_val... | Save a message template for later use with `Load template`.
If saved template is marked as unlocked, then changes can be made to it
afterwards. By default tempaltes are locked.
Examples:
| Save Template | MyMessage |
| Save Template | MyOtherMessage | unlocked=True | |
364,792 | def toxml(self):
return +\
(.format(self.symbol) if self.symbol else ) +\
(.format(self.dimension) if self.dimension else ) +\
(.format(self.power) if self.power else ) +\
(.format(self.scale) if self.scale else ) +\
(.form... | Exports this object into a LEMS XML object |
364,793 | def __check_command_completion(self, testsemicolon=True):
if not self.__curcommand.iscomplete():
return True
ctype = self.__curcommand.get_type()
if ctype == "action" or \
(ctype == "control" and
not self.__curcommand.accept_children):
... | Check for command(s) completion
This function should be called each time a new argument is
seen by the parser in order to check a command is complete. As
not only one command can be ended when receiving a new
argument (nested commands case), we apply the same work to
parent comm... |
364,794 | def like(self):
r = requests.post(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header
)
return (r.json()) | Like a clip. |
364,795 | def _run(self, *args, **kwargs):
apgw_rpc_bind_ip = _validate_rpc_ip(kwargs.pop(NC_RPC_BIND_IP))
apgw_rpc_bind_port = _validate_rpc_port(kwargs.pop(NC_RPC_BIND_PORT))
sock_addr = (apgw_rpc_bind_ip, apgw_rpc_bind_port)
LOG.debug()
server_thread, _ = self._listen_tcp(soc... | Runs RPC server.
Wait for peer to connect and start rpc session with it.
For every connection we start and new rpc session. |
364,796 | def declare_type_info(config):
settings = config.registry.settings
settings[] = []
for line in settings[].splitlines():
if not line.strip():
continue
type_name, type_info = line.strip().split(, 1)
type_info = type_info.split(, 3)
settings[].append((type_name,... | Lookup type info from app configuration. |
364,797 | def add2node(self, othereplus, node):
node = node.upper()
self.dt[node.upper()] = self.dt[node.upper()] + \
othereplus.dt[node.upper()] | add the node here with the node from othereplus
this will potentially have duplicates |
364,798 | def __WaitForVolume(volume, desired_state):
print % (volume.id, desired_state)
while True:
volume.update()
sys.stdout.write()
sys.stdout.flush()
if volume.status == desired_state:
break
time.sleep(5)
return | Blocks until EBS volume is in desired state. |
364,799 | def create_user(self, username, email, password, active=False,
send_email=True):
new_user = get_user_model().objects.create_user(
username, email, password)
new_user.is_active = active
new_user.save()
for perm in ASSIGNED_PERMISSIONS[]:... | A simple wrapper that creates a new :class:`User`.
:param username:
String containing the username of the new user.
:param email:
String containing the email address of the new user.
:param password:
String containing the password for the new user.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.