Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,800 | def _old_epd_diffmags(coeff, fsv, fdv, fkv, xcc, ycc, bgv, bge, mag):
return -(coeff[0]*fsv**2. +
coeff[1]*fsv +
coeff[2]*fdv**2. +
coeff[3]*fdv +
coeff[4]*fkv**2. +
coeff[5]*fkv +
coeff[6] +
coeff[7]*fsv*fdv +
... | This calculates the difference in mags after EPD coefficients are
calculated.
final EPD mags = median(magseries) + epd_diffmags() |
340,801 | def nu(self):
rargon
return phase_select_property(phase=self.phase, l=self.nul, g=self.nug) | r'''Kinematic viscosity of the the chemical at its current temperature,
pressure, and phase in units of [m^2/s].
.. math::
\nu = \frac{\mu}{\rho}
Examples
--------
>>> Chemical('argon').nu
1.3846930410865003e-05 |
340,802 | def _expectation(p, kern, feat, none1, none2, nghp=None):
with params_as_tensors_for(kern, feat):
Xcov = kern._slice_cov(p.cov)
Z, Xmu = kern._slice(feat.Z, p.mu)
D = tf.shape(Xmu)[1]
if kern.ARD:
lengthscales = kern.lengthscales
else:
le... | Compute the expectation:
<K_{X, Z}>_p(X)
- K_{.,.} :: RBF kernel
:return: NxM |
340,803 | def unmute():
if system.get_name() == :
pass
elif system.get_name() == :
sp.Popen([, , ]).wait()
else:
if unix_is_pulseaudio_server():
sp.Popen([, , , , ,
, ]).wait()
else:
sp.Popen([, , , , ]).wait() | Unmute the volume.
Unmutes the system volume.
Note:
On some systems, volume is restored to its previous level after unmute, or set to 100. |
340,804 | def extend(self, **attributes):
for key, value in attributes.iteritems():
if not hasattr(self, key):
setattr(self, key, value) | Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance. |
340,805 | def _rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) | [True, True, False, True, False], 2 ->
[
[True, True],
[True, False],
[False, True],
[True, False],
] |
340,806 | def process_compile_entries(
processor, spec, entries, modpath_logger=None, targetpath_logger=None):
all_modpaths = {}
all_targets = {}
all_export_module_names = []
def update(base, fresh, logger):
if callable(logger):
for dupes in dict_update_overw... | The generalized raw spec entry process invocation loop. |
340,807 | def delete_relationship(
self,
entity1_ilx: str,
relationship_ilx: str,
entity2_ilx: str) -> dict:
entity1_data = self.get_entity(entity1_ilx)
if not entity1_data[]:
exit(
+ entity1_data +
)
relationship_data = s... | Adds relationship connection in Interlex
A relationship exists as 3 different parts:
1. entity with type term, cde, fde, or pde
2. entity with type relationship that connects entity1 to entity2
-> Has its' own meta data, so no value needed
3. entity with type... |
340,808 | def create(self, data):
try:
floyd_logger.info("Making create request to server...")
post_body = data.to_dict()
post_body["resumable"] = True
response = self.request("POST", self.url, json=post_body)
return response.json()
except BadRe... | Create a temporary directory for the tar file that will be removed at
the end of the operation. |
340,809 | def file_exists(original_file):
s3 = boto3.resource()
bucket_name, object_key = _parse_s3_file(original_file)
bucket = s3.Bucket(bucket_name)
bucket_iterator = bucket.objects.filter(Prefix=object_key)
bucket_list = [x for x in bucket_iterator]
logger.debug("Bucket List: {0}".format(", ".joi... | Validate the original file is in the S3 bucket |
340,810 | def list_platform_sets(server_url):
config = _get_asam_configuration(server_url)
if not config:
return False
url = config[]
data = {
: ,
}
auth = (
config[],
config[]
)
try:
html_content = _make_post_request(url, data, auth, verify=False)
... | To list all ASAM platform sets present on the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.list_platform_sets prov1.domain.com |
340,811 | async def execute_job(self):
self.execution_start = datetime.now()
if not self.can_be_executed:
return self._set_job_outputs(RunStatus.DID_NOT_RUN)
exe = self.get_exe_path()
dfile = self.write_dfile()
outfile = self.get_outfile(dfile)
o2 = ... | Execute the BMDS model and parse outputs if successful. |
340,812 | def os_forkpty_wrapper():
pid = None
prepare_to_fork_acquire()
try:
pid, fd = _orig_os_forkpty()
finally:
if pid == 0:
child_after_fork_release()
else:
parent_after_fork_release()
return pid, fd | Wraps os.forkpty() to run atfork handlers. |
340,813 | def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu",
password="", dialect="mysqldb"):
if os.path.exists(db):
db = "sqlite:///" + db
if self.db_regex.match(db):
self.db = self.url = db
self.dburl = db
self.... | internal: create a dburl from a set of parameters or the defaults on
this object |
340,814 | def safe_execfile_ipy(self, fname):
fname = os.path.abspath(os.path.expanduser(fname))
try:
with open(fname) as thefile:
pass
except:
warn( % fname)
return
| Like safe_execfile, but for .ipy files with IPython syntax.
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
.ipy extension. |
340,815 | def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
access_token = AccessToken(rand_str(), self.access_token_lifetime)
scope = current_scope or granted_scope
logger.debug(, scope)
authz_info = {
: int(time.time(... | Creates an access token bound to the subject identifier, client id and requested scope. |
340,816 | def _encrypt_request_bytes(request_bytes, key, iv):
cipher = Cipher.AES.new(key, Cipher.AES.MODE_CBC, iv)
request_bytes_padded = _pad_bytes(request_bytes)
return cipher.encrypt(request_bytes_padded) | :type request_bytes: bytes
:type key: bytes
:type iv: bytes
:rtype: bytes |
340,817 | def get_model_parser(top_rule, comments_model, **kwargs):
class TextXModelParser(Parser):
def __init__(self, *args, **kwargs):
super(TextXModelParser, self).__init__(*args, **kwargs)
self.parser_model = Sequence(
nodes=[top_r... | Creates model parser for the given language. |
340,818 | def scatter(obj, axis=-1, blocksize=None):
if hasattr(obj, ):
return obj.__distob_scatter__(axis, None, blocksize)
if distob._have_numpy and (isinstance(obj, np.ndarray) or
hasattr(type(obj), )):
return _scatter_ndarray(obj, axis, blocksize)
elif isinstance(obj, ... | Distribute obj or list to remote engines, returning proxy objects
Args:
obj: any python object, or list of objects
axis (int, optional): Can be used if scattering a numpy array,
specifying along which axis to split the array to distribute it. The
default is to split along the last axis.... |
340,819 | def _hexplot(matrix, fig, colormap):
umatrix_min = matrix.min()
umatrix_max = matrix.max()
n_rows, n_columns = matrix.shape
cmap = plt.get_cmap(colormap)
offsets = np.zeros((n_columns * n_rows, 2))
facecolors = []
for row in range(n_rows):
for col in range(n_columns):
... | Internal function to plot a hexagonal map. |
340,820 | def _get_image_link_target_from_file(dir_path, image_file, force_no_processing=False):
return _get_image_src_from_file(
dir_path, image_file, force_no_processing
)
return image_file | Get the value to be used as the href for links from thumbnail images. For
most image formats this will simply be the image file name itself. However,
some image formats (tif) are not natively displayable by many browsers and
therefore we must link to image data in another format.
@param {String} dir_pat... |
340,821 | def _get_Berger_data(verbose=True):
orbit91_pd, path = load_data_source(local_path = local_path,
remote_source_list = [threddspath, NCDCpath],
open_method = pd.read_csv,
open_method_kwargs = {: True, :1},
verbose=verbose,)
... | Read in the Berger and Loutre orbital table as a pandas dataframe, convert to xarray |
340,822 | def list_upgrades(refresh=True, **kwargs):
**
if salt.utils.data.is_true(refresh):
refresh_db(full=True)
upgrades = {}
lines = __salt__[]("/bin/pkg list -Huv").splitlines()
for line in lines:
upgrades[_ips_get_pkgname(line)] = _ips_get_pkgversion(line)
return upgrades | Lists all packages available for update.
When run in global zone, it reports only upgradable packages for the global
zone.
When run in non-global zone, it can report more upgradable packages than
``pkg update -vn``, because ``pkg update`` hides packages that require
newer version of ``pkg://solari... |
340,823 | def request_response(func: typing.Callable) -> ASGIApp:
is_coroutine = asyncio.iscoroutinefunction(func)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive=receive)
if is_coroutine:
response = await func(request)
else:
... | Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application. |
340,824 | def movie_lists(self, **kwargs):
path = self._get_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Gets the movie lists available from the API.
Returns:
A dict respresentation of the JSON returned from the API. |
340,825 | def concatenate(self, other, *args):
from . import objects
result = objects.concatenate(self, other, *args)
return result | Concatenate two or more ColorVisuals objects into a single object.
Parameters
-----------
other : ColorVisuals
Object to append
*args: ColorVisuals objects
Returns
-----------
result: ColorVisuals object containing information from current
... |
340,826 | def _node_to_model(tree_or_item, metadata=None, parent=None,
lucent_id=cnxepub.TRANSLUCENT_BINDER_ID):
if in tree_or_item:
tree = tree_or_item
binder = cnxepub.TranslucentBinder(metadata=tree)
for item in tree[]:
node = _node_to_model(item, paren... | Given a tree, parse to a set of models |
340,827 | def get_content_version(cls, abspath):
data = cls.get_content(abspath)
hasher = hashlib.md5()
mtime_data = format(cls.get_content_modified_time(abspath), "%Y-%m-%d %H:%M:%S")
hasher.update(mtime_data.encode())
if isinstance(data, bytes):
hasher.update(data... | Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1 |
340,828 | def get(self, user, password, endpoints):
now = time.time()
if isinstance(endpoints, str):
endpoints = [endpoints]
for ep in endpoints:
if ep not in self.pool:
continue
entry = self.pool[ep]
if (not entry.client.is... | Gets an existing connection or opens a new one |
340,829 | def uninstall(ctx, yes, services):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for service in services:
service_path = plugin_utils.get_plugin_path(home, SERVICES, serv... | Uninstall a service. |
340,830 | def clear(self):
dict.clear(self)
self.nodes = []
self.edges = []
self.root = None
self.layout.i = 0
self.alpha = 0 | Remove nodes and edges and reset the layout. |
340,831 | def save(self):
if self.can_put and (not self.can_list or self.id):
categories = [elem for elem in self.findall("category")]
categories.extend([elem for elem in self.findall("category/name")])
for ... | Update or create a new object on the JSS.
If this object is not yet on the JSS, this method will create
a new object with POST, otherwise, it will try to update the
existing object with PUT.
Data validation is up to the client; The JSS in most cases will
at least give you some ... |
340,832 | def Is64bit(self):
if "64" not in platform.machine():
return False
iswow64 = ctypes.c_bool(False)
if IsWow64Process is None:
return False
if not IsWow64Process(self.h_process, ctypes.byref(iswow64)):
raise process_error.ProcessError("Error while calling IsWow64Process.")
retur... | Returns true if this is a 64 bit process. |
340,833 | def whois_emails(self, emails):
api_name =
fmt_url_path = u
return self._multi_get(api_name, fmt_url_path, emails) | Calls WHOIS Email end point
Args:
emails: An enumerable of string Emails
Returns:
A dict of {email: domain_result} |
340,834 | def off(self):
self.win.keypad(0)
curses.nocbreak()
curses.echo()
try:
curses.curs_set(1)
except:
pass
curses.endwin() | Turn off curses |
340,835 | def handle_debug_break(self, call_id, payload):
line = payload[]
config = self.launcher.config
path = os.path.relpath(payload[], config[])
self.editor.raw_message(feedback[].format(line, path))
self.debug_thread_id = payload["threadId"] | Handle responses `DebugBreakEvent`. |
340,836 | def is_active(self):
if self._queue.exhausted:
return False
return any(ch.is_active for ch in self._refs.values()) | Returns True if listener has any active subscription. |
340,837 | def read_geo(self, key, info):
pairs = {(, ):
("SatelliteAzimuthAngle", "SatelliteZenithAngle"),
(, ):
("SolarAzimuthAngle", "SolarZenithAngle"),
(, ):
("SolarAzimuthAngle", "SolarZenithAngle"),
(, ):
... | Read angles. |
340,838 | def record(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return b + struct.pack(, RRSPRecord.length(), SU_ENTRY_VERSION, 0xbe, 0xef, self.bytes_to_skip) | Generate a string representing the Rock Ridge Sharing Protocol record.
Parameters:
None.
Returns:
String containing the Rock Ridge record. |
340,839 | def log_in(self, username, password):
self.resource.credentials = (username, password)
return self.resource.get_json("_session")[2] | Logs in to the CouchDB instance with the credentials `username` and
`password` |
340,840 | def by_prefix(self,
prefix,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
return self.query(
prefix=prefix,
sort_by=sort_by,... | Search zipcode information by first N digits.
Returns multiple results. |
340,841 | def read_frame(self):
ret, frame = self.capture.read()
if not ret:
self.event_source.stop()
try:
self.capture.release()
except AttributeError:
pass
return None
if self.convert_color != -1 an... | Reads a frame and converts the color if needed.
In case no frame is available, i.e. self.capture.read() returns False
as the first return value, the event_source of the TimedAnimation is
stopped, and if possible the capture source released.
Returns:
None if stopped, otherwi... |
340,842 | def add(self, key, item):
mmkeys = self.mmkeys
if mmkeys is not None and not (key in self.data):
lenkey = len(key)
start = min(self.minkeylength,lenkey)
mmkeysGet = mmkeys.setdefault
for i in range(start,lenk... | Add a new key/item pair to the dictionary. Resets an existing
key value only if this is an exact match to a known key. |
340,843 | def _Open(self, path_spec=None, mode=):
if not path_spec:
raise ValueError()
file_system = resolver.Resolver.OpenFileSystem(
path_spec, resolver_context=self._resolver_context)
file_entry = file_system.GetFileEntryByPathSpec(path_spec)
if not file_entry:
file_system.Close()
... | Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSErro... |
340,844 | def _pstoref16(ins):
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] ==
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
I += 4
output = _f16_oper(value)
if indirect:
output.append( % I)
output.append()
REQUIRES.... | Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer. |
340,845 | def __update_window(self, width, height, message_no, page_no):
file_exists_label =
if not os.path.exists(self.__create_file_name(message_no)):
file_exists_label =
if PLATFORM == :
for _ in range(50):
print
... | Update the window with the menu and the new text |
340,846 | def dictmerge(a, b, name=None):
key = None
if b is None:
return a
try:
if a is None or isinstance(a, (bytes, int, str, float)):
a = b
elif isinstance(a, list):
if isinstance(b, list):
a.extend(... | Deeply merge two ``dict``s that consist of lists, dicts, and scalars.
This function (recursively) merges ``b`` INTO ``a``, does not copy any values, and returns ``a``.
based on https://stackoverflow.com/a/15836901/5042831
NOTE: tuples and arbitrary objects are NOT handled and will raise TypeError |
340,847 | def deactivate_object(brain_or_object):
obj = get_object(brain_or_object)
if is_root(obj):
fail(401, "Deactivating the Portal is not allowed")
try:
do_transition_for(brain_or_object, "deactivate")
except Unauthorized:
fail(401, "Not allowed to deactivate object " % obj.... | Deactivate the given object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Nothing
:rtype: None |
340,848 | def _perform_request(self, request, parser=None, parser_args=None, operation_context=None):
operation_context = operation_context or _OperationContext()
retry_context = RetryContext()
retry_context.is_emulated = self.is_emulated
self._apply_host(request, operation_cont... | Sends the request and return response. Catches HTTPError and hands it
to error handler |
340,849 | def split_lists(d, split_keys, new_name=,
check_length=True, deepcopy=True):
flattened = flatten2d(d)
new_d = {}
for key, value in flattened.items():
if set(split_keys).issubset(value.keys()):
combine_d = []
sub_d = {}
length =... | split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
top level key for split items
check_length : bool
if true, raise error if ... |
340,850 | def gen_csv(sc, filename, field_list, source, filters):
datafile = open(filename, )
csvfile = csv.writer(datafile)
header = []
for field in field_list:
header.append(fields.fields[field][])
csvfile.writerow(header)
debug.write( % filename)
datafile.cl... | csv SecurityCenterObj, AssetListName, CSVFields, EmailAddress |
340,851 | def trec_dataset(directory=,
train=False,
test=False,
train_filename=,
test_filename=,
check_files=[],
urls=[
,
],
fine_grained=False):
... | Load the Text REtrieval Conference (TREC) Question Classification dataset.
TREC dataset contains 5500 labeled questions in training set and another 500 for test set. The
dataset has 6 labels, 50 level-2 labels. Average length of each sentence is 10, vocabulary size
of 8700.
References:
* https... |
340,852 | async def ResolveUnitErrors(self, all_, retry, tags):
_params = dict()
msg = dict(type=,
request=,
version=8,
params=_params)
_params[] = all_
_params[] = retry
_params[] = tags
reply = await self.... | all_ : bool
retry : bool
tags : Entities
Returns -> typing.Sequence[~ErrorResult] |
340,853 | def simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, grid_size=(80, 80), model="projection",
pixel_size=None, center=None):
if isinstance(grid_size, numbers.Integral):
grid_size = (grid_size, grid_size)
if pixel_size is None:
... | Simulate scattering at a sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the object
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of the imaging light... |
340,854 | def get_actions(self, action_name, config_name, instances=None, map_name=None, **kwargs):
policy = self.get_policy()
action_generator = self.get_action_generator(action_name, policy, kwargs)
for state in self.get_states(action_name, config_name, instances=instances, map_name=map_name, *... | Returns the entire set of actions performed for the indicated action name.
:param action_name: Action name.
:type action_name: unicode | str
:param config_name: Name(s) of container configuration(s) or MapConfigId tuple(s).
:type config_name: unicode | str | collections.Iterable[unicode... |
340,855 | def reset(self):
self.__path = None
self.__repo = {: str(uuid.uuid1()),
: time.time(),
: None,
: str(__version__),
: ,
: []} | Reset repository instance. |
340,856 | def sales_payment_summary():
def value_or_zero(aggregate, key):
return aggregate[key] or 0
def sum_amount(payment_set):
a = payment_set.values("amount").aggregate(total=Sum("amount"))
return value_or_zero(a, "total")
headings = ["Category", "Total"]
data = []
sa... | Summarises paid items and payments. |
340,857 | def initialize_vocabulary(vocabulary_path):
if gfile.Exists(vocabulary_path):
rev_vocab = []
with gfile.GFile(vocabulary_path, mode="rb") as f:
rev_vocab.extend(f.readlines())
rev_vocab = [tf.compat.as_bytes(line.strip()) for line in rev_vocab]
vocab = dict([(x, y) f... | Initialize vocabulary from file, return the `word_to_id` (dictionary)
and `id_to_word` (list).
We assume the vocabulary is stored one-item-per-line, so a file will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"].
Parameters
-------... |
340,858 | def validate_schema(sconf):
if not in sconf:
raise exc.ConfigError()
if not in sconf:
raise exc.ConfigError()
for window in sconf[]:
if not in window:
raise exc.ConfigError()
if not in window:
raise exc.ConfigError(
%... | Return True if config schema is correct.
Parameters
----------
sconf : dict
session configuration
Returns
-------
bool |
340,859 | def create_router_on_eos(self, router_name, rdm, server):
cmds = []
rd = "%s:%s" % (rdm, rdm)
for c in self.routerDict[]:
cmds.append(c.format(router_name, rd))
if self._mlag_configured:
mac = VIRTUAL_ROUTER_MAC
for c in self._additionalRout... | Creates a router on Arista HW Device.
:param router_name: globally unique identifier for router/VRF
:param rdm: A value generated by hashing router name
:param server: Server endpoint on the Arista switch to be configured |
340,860 | def prettyjson(json, indentation=):
if isinstance(json, int) or isinstance(json, float):
return str(json)
elif isinstance(json, str):
if in json:
return
return repr(json)
elif isinstance(json, list):
lst = [indent(prettyjson(el, indentation), indentation) f... | Formats a Python-object into a string in a JSON like way, but
uses triple quotes for multiline strings.
PARAMETERS:
json -- Python object that is serializable into json.
indentation -- str; represents one level of indentation
NOTES:
All multiline strings are treated as raw strings.
... |
340,861 | def almost_identity(gate: Gate) -> bool:
N = gate.qubit_nb
return np.allclose(asarray(gate.asoperator()), np.eye(2**N)) | Return true if gate tensor is (almost) the identity |
340,862 | def _load(self, data):
self.raw_data = data
self.id = data[]
self.reference_id = data[]
self.name = data[]
self.short_description = data[]
self.thumbnail_url = data[]
self.videos = []
self.video_ids = data[]
self.type = data[]
for... | Internal method that deserializes a ``pybrightcove.playlist.Playlist``
object. |
340,863 | def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers):
for container in containers:
files = glob.glob( os.path.join( sourceDir, container, container + + suffix ) )
for currentFile in sorted( files ):
fix_header_comment( currentFile, timestamp ) | Fixes files used as input when pre-processing MPL-containers in their numbered form. |
340,864 | def __process_by_ccore(self):
(self.__clusters, self.__noise, block_logical_locations, block_max_corners, block_min_corners, block_points) = \
wrapper.clique(self.__data, self.__amount_intervals, self.__density_threshold)
amount_cells = len(block_logical_locations)
fo... | !
@brief Performs cluster analysis using C++ implementation of CLIQUE algorithm that is used by default if
user's target platform is supported. |
340,865 | def is_dev_version(cls):
command = "git branch"
command_result = Command(command).execute()
for branch in command_result.split("\n"):
if branch.startswith("*") and "dev" in branch:
... | Check if the current branch is `dev`. |
340,866 | def _new_mem_buf(buffer=None):
if buffer is None:
bio = _lib.BIO_new(_lib.BIO_s_mem())
free = _lib.BIO_free
else:
data = _ffi.new("char[]", buffer)
bio = _lib.BIO_new_mem_buf(data, len(buffer))
def free(bio, ref=data):
return _lib.BIO_free(bio)
... | Allocate a new OpenSSL memory BIO.
Arrange for the garbage collector to clean it up automatically.
:param buffer: None or some bytes to use to put into the BIO so that they
can be read out. |
340,867 | def get_environ(keys):
items = ((k, os.environ.get(k)) for k in keys)
subenv = dict((k, v) for (k, v) in items if v is not None)
needset = lambda k: k in keys and not subenv.get(k)
def setifnonempty(key, value):
if value:
subenv[key] = value
if needset():
import pl... | Get environment variables from :data:`os.environ`.
:type keys: [str]
:rtype: dict
Some additional features.
* If 'HOST' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`platform.node`.
* If 'TTY' is not in :data:`os.environ`, this function
automatically ... |
340,868 | def img2img_transformer_base():
hparams = image_transformer2d_base()
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.learning_rate = 0.2
hparams.layer_prepostprocess_dropout = 0.1
hparams.learning_rate_warmup_steps = 12000
hparams.filter_size = 2048
hpa... | Base params for local1d attention. |
340,869 | def to_stata(self, fname, convert_dates=None, write_index=True,
encoding="latin-1", byteorder=None, time_stamp=None,
data_label=None, variable_labels=None, version=114,
convert_strl=None):
kwargs = {}
if version not in (114, 117):
r... | Export DataFrame object to Stata dta format.
Writes the DataFrame to a Stata dataset file.
"dta" files contain a Stata dataset.
Parameters
----------
fname : str, buffer or path object
String, path object (pathlib.Path or py._path.local.LocalPath) or
obj... |
340,870 | def autozoom(self, n=None):
if n==None:
for p in self.plot_widgets: p.autoRange()
else: self.plot_widgets[n].autoRange()
return self | Auto-scales the axes to fit all the data in plot index n. If n == None,
auto-scale everyone. |
340,871 | def constructFMIndex(self, logger):
ACC$C$CAd end up with this:
BWT FM-index
C 0 0 0
$ 0 0 1
C 1 0 1
A 1 0 2
1 1 2
This is necessary for finding the occurrence of a letter using the getOccurrenceOfCharAtInd... | This function iterates through the BWT and counts the letters as it goes to create the FM index. For example, the string 'ACC$' would have BWT
'C$CA'. The FM index would iterate over this and count the occurence of the letter it found so you'd end up with this:
BWT FM-index
C 0 0 0... |
340,872 | def progress_indicator(self, fmt=None, interval=100, values=None):
return ProgressIndicator(self.io, fmt, interval, values) | Creates a new progress indicator. |
340,873 | def cmd_crack_luhn(number):
number = number.replace(, )
unknown_count = number.count()
if not number.replace(, ).isdigit():
print(, file=sys.stderr)
sys.exit(1)
for n in range(10 ** unknown_count):
candidate = number
for item in .format(n, count=unknown_count):
... | Having known values for a Luhn validated number, obtain the possible unknown numbers.
Numbers that use the Luhn algorithm for validation are Credit Cards, IMEI,
National Provider Identifier in the United States, Canadian Social
Insurance Numbers, Israel ID Numbers and Greek Social Security Numbers (ΑΜΚΑ).
... |
340,874 | def cb_list_groups(self, *args, **kwargs):
for check in self.linter.get_checker_names():
print(check)
sys.exit(0) | List all the check groups that pylint knows about
These should be useful to know what check groups someone can disable
or enable. |
340,875 | def get_json(self, prettyprint=False, translate=True):
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = json.dumps(j, indent=2, separators=(,))
e... | Get the data in JSON form |
340,876 | def from_video(self, path):
frames = self.get_video_frames(path)
self.handle_type(frames)
return self | Read from videos |
340,877 | def _load_callwraps(packname, package):
global _callwraps
from acorn.config import settings
from acorn.logging.descriptors import _obj_getattr
spack = settings(packname)
if spack is not None:
if spack.has_section("callwrap"):
wrappings = dict(spack.items("callwrap"))
... | Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
packname (str): name of the package to get c... |
340,878 | def configuration():
defaults =
cfg = ConfigParser.SafeConfigParser()
cfg.readfp(io.BytesIO(defaults))
cfg.read([
,
os.path.expanduser(),
,
])
return cfg | Loads configuration from the file system. |
340,879 | def export(self, nidm_version, export_dir):
atts = (
(PROV[], NIDM_CONTRAST_MAP),
(NIDM_CONTRAST_NAME, self.name))
if not self.isderfrommap:
atts = atts + (
(NIDM_IN_COORDINATE_SPACE, self.coord_space.id),)
if self.label is ... | Create prov graph. |
340,880 | def enable_audio_video_cmd(param, enable):
cmd =
formats = [(, 3), (, 4)]
if param == :
formats.append((, 3))
for fmt, num in formats:
for i in range(num):
cmd += .format(
fmt, i, param, str(enable).lower())
return cmd | Return command to enable/disable all audio/video streams. |
340,881 | def com_google_fonts_check_family_win_ascent_and_descent(ttFont, vmetrics):
failed = False
if ttFont[].usWinAscent < vmetrics[]:
failed = True
yield FAIL, Message("ascent",
("OS/2.usWinAscent value"
" should be equal or greater than {}, but got"
... | Checking OS/2 usWinAscent & usWinDescent.
A font's winAscent and winDescent values should be greater than the
head table's yMax, abs(yMin) values. If they are less than these
values, clipping can occur on Windows platforms,
https://github.com/RedHatBrand/Overpass/issues/33
If the font includes tall/deep wri... |
340,882 | def set_pythonshell_font(self, font=None):
if font is None:
font = QFont()
for style in self.font_styles:
style.apply_style(font=font,
is_default=style is self.default_style)
self.ansi_handler.set_base_format(self.default_style.forma... | Python Shell only |
340,883 | def create_from_axis_angle(cls, angle, ax, ay, az, degrees=False):
if degrees:
angle = np.radians(angle)
while angle < 0:
angle += np.pi*2
angle2 = angle/2.0
sinang2 = np.sin(angle2)
return Quaternion(np.cos(angle2), ax*sinang2, ay*sinang2, az*sin... | Classmethod to create a quaternion from an axis-angle representation.
(angle should be in radians). |
340,884 | def import_process_template_status(self, id):
route_values = {}
if id is not None:
route_values[] = self._serialize.url(, id, )
route_values[] =
response = self._send(http_method=,
location_id=,
version=,
... | ImportProcessTemplateStatus.
[Preview API] Tells whether promote has completed for the specified promote job ID.
:param str id: The ID of the promote job operation
:rtype: :class:`<ProcessPromoteStatus> <azure.devops.v5_0.work_item_tracking_process_template.models.ProcessPromoteStatus>` |
340,885 | def _maybe_run_matchers(self, text, run_matchers):
if run_matchers is True or \
(run_matchers is not False and text not in self._overlayed_already):
text.overlay(self.matchers)
self._overlayed_already.append(text) | OverlayedText should be smart enough to not run twice the same
matchers but this is an extra handle of control over that. |
340,886 | def from_json_dict(cls,
json_dict
):
result = cast(EnumSpec,
super().from_json_dict(json_dict))
format_ = json_dict[]
result.values = set(format_[])
return result | Make a EnumSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'enum'` key specifying the permitted values. In
addition, it must contain a `'hashing'` key, whose
contents are passed to :... |
340,887 | def get_index_range(blockchain_name, blockchain_client, impl, working_dir):
start_block = config.get_first_block_id(impl)
try:
current_block = get_blockchain_height(blockchain_name, blockchain_client)
except Exception, e:
log.exception(e)
return None, None
saved_block = St... | Get the range of block numbers that we need to fetch from the blockchain.
Requires virtualchain to have been configured with setup_virtualchain() if impl=None
Return None, None if we fail to connect to the blockchain |
340,888 | def sortBy(self, keyfunc, ascending=True, numPartitions=None):
return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values() | Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()
[('a', 1), ('b', ... |
340,889 | def geometrize_shapes(
shapes: DataFrame, *, use_utm: bool = False
) -> DataFrame:
import geopandas as gpd
f = shapes.copy().sort_values(["shape_id", "shape_pt_sequence"])
def my_agg(group):
d = {}
d["geometry"] = sg.LineString(
group[["shape_pt_lon", "shape_pt_lat"]].... | Given a GTFS shapes DataFrame, convert it to a GeoPandas
GeoDataFrame and return the result.
The result has a ``'geometry'`` column of WGS84 LineStrings
instead of the columns ``'shape_pt_sequence'``, ``'shape_pt_lon'``,
``'shape_pt_lat'``, and ``'shape_dist_traveled'``.
If ``use_utm``, then use loc... |
340,890 | def with_timestamps(self, created_at=None, updated_at=None):
if not created_at:
created_at = self.created_at()
if not updated_at:
updated_at = self.updated_at()
return self.with_pivot(created_at, updated_at) | Specify that the pivot table has creation and update columns. |
340,891 | def reload(self):
self._source = self._fetch_secrets(self._vault_url, self._path, self._token) | Reread secrets from the vault path |
340,892 | def edisp_disable_list(self):
l = []
for model_comp in self.model_components.values():
if model_comp.edisp_disable:
l += [model_comp.info.source_name]
return l | Return the list of source for which energy dispersion should be turned off |
340,893 | def get_hosts_dict(self) -> Dict:
return {
k: deserializer.inventory.InventoryElement.serialize(v).dict()
for k, v in self.hosts.items()
} | Returns serialized dictionary of hosts from inventory |
340,894 | def uncomment_lines(lines):
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups()
ret.append(ws_prefix + rest)
return .join(ret) | Uncomment the given list of lines and return them. The first hash mark
following any amount of whitespace will be removed on each line. |
340,895 | def event_listeners(self):
return (self.__command_listeners[:],
self.__server_heartbeat_listeners[:],
self.__server_listeners[:],
self.__topology_listeners[:]) | List of registered event listeners. |
340,896 | def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
pass_manager = PassManager()
pass_manager.property_set[] = initial_layout
pass_manager.append(Unroller(basis_gates))
pass_manager.append(TrivialLayout(coupling_map),
condition=lambda... | The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
... |
340,897 | def cumulate(self, axis):
axis = self.get_axis_number(axis)
return Histdd.from_histogram(np.cumsum(self.histogram, axis=axis),
bin_edges=self.bin_edges,
axis_names=self.axis_names) | Returns new histogram with all data cumulated along axis. |
340,898 | def safequote_restbase(title):
try:
return quote(title.encode(), safe=)
except UnicodeDecodeError:
return quote(title, safe=) | Safequote restbase title possibly having slash in title |
340,899 | def fetch(self, task_channel=values.unset):
return self._proxy.fetch(task_channel=task_channel, ) | Fetch a WorkspaceRealTimeStatisticsInstance
:param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel.
:returns: Fetched WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.