Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
370,000 | def integrate(self, function, lower_bound, upper_bound):
ret = 0.0
n = self.nsteps
xStep = (float(upper_bound) - float(lower_bound)) / float(n)
self.log_info("xStep" + str(xStep))
x = lower_bound
val1 = function(x)
self.log_info("val1: " + str(val1))
... | Calculates the integral of the given one dimensional function
in the interval from lower_bound to upper_bound, with the simplex integration method. |
370,001 | def readlen(args):
p = OptionParser(readlen.__doc__)
p.set_firstN()
p.add_option("--silent", default=False, action="store_true",
help="Do not print read length stats")
p.add_option("--nocheck", default=False, action="store_true",
help="Do not check file type suffix... | %prog readlen fastqfile
Calculate read length, will only try the first N reads. Output min, max, and
avg for each file. |
370,002 | def fftw_normxcorr(templates, stream, pads, threaded=False, *args, **kwargs):
utilslib = _load_cdll()
argtypes = [
np.ctypeslib.ndpointer(dtype=np.float32, ndim=1,
flags=native_str()),
ctypes.c_long, ctypes.c_long,
np.ctypeslib.ndpointer(dtype=np.floa... | Normalised cross-correlation using the fftw library.
Internally this function used double precision numbers, which is definitely
required for seismic data. Cross-correlations are computed as the
inverse fft of the dot product of the ffts of the stream and the reversed,
normalised, templates. The cross... |
370,003 | def get_changes(self, fixer=str.lower,
task_handle=taskhandle.NullTaskHandle()):
stack = changestack.ChangeStack(self.project, )
jobset = task_handle.create_jobset(,
self._count_fixes(fixer) + 1)
try:
while True:... | Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name. |
370,004 | def memoize(f):
def _c(*args, **kwargs):
if not hasattr(f, ):
f.cache = dict()
key = (args, tuple(kwargs))
if key not in f.cache:
f.cache[key] = f(*args, **kwargs)
return f.cache[key]
return wraps(f)(_c) | Memoization decorator for a function taking one or more arguments. |
370,005 | def repack_all(self):
non_na_sequences = [s for s in self.sequences if not in s]
self.pack_new_sequences(non_na_sequences)
return | Repacks the side chains of all Polymers in the Assembly. |
370,006 | def to_bytes(self):
rXyZSomeDummyPayloadData\x88XyZ\x00\x04\xd2\x00SomeDummyPayloadData
self.sanitize()
bitstream = BitArray(
% (self.nonce is not None,
self.lsb is not None,
self.echo... | r'''
Create bytes from properties
>>> message = DataPacket(nonce='XyZ', instance_id=1234,
... payload='SomeDummyPayloadData')
>>> message.to_bytes()
'\x88XyZ\x00\x04\xd2\x00SomeDummyPayloadData' |
370,007 | def get_vlan_brief_output_vlan_interface_interface_type(self, **kwargs):
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan... | Auto Generated Code |
370,008 | def get_patient_pharmacies(self, patient_id,
patients_favorite_only=):
magic = self._magic_json(
action=TouchWorksMagicConstants.ACTION_GET_PATIENT_PHARAMCIES,
patient_id=patient_id,
parameter1=patients_favorite_only)
response =... | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response |
370,009 | def get_instance(self, payload):
return InviteInstance(
self._version,
payload,
service_sid=self._solution[],
channel_sid=self._solution[],
) | Build an instance of InviteInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance
:rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance |
370,010 | def begin_operation(self, conn_or_internal_id, op_name, callback, timeout):
data = {
: conn_or_internal_id,
: callback,
: op_name
}
action = ConnectionAction(, data, timeout=timeout, sync=False)
self._actions.put(action) | Begin an operation on a connection
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
op_name (string): The name of the operation that we are starting (stored in
the connection's microstate)
callba... |
370,011 | def insert(self, loc, item):
_self = np.asarray(self)
item = self._coerce_scalar_to_index(item)._ndarray_values
idx = np.concatenate((_self[:loc], item, _self[loc:]))
return self._shallow_copy_with_infer(idx) | Make new Index inserting new item at location.
Follows Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index |
370,012 | def getcwd(cls):
if not hasattr(cls._tl, "cwd"):
cls._tl.cwd = os.getcwd()
return cls._tl.cwd | Provide a context dependent current working directory. This method
will return the directory currently holding the lock. |
370,013 | def show_vcs_output_nodes_disconnected_from_cluster(self, **kwargs):
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
nodes_disconnected_from_cluster = ET.SubElement(output, "nodes-disconnected-f... | Auto Generated Code |
370,014 | def enable_digital_reporting(self, pin):
port = pin // 8
command = [self._command_handler.REPORT_DIGITAL + port, self.REPORTING_ENABLE]
self._command_handler.send_command(command) | Enables digital reporting. By turning reporting on for all 8 bits in the "port" -
this is part of Firmata's protocol specification.
:param pin: Pin and all pins for this port
:return: No return value |
370,015 | def __get_user(self, login):
user = {}
if not login:
return user
user_raw = self.client.user(login)
user = json.loads(user_raw)
user_orgs_raw = \
self.client.user_orgs(login)
user[] = json.loads(user_orgs_raw)
return user | Get user and org data for the login |
370,016 | def _remove_wrappers(self):
ansible_mitogen.loaders.action_loader.get = action_loader__get
ansible_mitogen.loaders.connection_loader.get = connection_loader__get
ansible.executor.process.worker.WorkerProcess.run = worker__run | Uninstall the PluginLoader monkey patches. |
370,017 | def addFeature(self, features,
gdbVersion=None,
rollbackOnFailure=True):
url = self._url + "/addFeatures"
params = {
"f" : "json"
}
if gdbVersion is not None:
params[] = gdbVersion
if isinstance(rollbackOnFail... | Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
list of dictionary objects
gdbVersion - Geodatabase version to apply the edits
... |
370,018 | def pprint(self, indent: str = , remove_comments=False):
warn(
,
DeprecationWarning,
)
return self.pformat(indent, remove_comments) | Deprecated, use self.pformat instead. |
370,019 | def on_entry_click(self, event):
if event.widget.config() [4] == :
event.widget.delete(0, "end" )
event.widget.insert(0, )
event.widget.config(fg = ) | function that gets called whenever entry is clicked |
370,020 | def _fmt_args_kwargs(self, *some_args, **some_kwargs):
if some_args:
out_args = str(some_args).lstrip().rstrip()
if some_kwargs:
out_kwargs = .join([str(i).lstrip().rstrip().replace(,) for i in [
(k,some_kwargs[k]) for k in sorted(some_kwargs.keys())]... | Helper to convert the given args and kwargs into a string. |
370,021 | def find_particles_in_tile(positions, tile):
bools = tile.contains(positions)
return np.arange(bools.size)[bools] | Finds the particles in a tile, as numpy.ndarray of ints.
Parameters
----------
positions : `numpy.ndarray`
[N,3] array of the particle positions to check in the tile
tile : :class:`peri.util.Tile` instance
Tile of the region inside which to check for particles.
Retu... |
370,022 | def _choose_port(self):
| Return a port number from 5000-5999 based on the environment name
to be used as a default when the user hasn't selected one. |
370,023 | def steam64_from_url(url, http_timeout=30):
match = re.match(r
r, url)
if not match:
return None
web = make_requests_session()
try:
if match.group() in (, ):
text = web.get(match.group(), timeout=http_timeout).text
data_match... | Takes a Steam Community url and returns steam64 or None
.. note::
Each call makes a http request to ``steamcommunity.com``
.. note::
For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api
:param url: steam community url
:type url: :class:`str`
:param h... |
370,024 | def tokenized(self, delimiter=, overlap_threshold=0.1):
sorted_by_start = sorted(self.labels)
tokens = []
last_label_end = None
for label in sorted_by_start:
if last_label_end is None or (last_label_end - label.start < overlap_threshold and last_label_end > 0):
... | Return a ordered list of tokens based on all labels.
Joins all token from all labels (``label.tokenized()```).
If the overlapping between two labels is greater than ``overlap_threshold``,
an Exception is thrown.
Args:
delimiter (str): The delimiter used to split labels into ... |
370,025 | async def post(self, public_key):
logging.debug("[+] -- Deal debugging. ")
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(400)
self.write({"error":400, "reason":"Unexpected data format. JSON required"})
raise tornado.w... | Accepting offer by buyer
Function accepts:
- cid
- buyer access string
- buyer public key
- seller public key |
370,026 | def shrink(self):
x = np.nan_to_num(self.X.values)
t, n = np.shape(x)
meanx = x.mean(axis=0)
x = x - np.tile(meanx, (t, 1))
xmkt = x.mean(axis=1).reshape(t, 1)
sample = np.cov(np.append(x, xmkt, axis=1), rowvar=False) * (t - 1) / t
cov... | Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray |
370,027 | def get_notification(self, id):
url = self._base_url + "/3/notification/{0}".format(id)
resp = self._send_request(url)
return Notification(resp, self) | Return a Notification object.
:param id: The id of the notification object to return. |
370,028 | def get_dag_configs(self) -> Dict[str, Dict[str, Any]]:
return {dag: self.config[dag] for dag in self.config.keys() if dag != "default"} | Returns configuration for each the DAG in factory
:returns: dict with configuration for dags |
370,029 | def get_connected(self):
connected = c_int32()
result = self.library.Cli_GetConnected(self.pointer, byref(connected))
check_error(result, context="client")
return bool(connected) | Returns the connection status
:returns: a boolean that indicates if connected. |
370,030 | def setValue(self, value):
self.__value = projex.text.decoded(value) if isinstance(value, (str, unicode)) else value | Sets the value that will be used for this query instance.
:param value <variant> |
370,031 | def history_file(self, location=None):
if location:
if os.path.exists(location):
return location
else:
logger.warn("The specified history file %s doesnCHANGESHISTORYCHANGELOGrsttxtmarkdown.'.join([base, extension]))
history = ... | Return history file location. |
370,032 | def create_key_ring(
self,
parent,
key_ring_id,
key_ring,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "create_key_ring" not in self._inner_api_calls:
... | Create a new ``KeyRing`` in a given Project and Location.
Example:
>>> from google.cloud import kms_v1
>>>
>>> client = kms_v1.KeyManagementServiceClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>... |
370,033 | def get_draw(self, index: Index, additional_key: Any=None) -> pd.Series:
if self._for_initialization:
draw = random(self._key(additional_key), pd.Index(range(len(index))), self.index_map)
draw.index = index
else:
draw = random(self._key(additional_key), index... | Get an indexed sequence of floats pulled from a uniform distribution over [0.0, 1.0)
Parameters
----------
index :
An index whose length is the number of random draws made
and which indexes the returned `pandas.Series`.
additional_key :
Any additional... |
370,034 | def _line_parse(line):
if line[-2:] in ["\r\n", b"\r\n"]:
return line[:-2], True
elif line[-1:] in ["\r", "\n", b"\r", b"\n"]:
return line[:-1], True
return line, False | Removes line ending characters and returns a tuple (`stripped_line`,
`is_terminated`). |
370,035 | def process(self):
client = self._get_client_by_hostname(self.host)
self._await_flow(client, self.flow_id)
collected_flow_data = self._download_files(client, self.flow_id)
if collected_flow_data:
print(.format(
self.flow_id, collected_flow_data))
fqdn = client.data.os_info.fqd... | Collect the results.
Raises:
DFTimewolfError: if no files specified |
370,036 | def getTemplate(self, uri, meta=None):
if not meta:
metaKey = self.cacheKey + + uri
meta = cache.get(metaKey, None)
if not meta:
meta = self.getMeta(uri)
cache.set(metaKey, meta, 15)
if not meta:
return None... | Return the template for an action. Cache the result. Can use an optional meta parameter with meta information |
370,037 | def get_account_holds(self, account_id, **kwargs):
endpoint = .format(account_id)
return self._send_paginated_message(endpoint, params=kwargs) | Get holds on an account.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Holds are placed on an account for active orders or
pending withdraw requests.
As an order is filled, the hold amount is updated. If an order
is c... |
370,038 | def os_change_list(self, subid, params=None):
params = update_params(params, {: subid})
return self.request(, params, ) | /v1/server/os_change_list
GET - account
Retrieves a list of operating systems to which this server can be
changed.
Link: https://www.vultr.com/api/#server_os_change_list |
370,039 | def load_nb(cls, inline=True):
with param.logging_level():
cls.notebook_context = True
cls.comm_manager = JupyterCommManager | Loads any resources required for display of plots
in the Jupyter notebook |
370,040 | def iterline(x1, y1, x2, y2):
xdiff = abs(x2-x1)
ydiff = abs(y2-y1)
xdir = 1 if x1 <= x2 else -1
ydir = 1 if y1 <= y2 else -1
r = math.ceil(max(xdiff, ydiff))
if r == 0:
yield x1, y1
else:
x, y = math.floor(x1), math.floor(y1)
i = 0
while i < r:
... | Yields (x, y) coords of line from (x1, y1) to (x2, y2) |
370,041 | def do_file_upload(client, args):
if len(args.paths) > 1:
try:
resource = client.get_resource_by_uri(args.dest_uri)
except ResourceNotFoundError:
resource = None
if resource and not isinstance(resource, Folder):
print("file-upload: "
... | Upload files |
370,042 | def save_parameters(self, path, grad_only=False):
params = self.get_parameters(grad_only=grad_only)
nn.save_parameters(path, params) | Save all parameters into a file with the specified format.
Currently hdf5 and protobuf formats are supported.
Args:
path : path or file object
grad_only (bool, optional): Return parameters with `need_grad` option as `True`. |
370,043 | def guess_sequence(redeem_script):
s not a constant before OP_CSV
OP_CHECKSEQUENCEVERIFY')
return int(script_array[loc - 1], 16)
except ValueError:
return 0xFFFFFFFE | str -> int
If OP_CSV is used, guess an appropriate sequence
Otherwise, disable RBF, but leave lock_time on.
Fails if there's not a constant before OP_CSV |
370,044 | def hook_key(key, callback, suppress=False):
_listener.start_if_necessary()
store = _listener.blocking_keys if suppress else _listener.nonblocking_keys
scan_codes = key_to_scan_codes(key)
for scan_code in scan_codes:
store[scan_code].append(callback)
def remove_():
del _hooks[c... | Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use `unhook_key(key)` or
`unhook_key(handler)`.
Note: this function shares state with hotkeys, so `clear_all_hotkeys`
affects it aswell. |
370,045 | def _checkup(peaks, ecg_integrated, sample_rate, rr_buffer, spk1, npk1, threshold):
peaks_amp = [ecg_integrated[peak] for peak in peaks]
definitive_peaks = []
for i, peak in enumerate(peaks):
amp = peaks_amp[i]
if amp > threshold:
definitive_peaks, spk1, r... | Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
s... |
370,046 | def zinnia_pagination(context, page, begin_pages=1, end_pages=1,
before_pages=2, after_pages=2,
template=):
get_string =
for key, value in context[].GET.items():
if key != :
get_string += % (key, value)
page_range = list(page.paginator.... | Return a Digg-like pagination,
by splitting long list of page into 3 blocks of pages. |
370,047 | def _get_repeat_masker_header(pairwise_alignment):
res = ""
res += str(pairwise_alignment.meta[ALIG_SCORE_KEY]) + " "
res += "{:.2f}".format(pairwise_alignment.meta[PCENT_SUBS_KEY]) + " "
res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S1_INDELS_KEY]) + " "
res += "{:.2f}".format(pairwise_alignment.me... | generate header string of repeatmasker formated repr of self. |
370,048 | def replace_project(self, owner, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_project_with_http_info(owner, id, **kwargs)
else:
(data) = self.replace_project_with_http_info(owner, id, **kwargs)
return data | Create / Replace a project
Create a project with a given id or completely rewrite the project, including any previously added files or linked datasets, if one already exists with the given id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please d... |
370,049 | def _apply_filters(self, **filters):
regexp = filters.pop(, False)
keep = np.array([True] * len(self.data))
for col, values in filters.items():
if values is None:
continue
if col in self.meta.columns:
matche... | Determine rows to keep in data for given set of filters
Parameters
----------
filters: dict
dictionary of filters ({col: values}}); uses a pseudo-regexp syntax
by default, but accepts `regexp: True` to use regexp directly |
370,050 | def encrypt_file(file, keys=secretKeys()):
key = keys.encryptKey
iv = keys.encryptIV
encData = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode=)
cipher = Cryptodome.Cipher.AES.new(key, Cryptodome.Cipher.AES.MODE_GCM, iv)
pbar = progbar(fileSize(file))
for chunk in iter(lambda: fil... | Encrypt file data with the same method as the Send browser/js client |
370,051 | def missing(name, limit=):
***
if limit == :
return not _service_is_upstart(name)
elif limit == :
return not _service_is_sysv(name)
else:
if _service_is_upstart(name) or _service_is_sysv(name):
return False
else:
return True | The inverse of service.available.
Return True if the named service is not available. Use the ``limit`` param to
restrict results to services of that type.
CLI Examples:
.. code-block:: bash
salt '*' service.missing sshd
salt '*' service.missing sshd limit=upstart
salt '*' ser... |
370,052 | def critical(self, msg, *args, **kwargs) -> Task:
return self._make_log_task(logging.CRITICAL, msg, args, **kwargs) | Log msg with severity 'CRITICAL'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
await logger.critical("Houston, we have a major disaster", exc_info=1) |
370,053 | def configure_versioning(self, versioning, mfa_delete=False,
mfa_token=None, headers=None):
if versioning:
ver =
else:
ver =
if mfa_delete:
mfa =
else:
mfa =
body = self.VersioningBody % (ve... | Configure versioning for this bucket.
..note:: This feature is currently in beta.
:type versioning: bool
:param versioning: A boolean indicating whether version is
enabled (True) or disabled (False).
:type mfa_delete: bool
:p... |
370,054 | def update_catalog_extent(self, current_extent):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self.br.update_boot_system_use(struct.pack(, current_extent)) | A method to update the extent associated with this Boot Catalog.
Parameters:
current_extent - New extent to associate with this Boot Catalog
Returns:
Nothing. |
370,055 | def restart(self, restart_only_stale_services=None,
redeploy_client_configuration=None,
restart_service_names=None):
if self._get_resource_root().version < 6:
return self._cmd()
else:
args = dict()
args[] = restart_only_stale_services
args[] = redeploy_client_configuration
... | Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have stale
configuration and their dependent
services. De... |
370,056 | def store_random(self):
with h5py.File(self.database.input, ) as io5:
fillsets = io5["quartets"]
qiter = itertools.combinations(xrange(len(self.samples)), 4)
rand = np.arange(0, n_choose_k(len(self.samples), 4))
np.random.shuffle(rand)
rslice = rand[:self.para... | Populate array with random quartets sampled from a generator.
Holding all sets in memory might take a lot, but holding a very
large list of random numbers for which ones to sample will fit
into memory for most reasonable sized sets. So we'll load a
list of random numbers in the range of the length of ... |
370,057 | def get_width(self, c, default=0, match_only=None):
return self.getattr(c=c,
attr=,
default=default,
match_only=match_only) | Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The component to look up.
default (float): The width to return in the ev... |
370,058 | def set_nodes_vlan(site, nodes, interface, vlan_id):
def _to_network_address(host):
splitted = host.split()
splitted[0] = splitted[0] + "-" + interface
return ".".join(splitted)
gk = get_api_client()
network_addresses = [_to_network_address(n) for n in nodes]
gk.si... | Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to put in the vlan
vlan_id(str): the id of the vlan |
370,059 | def todo(self, **kwargs):
path = % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path, **kwargs) | Create a todo associated to the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the todo cannot be set |
370,060 | def decode_mst(energy: numpy.ndarray,
length: int,
has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]:
if has_labels and energy.ndim != 3:
raise ConfigurationError("The dimension of the energy array is not equal to 3.")
elif not has_labels and energy.ndim ... | Note: Counter to typical intuition, this function decodes the _maximum_
spanning tree.
Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for
maximum spanning arborescences on graphs.
Parameters
----------
energy : ``numpy.ndarray``, required.
A tensor with shape (num_label... |
370,061 | def _get_synset_offsets(synset_idxes):
offsets = {}
current_seeked_offset_idx = 0
ordered_synset_idxes = sorted(synset_idxes)
with codecs.open(_SOI,, ) as fin:
for line in fin:
split_line = line.split()
while current_seeked_offset_idx < len(ordered_synse... | Returs pointer offset in the WordNet file for every synset index.
Notes
-----
Internal function. Do not call directly.
Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)].
Parameters
----------
synset_idxes : list of ints
Lists synset IDs, which need offset.
... |
370,062 | def all_announcements_view(request):
page_name = "Archives - All Announcements"
userProfile = UserProfile.objects.get(user=request.user)
announcement_form = None
manager_positions = Manager.objects.filter(incumbent=userProfile)
if manager_positions:
announcement_form = AnnouncementForm(... | The view of manager announcements. |
370,063 | async def update(self) -> None:
if self.next_allowed_update is not None and \
datetime.utcnow() < self.next_allowed_update:
return
self.next_allowed_update = None
await self.api._update_device_state()
self._device_json = self._device[] | Retrieve updated device state. |
370,064 | def to_instants_dataframe(self, sql_ctx):
ssql_ctx = sql_ctx._ssql_ctx
jdf = self._jtsrdd.toInstantsDataFrame(ssql_ctx, -1)
return DataFrame(jdf, sql_ctx) | Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD. |
370,065 | def find_expcoef(self, nsd_below=0., plot=False,
trimlim=None, autorange_kwargs={}):
print()
def findtrim(tr, lim=None):
trr = np.roll(tr, -1)
trr[-1] = 0
if lim is None:
lim = 0.5 * np.nanmax(tr - trr)
ind = ... | Determines exponential decay coefficient for despike filter.
Fits an exponential decay function to the washout phase of standards
to determine the washout time of your laser cell. The exponential
coefficient reported is `nsd_below` standard deviations below the
fitted exponent, to ensur... |
370,066 | def _load_mnist_dataset(shape, path, name=, url=):
path = os.path.join(path, name)
with gzip.open(filepath, ) as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
data = data.reshape(shape)
return data / np.float32(256)... | A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(th... |
370,067 | def authenticate_credentials(self, request, access_token):
try:
token = oauth2_provider.oauth2.models.AccessToken.objects.select_related()
token = token.get(token=access_token, expires__gt=provider_now())
except oauth2_provider.oauth2.models.Ac... | Authenticate the request, given the access token. |
370,068 | def gcs_read(self, remote_log_location):
bkt, blob = self.parse_gcs_url(remote_log_location)
return self.hook.download(bkt, blob).decode() | Returns the log found at the remote_log_location.
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path) |
370,069 | def write_byte_data(self, addr, cmd, val):
self._set_addr(addr)
if SMBUS.i2c_smbus_write_byte_data(self._fd,
ffi.cast("__u8", cmd),
ffi.cast("__u8", val)) == -1:
raise IOError(ffi.errno) | write_byte_data(addr, cmd, val)
Perform SMBus Write Byte Data transaction. |
370,070 | def _tree_view_builder(self, indent=0, is_root=True):
def pad_text(indent):
return " " * indent + "|-- "
lines = list()
if is_root:
lines.append(SP_DIR)
lines.append(
"%s%s (%s)" % (pad_text(indent), self.shortname, self.fullname)
... | Build a text to represent the package structure. |
370,071 | def inverted(self):
return Instance(input=self.output, output=self.input,
annotated_input=self.annotated_output,
annotated_output=self.annotated_input,
alt_inputs=self.alt_outputs,
alt_outputs=self.alt_input... | Return a version of this instance with inputs replaced by outputs and vice versa. |
370,072 | def trace_integration(tracer=None):
log.info("Integrated module: {}".format(MODULE_NAME))
start_func = getattr(threading.Thread, "start")
setattr(
threading.Thread, start_func.__name__, wrap_threading_start(start_func)
)
run_func = getattr(threading.Thread, "run")
setattr... | Wrap threading functions to trace. |
370,073 | def go_to_position(self, position):
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
return True | Moves the text cursor to given position.
:param position: Position to go to.
:type position: int
:return: Method success.
:rtype: bool |
370,074 | def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):
out = ""
if self.codon_positions in [, ]:
for gene_code, seqs in block_1st2nd.items():
out += .format(gene_code)
for seq in seqs:
out ... | Takes into account whether we need to output all codon positions. |
370,075 | def search(self, keyword, count=30):
kwargs = {}
kwargs[] = keyword
root = self.root_directory
entries = root._load_entries(func=self._req_files_search,
count=count, page=1, **kwargs)
res = []
for entry in entries:
... | Search files or directories
:param str keyword: keyword
:param int count: number of entries to be listed |
370,076 | def condense(self):
for pseudo_key, rows in self._rows.items():
tmp1 = []
intervals = sorted(self._derive_distinct_intervals(rows))
for interval in intervals:
tmp2 = dict(zip(self._pseudo_key, pseudo_key))
tmp2[self._key_start_date] = ... | Condense the data set to the distinct intervals based on the pseudo key. |
370,077 | def Prep(self, size, additionalBytes):
if size > self.minalign:
self.minalign = size
alignSize = (~(len(self.Bytes) - self.Head() + additionalBytes)) + 1
alignSize &= (size - 1)
while self.Head() < alignSize+size+additionalBytes... | Prep prepares to write an element of `size` after `additional_bytes`
have been written, e.g. if you write a string, you need to align
such the int length field is aligned to SizeInt32, and the string
data follows it directly.
If all you need to do is align, `additionalBytes` will be 0. |
370,078 | def cbar_value_cb(self, cbar, value, event):
if self.cursor_obj is not None:
readout = self.cursor_obj.readout
if readout is not None:
maxv = readout.maxv
text = "Value: %-*.*s" % (maxv, maxv, value)
readout.set_text(text) | This method is called when the user moves the mouse over the
ColorBar. It displays the value of the mouse position in the
ColorBar in the Readout (if any). |
370,079 | def getkeypress(self):
u
ck = System.ConsoleKey
while 1:
e = System.Console.ReadKey(True)
if e.Key == System.ConsoleKey.PageDown:
self.scroll_window(12)
elif e.Key == System.ConsoleKey.PageUp:
self.scroll_window(-12)
... | u'''Return next key press event from the queue, ignoring others. |
370,080 | def p_expression_lesseq(self, p):
p[0] = LessEq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LE expression |
370,081 | def main():
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_properties(parser)
add_region(parser)
add_artifact_path(parser)
add_artifact_version(parser)
args = pars... | Create application.properties for a given application. |
370,082 | def is_writable(filename):
if not os.path.exists(filename):
parentdir = os.path.dirname(filename)
return os.path.isdir(parentdir) and os.access(parentdir, os.W_OK)
return os.path.isfile(filename) and os.access(filename, os.W_OK) | Check if
- the file is a regular file and is writable, or
- the file does not exist and its parent directory exists and is
writable |
370,083 | def check(self, orb):
return self.prev is not None and np.sign(self(orb)) != np.sign(self(self.prev)) | Method that check whether or not the listener is triggered
Args:
orb (Orbit):
Return:
bool: True if there is a zero-crossing for the parameter watched by the listener |
370,084 | def _value_format(self, value):
return % (
self.area_names.get(self.adapt_code(value[0]), ),
self._y_format(value[1])
) | Format value for map value display. |
370,085 | def ldeo(magfile, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
specnum=0, samp_con="1", location="unknown", codelist="",
coil="", arm_labfield=50e-6, trm_peakT=873.,... | converts Lamont Doherty Earth Observatory measurement files to MagIC data base model 3.0
Parameters
_________
magfile : input measurement file
dir_path : output directory path, default "."
input_dir_path : input file directory IF different from dir_path, default ""
meas_file : output file measu... |
370,086 | def get_pull_requests(self, project, repository, state=, order=, limit=100, start=0):
url = .format(project=project,
repository=repository)
params = {}
if state:
params[] = state
... | Get pull requests
:param project:
:param repository:
:param state:
:param order: OPTIONAL: defaults to NEWEST) the order to return pull requests in, either OLDEST
(as in: "oldest first") or NEWEST.
:param limit:
:param start:
:retur... |
370,087 | def _get_matching(self, reltype, target, is_external=False):
def matches(rel, reltype, target, is_external):
if rel.reltype != reltype:
return False
if rel.is_external != is_external:
return False
rel_target = rel.target_ref if rel.is_... | Return relationship of matching *reltype*, *target*, and
*is_external* from collection, or None if not found. |
370,088 | def update(self,table, sys_id, **kparams):
record = self.api.update(table, sys_id, **kparams)
return record | update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj. |
370,089 | def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]:
alpha = kwargs.pop("alpha", 1)
if hasattr(alpha, "__call__"):
return np.vectorize(alpha)(data)
return alpha | Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data. |
370,090 | def show(self, start_date, end_date):
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", "."),
"end": end_date.strftime("%x").replace("/", ".")}
if start_date != end_date:
filename = "%(title)s, %(start)s - %(e... | setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux |
370,091 | async def get_headline(self, name):
resp = await self.send_command(OPERATIONS.CMD_QUERY_HEADLINE, {: name},
MESSAGES.QueryHeadlineResponse, timeout=5.0)
if resp is not None:
resp = states.ServiceMessage.FromDictionary(resp)
return re... | Get stored messages for a service.
Args:
name (string): The name of the service to get messages from.
Returns:
ServiceMessage: the headline or None if no headline has been set |
370,092 | def get_api_ruler(self):
if self.api_ruler is None:
try:
self.api_ruler = \
autoclass()
except JavaException as e:
raise ReachOfflineReadingError(e)
return self.api_ruler | Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object). |
370,093 | def addTab(self, view, title):
if not isinstance(view, XView):
return False
tab = self._tabBar.addTab(title)
self.addWidget(view)
tab.titleChanged.connect(view.setWindowTitle)
try:
view.windowTitleChanged.connect(self.refreshTit... | Adds a new view tab to this panel.
:param view | <XView>
title | <str>
:return <bool> | success |
370,094 | def encode_field(self, field, value):
for encoder in _GetFieldCodecs(field, ):
result = encoder(field, value)
value = result.value
if result.complete:
return value
if isinstance(field, messages.EnumField):
if field.repeated:
... | Encode the given value as JSON.
Args:
field: a messages.Field for the field we're encoding.
value: a value for field.
Returns:
A python value suitable for json.dumps. |
370,095 | def register_callback(self):
cid = str(self.__cid)
self.__cid += 1
event = queue.Queue()
self.__callbacks[cid] = event
return cid, event | Register callback that we will have to wait for |
370,096 | def _handle_precalled(data):
if data.get("vrn_file") and not cwlutils.is_cwl_run(data):
vrn_file = data["vrn_file"]
if isinstance(vrn_file, (list, tuple)):
assert len(vrn_file) == 1
vrn_file = vrn_file[0]
precalled_dir = utils.safe_makedir(os.path.join(dd.get_wor... | Copy in external pre-called variants fed into analysis.
Symlinks for non-CWL runs where we want to ensure VCF present
in a local directory. |
370,097 | def _exponent_handler_factory(ion_type, exp_chars, parse_func, first_char=None):
def transition(prev, c, ctx, trans):
if c in _SIGN and prev in exp_chars:
ctx.value.append(c)
else:
_illegal_character(c, ctx)
return trans
illegal = exp_chars + _SIGN
return... | Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters for this component.
parse_func (callable): Called upon ending the numeric value.... |
370,098 | def Run(self, arg):
try:
if self.grr_worker.client.FleetspeakEnabled():
raise ValueError("Not supported on Fleetspeak enabled clients.")
except AttributeError:
pass
smart_arg = {str(field): value for field, value in iteritems(arg)}
disallowed_fields = [
field for field... | Does the actual work. |
370,099 | def get_fmt_widget(self, parent, project):
from psy_simple.widgets.texts import LabelWidget
return LabelWidget(parent, self, project) | Create a combobox with the attributes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.