content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sciper2name(sciper):
"""Convert a sciper to a name, using EPFL's LDAP"""
return search_attr_in_ldap(sciper, 'cn') or _("Unknown name") | 5,301,100 |
def test_info_main_internet_free():
"""
test the pkg-info main funtion in an internet free context
(pkg-info)
"""
## Install hg19-gaps
try:
pytest_enable_socket()
install_hg19_gaps_ucsc_v1()
except:
pass
## Check show-env in an internet free context
pyte... | 5,301,101 |
def title1():
""" Ученое звание """
title = Person.Title()
title.date = datetime(2010, 1, 1)
title.title = 'доц.'
return title | 5,301,102 |
def from_args(it, key, lo, hi, prefix, reverse, max_, include, max_phys):
"""This function is a stand-in until the core.py API is refurbished."""
if key:
it.set_exact(key)
return it.forward()
elif prefix:
it.set_prefix(prefix)
else:
if lo:
it.set_lo(lo)
... | 5,301,103 |
def bump_version(version_array, level):
"""
Perform ++1 action on the array [x, y, z] cell,
Input values are assumed to be validated
:param version_array: int array of [x, y, z] validated array
:param level: string represents major|minor|patch
:return: int array with new value
"""
if typ... | 5,301,104 |
def logistic_regression():
"""
Source used for guidance:
- https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8
---------------------------------------------------------------------------
Source used for guidance:
Transforming th... | 5,301,105 |
def all_event_tweets(request):
"""Summary of tweets and submission of tweets"""
return render(request, 'manage/all_event_tweets.html') | 5,301,106 |
def basic(mzml, output, zip):
"""
Calculate the basic metrics available from virtually every mzML file.
"""
if mzml is None:
print_help()
exp = oms.MSExperiment()
oms.MzMLFile().load(click.format_filename(mzml), exp)
rq = basicqc.getBasicQuality(exp)
rqs.append(rq)
global_variables(output, zip)
... | 5,301,107 |
def map_persons_to_known_ldap_user(person_record, session):
"""
Since the exported persons table contains records without email
from various sources, we have to try to map it to an existing record
or create a new one.
The ldap fetched users have an attendee created with
first_name, last_name an... | 5,301,108 |
def print_usage():
"""
Print commandline usage
:return: returns 1 for for exit code purposes
:rtype: int
"""
print("""
Usage:
{0} --help-info
{0} [options] input.json output.json
Options:
--overwrite Overwrite output file
-a field=val Only add a field if it doesn't exi... | 5,301,109 |
async def list_of_speakers_slide(
all_data: AllData, element: Dict[str, Any], projector_id: int
) -> Dict[str, Any]:
"""
List of speakers slide.
Returns all usernames, that are on the list of speaker of a slide.
"""
list_of_speakers_id = element.get("id")
if list_of_speakers_id is None:
... | 5,301,110 |
def calculate_intervals(values: np.array) -> Tuple[int]:
"""Calculate intervals between the provided note values."""
return tuple(
[(next_note - note) % 12 for note, next_note in zip(values, values[1:])]
) | 5,301,111 |
def get_time_with_timezone(time_delta):
"""Parameter is timezone offset from UTC in seconds. Returns a string H:M:S."""
return (datetime.datetime.now() + datetime.timedelta(seconds=time_delta)).strftime("%H:%M") + " UTC" + str(time_delta / 3600) | 5,301,112 |
def shallFreezeAllStdlib():
"""*bool* = **not** shallFollowStandardLibrary"""
return not shallFollowStandardLibrary() | 5,301,113 |
def _get_attribute_accesses_for_import_from(node, variable):
"""
..code:: python
ImportFrom(identifier? module, alias* names, int? level)
"""
return
yield | 5,301,114 |
def _get_timestep_lookup_function(control_loop_period, memory_loc, rtf_key):
"""
Creates a customized timestep lookup function for a SynchronizedTimedLoop
:param control_loop_period: duration in [s] of each timed loop
:param memory_loc: location in shared memory to get() data from
:param rtf_key: ke... | 5,301,115 |
def finditer(pattern, string, flags=0):
"""Finditer after applying backrefs."""
return re.finditer(_apply_search_backrefs(pattern, flags), string, flags) | 5,301,116 |
def quit_client():
"""Close the EVE client"""
pg.press('esc')
time.sleep(2)
click_img('images/client-popup-logoff.png') | 5,301,117 |
def stretched_exponential_series(Lambda = 1.0, Beta = 1.0, n = 1, xmin = 1.0, discrete = False):
"""
Generator to generate a stream of numbers taken from stretched exponential distribution.
**Parameters**
Lambda : Float/Integer, Lambda constant for the distribution.
Default value is 1... | 5,301,118 |
def decode_mint_to(instruction: TransactionInstruction) -> MintToParams:
"""Decode a mint to token transaction and retrieve the instruction params."""
parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO)
return MintToParams(
program_id=instruction.program_id,
... | 5,301,119 |
def test_init_on_cloned_repo(isolated_runner, data_repository):
"""Run init on a cloned repository."""
runner = isolated_runner
pwd = os.getcwd()
# Clone to the current directory
data_repository.clone(pwd)
# Only --force should work
result = runner.invoke(cli.cli, ['init'])
assert 0 !=... | 5,301,120 |
def daemonize(func):
"""
A function wrapper that checks daemon flags. This wrapper as it is assumes
that the calling class has a daemon attribute.
"""
def _wrapper(self, *args, d_init=False, **kwargs):
if d_init:
self.daemon.d_init.append((func, self, args, kwargs))
retur... | 5,301,121 |
def _AddMirroredTagsArg(parser, is_for_update=False):
"""Adds args to specify mirrored tags."""
if is_for_update:
tags = parser.add_mutually_exclusive_group(help="""\
Update the mirrored tags of this packet mirroring.
To read more about configuring network tags, read this guide:
https://cloud... | 5,301,122 |
def train(epoch,trainset,inputs,net,batch_size,trainloader,resize,num_epochs,use_cuda,criterion,logfile):
"""
This is a javadoc style.
@param epoch: the current epoch to be run on top of existing net global variable
@param trainset: Dataset for training
@param inputs: the number of channels of input... | 5,301,123 |
def authenticated_user(method):
"""Decorate methods with this to require that the user be logged in."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method in ("GET", "HEAD"):
url = self.get_login_url()
... | 5,301,124 |
def make_string_to_dict(base64_headers: str) -> dict:
"""分割: """
d = {}
s = base64.decodebytes(base64_headers.encode('utf-8')).decode('utf-8')
string_list_by_line = s.strip().split('\n')
for each in string_list_by_line:
each = each.strip()
# 去除:开头的
if each.startswith(':'):
... | 5,301,125 |
def _find_converter(type_: type, /) -> MaybeNone[ConverterT]:
"""
!!! note:
This is a Future object that will be relevant in
future versions of petuhlang. There is no point
in using it right now.
"""
for types in __converters__.keys():
if type_ in types or type_ is types:... | 5,301,126 |
def proccess_host(host):
"""
:param host: This should be a dict where host['host'] is an ip address
:return:
"""
host['country_code'] = gi_country.country_code_by_addr(host['host'])
host['country_name'] = gi_country.country_name_by_addr(host['host'])
host['asn'] = gi_asn.asn_by_addr(host['h... | 5,301,127 |
def open_graph(directory, graph_name, wf_filename=WORKFLOW_DEFAULT_FILENAME):
"""Opens an existing workflow and return the specified graph instance.
Args:
directory (str): A directory containg a `workflow.py` file, or
a file named by the `wf_filename` argument.
graph_name (str): The ... | 5,301,128 |
def trajectory_2d(
tracks,
image=None,
labels=None,
color=None,
xlim=None, ylim=None,
cmap=None,
cbar=False,
cbar_width=30,
show_points=False,
line_kws=None,
scat_kws=None,
im_kws=None,
dpi=None,
scale=1.,
margin=None
):
"""
2d plot of trajectories.
... | 5,301,129 |
def p_alterStmt(t):
"""alterStmt : R_ALTER R_DATABASE idOrString alterDb
| R_ALTER R_TABLE idOrString alterTableList
| R_ALTER R_INDEX ifExists idOrString R_RENAME R_TO idOrString
| R_ALTER R_INDEX ifExists idOrString R_ALTER column idOrString idOrNumber
"""
if t[2] == "DATABASE":
t[0] =... | 5,301,130 |
def get_cpachecker_executable():
"""Return the path to the CPAchecker executable 'cpa.sh'.
If the executable is available in the systeme PATH, this executable is
used. Otherwise, it is checked whether an executable 'cpa.sh' is
available in the current directory './' or the './scripts' directory.
:r... | 5,301,131 |
def plan_validation(user, plan=None, on_activation=False):
"""
Validates validator that represents quotas in a given system
:param user:
:param plan:
:return:
"""
if plan is None:
# if plan is not given, the default is to use current plan of the user
plan = user.userplan.plan... | 5,301,132 |
def flairgen(submission):
"""Convert letters in string to inline flair codes - regular mode.
Input string -> converts as list -> output string
Iterates through tuples of flair values sorted by letter, assigning
the correct logo code to each respective letter in a submitted string."""
submission = su... | 5,301,133 |
def vm_modify(vm_uuid):
"""
Render the details of the VM
"""
run=libvirt_test()
form=ModifyVMForm()
_,vm_detail=run.api_get_domain_detail(vm_uuid)
if form.validate_on_submit():
#department.name = form.name.data
#department.description = form.description.data
... | 5,301,134 |
def edit_on_keypress_seq_corr(word):
"""
#### this is the BALL of the @word ###
"""
word = word.encode('ascii', 'ignore')
keypress_w = KB.word_to_keyseq(word)
return list(KB.keyseq_insert_edits(keypress_w, allowed_keys, allowed_keys))
# for i, c in enumerate(keypress_w):
# f... | 5,301,135 |
def weights_init(layer):
"""
Initializes the weights of the generator and discriminator for optimized performance.
Parameters
----------
layer: nn.Module layer
Weights of a layer
"""
if isinstance(layer, (nn.Conv2d, nn.ConvTranspose2d)):
nn.init.normal_(layer.weigh... | 5,301,136 |
def find_anagrams(name, word_list):
"""Read name & dictionary file & display all anagrams IN name
Args:
name (string): value to find anagram
wordlist (dict): dictionary file
"""
name_letter_map = Counter(name)
anagrams = []
for word in word_list:
test = ''
word_l... | 5,301,137 |
def marker_algorithm(psi: HornFormulaSet) -> Optional[Set[Variable]]:
"""
Applies Marker Algorithm to given Horn Formula and returns either minimal model (if satisfiable) or None
:param psi: Horn Formula represented as HornFormulaSet
:return: Minimal model as set of Variables or None
"""
N: Set[... | 5,301,138 |
def convert_to_grayscale(img, file_name, output_gray):
"""
This function converts the original image in a grayscale image. Then shows and saves the gray scale image.
:param img: path to image of interest
:param output_path: path for the output image
"""
# reads the image img in grayscale
... | 5,301,139 |
def create_tiles(raster_file, dir_tiles):
"""
Create tiles from a raster file (using GDAL)
Parameters
----------
raster_file : Pathstr
the filename of a raster
dir_tiles : Path
the path to the directory where tiles will be saved
"""
# Check if the tiles directory is empt... | 5,301,140 |
def read_toc(toc_file):
"""Reads Table of Contents from the given file object 'f'.
Each line in file should be in form
<'*' x level> <page number> <description>
'level' of the next line should be at most one '*' larger than that of
previous line.
First line should contain encoding name.
Exam... | 5,301,141 |
def register():
"""
Register a user to the application
:rtype: flask.wrappers.Response
:return: Registration status
"""
account_json = request.get_json()
username = account_json.get('username', None)
password = account_json.get('password', None)
db = get_db()
error = None
i... | 5,301,142 |
def make_error(error_code):
""" Makes and returns Error message."""
temp_payload = struct.pack('<B', error_code)
payload = bytearray(temp_payload)
message = HibikeMessage(MESSAGE_TYPES["Error"], payload)
return message | 5,301,143 |
def solve_ineq_fourier(ineq,vars=None):
"""
Solves sytem of inequalities using Maxima and fourier elimination
Can be used for system of linear inequalities and for some types
of nonlinear inequalities. For examples see the section EXAMPLES
below and http://maxima.cvs.sourceforge.net/viewvc/maxima/m... | 5,301,144 |
def buffered_gen(source_gen, buffer_size=2, sleep_time=1):
"""
Generator that runs a slow source generator in a separate thread.
buffer_size: the maximal number of items to pre-generate (length of the buffer)
"""
buffer = Queue.Queue(maxsize=buffer_size)
def _buffered_generation_thread(source_g... | 5,301,145 |
def get_cursor(connection):
"""
Gets a cursor from a given connection.
:type MySQLdb.connections.Connection
:param connection: A mysql connection
:rtype MySQLdb.cursors.SSDictCursor
:return A mysql cursor
"""
return connection.cursor() | 5,301,146 |
def make_pes_mess_str(spc_dct, rxn_lst, pes_idx, pesgrp_num,
unstable_chnls,
run_prefix, save_prefix, label_dct,
tsk_key_dct, pes_param_dct,
thy_dct, pes_model_dct_i, spc_model_dct_i,
spc_model):
""" Write ... | 5,301,147 |
def print_first_word(words):
"""Prints The frist words after popping it off.""" #people wanna popoff at the mouth
#prints word at index position 0
word = words.pop(0)
print word | 5,301,148 |
def main(args):
"""Command-line interface function for the script to parse EAF files for
segments in the 'Mother' and 'Toddler' tiers. For each EAF file specified
on the command line, it parses the data and writes a row for each segment to
a CSV file, using code numbers for the different expected value... | 5,301,149 |
def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False,
longtable=False, output_dir_path='.', input_dir_path='', latex=False):
"""
Extracts specimen results from a MagIC 3.0 format specimens.txt file.
Default output format is an Excel file.
t... | 5,301,150 |
def get_distances_matrix(hotels, workers):
"""Compute the distance matrix (distance between each hotels).
Returns a triangular matrix and the labels of the hotels.
Note:
1) That the first address shall be the address of the depot.
2) If the API doesn't returna a match for the address, we dr... | 5,301,151 |
def test_orientation_max_power(bias_params_fixed, bias_params_free,
reg, weight_norm, use_cov, depth, lower, upper,
lower_ori, upper_ori):
"""Test orientation selection for bias for max-power LCMV."""
# we simulate data for the fixed orientation forw... | 5,301,152 |
def _get_flim(flim, fscale, freq, sfreq=None):
"""Get reasonable frequency limits."""
if flim is None:
if freq is None:
flim = [0.1 if fscale == 'log' else 0., sfreq / 2.]
else:
if fscale == 'linear':
flim = [freq[0]]
else:
flim... | 5,301,153 |
def load(config_raw: t.Dict[str, t.Any]) -> bool:
"""
This function runs on the main process after the module is imported. It should parse
and validate the configuration and do other basic setup of the module. Do not start
any threads or long running tasks here, they should go in the ``start`` function.... | 5,301,154 |
def get_programs():
"""Get the counts of how many users belong to each program."""
users = m.User.objects().only('program_name')
programs_names = [user.short_program_name for user in users]
program_frequencies = collections.Counter(programs_names)
programs = []
for program, count in program_fr... | 5,301,155 |
def test_link_source_reference():
"""Ensure that a link can reference to source it was added by"""
db = Database(":memory:", create=True, verbose=True)
Source.add(
db,
name="Numpy",
prefix="https://docs.scipy.org/doc/numpy/",
uri="sphinx://https://docs.scipy.org/doc/numpy/",... | 5,301,156 |
def while_triangle():
"""Shape of 'Triangle' using Python while loop"""
row = 0
while row<6:
col = 0
while col<6:
if row<=col:
print(' ', end = ' ')
else:
... | 5,301,157 |
def halt(sending=False, removing=False):
"""
READ for the HALT command, SEND it, or CLEAN the HALT file.
IMPORTANT:
In order to prevents the system from ignoring your halt commands, please
don't forget to include this test in your (heavy) loops!
Examples:
... | 5,301,158 |
def test_get_send_binary(mock_send, mock_events, lora):
"""Test send, binary."""
lora.send(bytes.fromhex('01020211'))
mock_send.assert_called_once_with('send=0,1,01020211')
mock_events.assert_called_once() | 5,301,159 |
def _popup_footer(view, details):
"""
Generate a footer for the package popup that indicates how the package is
installed.
"""
return """
{shipped} <span class="status">Ships with Sublime</span>
{installed} <span class="status">In Installed Packages Folder</span> ... | 5,301,160 |
def process_chunk(
archive: ZipFile,
layer_id: str, chunk_name: str,
imagesize: list[int], tilesize: int,
columns: int, rows: int,
difference_x: int, difference_y: int,
strict: bool
) -> tuple[Image.Image, tuple[int, int]]:
"""iterate through chunks, decompress them, create images"""
# G... | 5,301,161 |
def remove_pyc_files():
"""removes .pyc files"""
curr_dir = os.path.dirname(os.path.abspath(__file__))
pyc_files = []
for root, _, filenames in os.walk(curr_dir):
for file_name in filenames:
if len(file_name) >= 4 and file_name[-4:] == '.pyc':
full_file_name = os.path... | 5,301,162 |
def check_smartass_animator(progress_controller=None):
"""Animator doesn't try to be a smart-ass
checks if the smartass animator is silently trying to create a new
version for a completed animation scene
"""
if progress_controller is None:
progress_controller = ProgressControllerBase()
... | 5,301,163 |
def testForUnevenHandles(glyph):
"""
Handles should share the workload as evenly as possible.
"""
unevenHandles = {}
for index, contour in enumerate(glyph):
prevPoint = contour[-1].onCurve
for segment in contour:
if segment.type == "curve":
# create rays p... | 5,301,164 |
def get_all_pages_url(ptt_index_url):
"""accroding get_max_pages,
generate each page url
index, index0, index1, ... ,
index == indexMax
"""
max_page = get_max_pages(ptt_index_url)
url_head = ptt_index_url.split('index')[0]
all_urls = ["{}index{}.html".format(url_head, i) for i in range(1... | 5,301,165 |
def query_tweets_once(query, limit=None, num_tweets=0):
"""
Queries twitter for all the tweets you want! It will load all pages it gets
from twitter. However, twitter might out of a sudden stop serving new pages,
in that case, use the `query_tweets` method.
Note that this function catches the Keybo... | 5,301,166 |
def trycast(new_type, value, default=None):
"""
Attempt to cast `value` as `new_type` or `default` if conversion fails
"""
try:
default = new_type(value)
finally:
return default | 5,301,167 |
def reverse_cache_data(data): # type: tensor_pb2.CacheDate -> None
"""tensor_pb2.CacheDate => 1.0 / tensor_pb2.CacheDate
"""
if data.type is tensor_pb2.INT8:
data.c[:] = map(lambda x: 1.0 / x, data.c)
elif data.type is tensor_pb2.INT32:
data.i[:] = map(lambda x: 1.0 / x, data.i)
eli... | 5,301,168 |
def time_function(out=sys.stdout, is_classmethod=False, return_time=False):
"""
Time run time of a function and write to stdout or a log file. Also has some extra functions in case you want to
apply it to a ArticleProcessingMixin.
:param out: Output of choice. None will result in no output, sys.stdout ... | 5,301,169 |
def unwrap(*args, **kwargs):
"""Unwraps the tuple into function parameters before calling the function.
This is not implemented on the Java side yet.
"""
return _function_decorator(args, kwargs, { 'parameters' : 'unwrap' }) | 5,301,170 |
def newSTTEngine(stt_engine, **kwargs):
"""
Returns a Speech-To-Text engine.
Currently, the supported implementations are the default Pocket Sphinx and
the Google Speech API
Arguments:
engine_type -- one of "sphinx" or "google"
kwargs -- keyword arguments passed to the constructor ... | 5,301,171 |
def msigma(i):
"""Returns a Pauli matrix sigma_i. i=1,2,3
See Also
========
http://en.wikipedia.org/wiki/Pauli_matrices
Examples
========
>>> from sympy.physics.matrices import msigma
>>> msigma(1)
[0, 1]
[1, 0]
"""
if i == 1:
mat = ( (
(0, 1),
... | 5,301,172 |
def main():
"""Application entry point."""
print("Test of the GrovePi DHT sensor, LEDs and RGB LCD screen.\n")
sensor_test() | 5,301,173 |
def run_python_script(script, params=None):
"""
Executes a script python as a string.
@param script python script
@param params params to add before the execution
.. exref::
:title: compile and run a custom script
::
fpr = lambda v : self.outStream.write(s... | 5,301,174 |
def _generate_wireless_settings_data(settings):
"""Generates a wireless settings data array to push to the
router from the given wireless settings."""
settings.ensure_valid()
data = {'ssid1': settings.ssid, 'channel': settings.channel, 'Save': 'Save'}
if settings.is_enabled:
data['ap'] = 1... | 5,301,175 |
def upload_video(filename, uploads_list, storage_addr, sas_token):
"""
Prepare the upload of files to a azure Filestorage
:param filename: filename
:type filename: str
:param uploads_list: list of processes to track the process of uploading
:type uploads_list: list
:param storage_addr: addr... | 5,301,176 |
def load(tfrecord_file, meta_data_file, model_spec):
"""Loads data from tfrecord file and metada file."""
dataset = input_pipeline.single_file_dataset(
tfrecord_file, model_spec.get_name_to_features())
dataset = dataset.map(
model_spec.select_data_from_record,
num_parallel_calls=tf.data.experim... | 5,301,177 |
def dummy_house():
"""
Sample dataset that will be used to alter and make prediction on
"""
return {
"Id": 34,
"MSSubClass": 20, # Identifies the type of dwelling involved in the sale.
"LotFrontage": 70.0, # Linear feet of street connected to property
"LotArea": 10552, ... | 5,301,178 |
def test_wrong_metadata_collection_type(dataset_type):
"""
Test passing in the wrong collection type into the metadata this should be corrected during the init.
"""
from qcsubmit.common_structures import Metadata
meta = Metadata(collection_type="INVALID")
dataset = dataset_type(metadata=meta)
... | 5,301,179 |
def create_instances(region='us-east-1', count=1):
"""Create some dummy instances and return the instance ids"""
client = boto3.client('ec2', region_name=region)
ids = []
create_results = client.run_instances(ImageId='ami-123abc', MinCount=count, MaxCount=count)
for created_instance in create_resu... | 5,301,180 |
def get_subsystem_other_info(dut, map_key):
"""Get the value from subsystem table other_info column."""
subsystem_uuid = dut(ovs_vsctl + "list subsystem | grep -i uuid|cut -d :"
" -f 2", shell="bash")
uuid = subsystem_uuid.replace('\r\n', '')
c = ovs_vsctl + "get subsystem " + u... | 5,301,181 |
def vg(P):
""" Specific volume [m^3 / kg]
of saturated vapor"""
return region4.vg(P) | 5,301,182 |
def is_gray(img):
"""Checks if the image is grayscale, i.e., has exactly two channels.
Args:
img: an image
Returns:
True/False
"""
return img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1) | 5,301,183 |
def run_commands(settings):
"""
Checks the settings and runs the needed commands
"""
dirs = settings["dirs"]
if settings["grep"]:
if settings["grep_startswith"] != "":
grep = settings["grep_startswith"]
else:
grep = settings["grep_include"]
ls_dir_gr... | 5,301,184 |
def __process_nasa_data(name, file):
"""Helper function to process NASA data"""
if name == 'nasa_carbon_dioxide_levels':
ret = __process_nasa_co2_data(file)
elif name == 'nasa_sea_level':
ret = __process_nasa_sea_level_data(file)
elif name == 'nasa_temperature_anomaly':
ret = __p... | 5,301,185 |
def parse_year(x: pd.Series) -> Union[pd.Series, ValueTypeError]:
"""
Parse strings as years.
Per XML Schema, permits negative years and years greater than 9999.
However, time zones are not supported
(https://www.w3.org/TR/xmlschema-2/#timeZonePermited).
Arguments:
x: Strings.
Ret... | 5,301,186 |
def heatmaps_to_coordinates(heatmaps):
"""
Heatmaps is a numpy array
Its size - (batch_size, n_keypoints, img_size, img_size)
"""
batch_size = heatmaps.shape[0]
sums = heatmaps.sum(axis=-1).sum(axis=-1)
sums = np.expand_dims(sums, [2, 3])
normalized = heatmaps / sums
x_prob = normali... | 5,301,187 |
def setup(query) -> list:
"""Setup is successful if an empty list is returned.
Use this function if you need the user to provide you data
"""
results = []
query_str = query.string
# abbreviations file
if not abbr_store_fname.is_file():
results.append(
v0.Item(
... | 5,301,188 |
def construct_description(prefix: str, suffix: str, items: list):
"""Construction of complete description with prefix and suffixx.
Args:
prefix (str): prefix
suffix (str): suffix
items (list): itesm
Returns:
str: complete description string
"""
item_str = ','.join(... | 5,301,189 |
def read_cookies_file(filename):
"""read cookie txt file
:param filename: (str) cookies file path
:return: (dict) cookies
"""
with open(filename, 'r') as fp:
cookies = fp.read()
return cookies | 5,301,190 |
def xlinregress(da_y, da_x, dim=None, ess_on=False, alpha=0.05):
"""xarray-version linregress (accept xr.DataArray as input)"""
if dim is None:
dim = [d for d in da_y.dims if d in da_x.dims][0]
slope, intercept, r, dof, tvalue, slope_stderr, intercept_stderr, predict_stderr, pvalue, t_alpha = xr.app... | 5,301,191 |
def outer_prod(mat1: tf.Tensor, mat2: tf.Tensor):
"""
Parameters
----------
mat1: torch.Tensor[nBatch, mat1_dim1, mat1_dim2, mat1_dim3, ...]
mat2: torch.Tensor[nBatch, mat2_dim1, mat2_dim2, mat2_dim3, ...]
Returns
-------
res : torch.Tensor[nBatch, mat1_dim1, ..., mat2_dim1, ...]
""... | 5,301,192 |
def open_or_fd(file, mode='rb'):
""" fd = open_or_fd(file)
Open file, gzipped file, pipe, or forward the file-descriptor.
Eventually seeks in the 'file' argument contains ':offset' suffix.
"""
offset = None
try:
# strip 'ark:' prefix from r{x,w}filename (optional),
if re.search('^(ark|scp)(,scp|,b... | 5,301,193 |
def discover(directory: str = '.') -> List[Module]:
"""
Discover all modules in the given directory recursively and import them.
:param directory: the directory in which modules are to be discovered.
:return: a ``list`` of all discovered modules.
"""
paths = _find_paths(directory, '**/*.py', Tru... | 5,301,194 |
def replace_functions_in_pdata(pdata, attributes, function_keys):
"""
:param pdata: container of which some attributes are sympy expressions (will be altered)
:param attributes: relevant attribute-dict, in which the functions have to be replaced
:param function_keys: dict like {x1(t): ... | 5,301,195 |
def sec(arg):
"""Secant"""
return 1 / np.cos(arg) | 5,301,196 |
def to_rgb_image(render_data, color_by_elevation=False):
"""
convert raw sar image and / or point cloud into 8-bit RGB for display
"""
im_rgb = None
radar_image_display = RadarImageStreamDisplay()
# Default image region
xmin = 0
xmax = 60
ymin = -30
ymax = 30
im_res = 0.1
... | 5,301,197 |
def torad( theta ):
""" convert to radian
"""
return theta * np.pi / 180.0 | 5,301,198 |
def dt_now(delta=None, tz=dateutil.tz.tzutc()):
"""Get the current datetime in for a specific tz.
Args:
delta (:obj:`datetime.timedelta`, optional): default ``None`` -
subtract timedelta from now
tz (:obj:`datetime.timezone`, optional): default :obj:`dateutil.tz.tzutc`:
... | 5,301,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.