content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_gzip_uncompressed_file_size(file_name):
"""
this function will return the uncompressed size of a gzip file
similar as gzip -l file_name
"""
file_obj = gzip.open(file_name, 'r')
file_obj.seek(-8, 2)
# crc32 = gzip.read32(file_obj)
isize = gzip.read32(file_obj)
return isize | 10,000 |
def Capitalize(v):
"""Capitalise a string.
>>> s = Schema(Capitalize)
>>> s('hello world')
'Hello world'
"""
return str(v).capitalize() | 10,001 |
def pg_index_exists(conn, schema_name: str, table_name: str, index_name: str) -> bool:
"""
Does a postgres index exist?
Unlike pg_exists(), we don't need heightened permissions on the table.
So, for example, Explorer's limited-permission user can check agdc/ODC tables
that it doesn't own.
"""
... | 10,002 |
def create_mock_data(bundle_name: str,
user_params: dict):
"""
create some mock data and push to S3 bucket
:param bundle_name: str, bundle name
:param user_params: dict, what parameters to save
:return:
"""
api.context(context_name)
api.remote(context_name, remote_co... | 10,003 |
def check_bullet_alien_collisions(settings, screen, stats, sb, ship, aliens, bullets):
""" Respond to any bullet-alien collision."""
# remove any bullets and aliens that have collided,
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if collisions:
stats.score += settings.ali... | 10,004 |
def main():
"""
Run the server.
"""
factory = server.DNSServerFactory(
clients=[DynamicResolver(), client.Resolver(resolv="/etc/resolv.conf")]
)
protocol = dns.DNSDatagramProtocol(controller=factory)
reactor.listenUDP(10053, protocol)
reactor.listenTCP(10053, factory)
reac... | 10,005 |
def DiscoverNameServers():
"""Don't call, only here for backward compatability. We do discovery for
you automatically.
"""
pass | 10,006 |
def _vertex_arrays_to_list(x_coords_metres, y_coords_metres):
"""Converts set of vertices from two arrays to one list.
V = number of vertices
:param x_coords_metres: length-V numpy array of x-coordinates.
:param y_coords_metres: length-V numpy array of y-coordinates.
:return: vertex_list_xy_metres... | 10,007 |
def info_from_apiKeyAuth(token: str, required_scopes) -> Optional[Dict[str, Any]]:
"""
Check and retrieve authentication information from an API key.
Returned value will be passed in 'token_info' parameter of your operation function, if there
is one. 'sub' or 'uid' will be set in 'user' parameter of yo... | 10,008 |
def xgb_test(
context,
models_path: DataItem,
test_set: DataItem,
label_column: str,
plots_dest: str = "plots",
default_model: str = "model.pkl",
) -> None:
"""Test one or more classifier models against held-out dataset
Using held-out test features, evaluates the peformance of the estim... | 10,009 |
def convert_unix2dt(series):
"""
Parameters
----------
series : column from pandas dataframe in UNIX microsecond formatting
Returns
-------
timestamp_dt : series in date-time format
"""
if (len(series) == 1):
unix_s = series/1000
else:
unix_s = series.squeez... | 10,010 |
def test_add_invalid_path(qtbot, pathmanager):
"""Checks for unicode on python 2."""
pathmanager.show()
count = pathmanager.count()
def interact_message_box():
qtbot.wait(500)
messagebox = pathmanager.findChild(QMessageBox)
button = messagebox.findChild(QPushButton)
qtbo... | 10,011 |
def main():
"""Program, kok"""
args = parse_args()
if args.bind:
override_socket(args.bind)
try:
check_update()
except Exception as ex:
print("Failed to check for new version:", ex,
file=sys.stderr, flush=True)
from volapi import Room
stat = Statist... | 10,012 |
def staging(new_settings={}):
"""Work on the staging environment"""
load_environ('staging', new_settings) | 10,013 |
def sentence_segment(text, delimiters=('?', '?', '!', '!', '。', ';', '……', '…'), include_symbols=True):
"""
Sentence segmentation
:param text: query
:param delimiters: set
:param include_symbols: bool
:return: list(word, idx)
"""
result = []
delimiters = set([item for item in delimit... | 10,014 |
def create_users_table(conn):
"""Create table for users"""
try:
sql = '''CREATE TABLE users (
numCorrect Int,
defaultPath String,
timerDuration Int,
charTimerValue Int,
charBasedTimer Bool,
noTyping Bool,
autoStart Bool,... | 10,015 |
def time_rep_song_to_16th_note_grid(time_rep_song):
"""
Transform the time_rep_song into an array of 16th note with pitches in the onsets
[[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0]
"""
grid_16th = []
for pair_p_t in time_rep_song:
grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)])
retur... | 10,016 |
def _double_threshold(x, high_thres, low_thres, n_connect=1, return_arr=True):
"""_double_threshold
Computes a double threshold over the input array
:param x: input array, needs to be 1d
:param high_thres: High threshold over the array
:param low_thres: Low threshold over the array
:param n_con... | 10,017 |
def _convert_dataset(split_name, files, labels, dataset_dir):
"""Converts the given filenames to a TFRecord dataset.
Args:
split_name: The name of the dataset, either 'train' or 'test'.
filenames: A list of absolute paths to png or jpg images.
class_names_to_ids: A dictionary from class names (strings)... | 10,018 |
def upload():
"""
Implements the upload page form
"""
return render_template('upload.html') | 10,019 |
def detect_changepoints(points, min_time, data_processor=acc_difference):
""" Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (functio... | 10,020 |
def Sum(idx, *args, **kwargs):
"""Instantiator for an arbitrary indexed sum.
This returns a function that instantiates the appropriate
:class:`QuantumIndexedSum` subclass for a given term expression. It is the
preferred way to "manually" create indexed sum expressions, closely
resembling the normal... | 10,021 |
def quad1(P):
"""[summary]
Arguments:
P (type): [description]
Returns:
[type]: [description]
"""
x1, z1, x2, z2 = P
return (Fraction(x1, z1) - Fraction(x2, z2))**2 | 10,022 |
def test_construct_form_fail():
"""Form objects must be constructed from form html elements."""
soup = bs4.BeautifulSoup('<notform>This is not a form</notform>', 'lxml')
tag = soup.find('notform')
assert isinstance(tag, bs4.element.Tag)
with pytest.warns(FutureWarning, match="from a 'notform'"):
... | 10,023 |
async def test_set_hold_mode_eco(opp):
"""Test setting the hold mode eco."""
await common.async_set_preset_mode(opp, PRESET_ECO, ENTITY_ECOBEE)
await opp.async_block_till_done()
state = opp.states.get(ENTITY_ECOBEE)
assert state.attributes.get(ATTR_PRESET_MODE) == PRESET_ECO | 10,024 |
def update_position(position, velocity):
"""
:param position: position(previus/running) of a particle
:param velocity: the newest velocity that has been calculated during the specific iteration- new velocity is calculated
before the new position
:return: list - new position
"""
pos = ... | 10,025 |
def respond_batch():
"""
responses with [{"batch": [{blacklist_1_name: true}, ]}]
"""
result = get_result(request)
return jsonify([{"batch": result}]) | 10,026 |
def get_iterable_itemtype(obj):
"""Attempts to get an iterable's itemtype without iterating over it,
not even partly. Note that iterating over an iterable might modify
its inner state, e.g. if it is an iterator.
Note that obj is expected to be an iterable, not a typing.Iterable.
This function levera... | 10,027 |
def set_subscription_policy(project, subscription_id):
"""Sets the IAM policy for a topic."""
# [START pubsub_set_subscription_policy]
from google.cloud import pubsub_v1
# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"
client = pubsub_v1.Subscri... | 10,028 |
def getTimerIPs():
"""
returns list of ip addr
"""
client = docker.from_env()
container_list = client.containers.list()
timer_ip_list = []
for container in container_list:
if re.search("^timer[1-9][0-9]*", container.name):
out = container.exec_run("awk 'END... | 10,029 |
def analyze_elb_logs(bucket, key):
"""
This is the main function of the script. This function will trigger all the helper functions
In order to:
1. Get the Log file, unzip ip, load the requests.
2. Analyze the requests.
3. Save all bad requests in a database
"""
# Check that ... | 10,030 |
def country_buttons():
"""Generates the country buttons for the layout
TODO(@andreasfo@gmail.com)
Fix to use this one instead of the dropdown menu
Returns:
dbcButtonGroup -- A button group of all countries
"""
countries = [{'label': '🇸🇪 Sweden',
'value': 'Swede... | 10,031 |
def BRepBlend_BlendTool_NbSamplesV(*args):
"""
:param S:
:type S: Handle_Adaptor3d_HSurface &
:param v1:
:type v1: float
:param v2:
:type v2: float
:rtype: int
"""
return _BRepBlend.BRepBlend_BlendTool_NbSamplesV(*args) | 10,032 |
def patch_urllib(monkeypatch, requests_monitor):
"""
Patch urllib to provide the following features:
- Retry failed requests. Makes test runs more stable.
- Track statistics with RequestsMonitor.
Retries could have been implemented differently:
- In test.geocoders.util.GeocoderTestB... | 10,033 |
def get_response(session, viewstate, event_validation, event_target, outro=None, stream=False, hdfExport=''):
"""
Handles all the responses received from every request made to the website.
"""
url = "http://www.ssp.sp.gov.br/transparenciassp/"
data = [
('__EVENTTARGET', event_target),
... | 10,034 |
def test_permission_dependency_returns_requested_resource(mocker):
""" If a user has a permission, the resource should be returned """
mocker.patch("fastapi_permissions.has_permission", return_value=True)
mocker.patch("fastapi_permissions.Depends")
from fastapi_permissions import Depends, permission_de... | 10,035 |
def validate_method(method, version):
"""Confirm that the specified method / version combination is available and exit accordingly"""
try:
get_predictor(method, version)
except PredictorCreationException:
sys.exit(1)
sys.exit(0) | 10,036 |
def write_summary_to_aiplatform(metric_tag, destdir, metric):
"""Write a metric as a TF Summary.
AI Platform will use this metric for hyperparameters tuning.
Args:
metric_tag: A string with the tag used for hypertuning.
destdir: Destination path for the metric to be written.
metric: Value of the met... | 10,037 |
def matchVuln(vuln, element, criteria):
"""
================================================================================
Name:
matchVuln
Description:
Sets the finding details of a given VULN.
Parameter(s):
vuln: The VULN element to be searched.
element: ... | 10,038 |
def require(*modules):
"""Check if the given modules are already available; if not add them to
the dependency list."""
deplist = []
for module in modules:
try:
__import__(module)
except ImportError:
deplist.append(module)
return deplist | 10,039 |
def download_weekly_deaths_numbers_rki(data_path):
"""!Downloads excel file from RKI webpage
@param data_path Path where to store the file.
"""
name_file = "RKI_deaths_weekly.xlsx"
url = "https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Projekte_RKI/" \
"COVID-19_Todesfaelle.... | 10,040 |
def test_degree_centrality():
"""
The following test checks the degree centrality before any perturbation.
"""
g = GeneralGraph()
g.load("tests/TOY_graph.csv")
g.check_before()
g.degree_centrality()
degree_centrality = {
'1': 0.1111111111111111,
'2': 0.1111111111111111,
... | 10,041 |
def fixture_base_context(
env_name: str,
) -> dict:
"""Return a basic context"""
ctx = dict(
current_user="a_user",
current_host="a_host",
)
return ctx | 10,042 |
def parse_pharmvar(fn):
"""
Parse PharmVar gene data.
Parameters
----------
fn : str
Gene data directory.
"""
gene = os.path.basename(fn).split('-')[0]
rs_dict = {}
vfs = {'GRCh37': [], 'GRCh38': []}
alleles = {}
for i, assembly in enumerate(['GRCh37', 'GRCh38']):
... | 10,043 |
def test_index():
"""Test if you can mask out periodogram
"""
lc = LightCurve(time=np.arange(1000), flux=np.random.normal(1, 0.1, 1000),
flux_err=np.zeros(1000)+0.1)
p = lc.to_periodogram()
mask = (p.frequency > 0.1*(1/u.day)) & (p.frequency < 0.2*(1/u.day))
assert len(p[mask... | 10,044 |
def definition(server: KedroLanguageServer, params: TextDocumentPositionParams) -> Optional[List[Location]]:
"""Support Goto Definition for a dataset or parameter.
Currently only support catalog defined in `conf/base`
"""
if not server.is_kedro_project():
return None
document = server.works... | 10,045 |
def augmented_neighbors_list(q_id,
neighbors,
is_training,
processor,
train_eval=False):
"""Retrieve and convert the neighbors to a list.
Args:
q_id: a question id
neighbors: a table mapping ... | 10,046 |
def estimate_tau_exp(chains, **kwargs):
"""
Estimate the exponential auto-correlation time for all parameters in a chain.
"""
# Calculate the normalised autocorrelation function in each parameter.
rho = np.nan * np.ones(chains.shape[1:])
for i in range(chains.shape[2]):
try:
... | 10,047 |
def setobjattr(obj, key, value, set_obj=None):
"""Sets an object attribute with the correct data type."""
key = inflection.underscore(key)
if set_obj:
setattr(obj, key, set_obj(value))
else:
if isinstance(value, bool):
setattr(obj, key, bool(value))
else:
... | 10,048 |
def lda_model_onepass(dictionary, corpus, topics):
"""Create a single pass LDA model"""
start_time = time.time()
model = LdaMulticore(corpus, id2word = dictionary, num_topics = topics)
model.save(""./data/lda/all_topics_single.lda"")
print(model.print_topics(-1))
print("\nDone in {}".format(tim... | 10,049 |
def install(ctx: Context, requirement: Optional[str]):
"""Install the dependencies."""
_try_to_load_agent_config(ctx)
if requirement:
logger.debug("Installing the dependencies in '{}'...".format(requirement))
dependencies = list(map(lambda x: x.strip(), open(requirement).readlines()))
e... | 10,050 |
def test_magic_len():
"""Test the magic function __len__."""
signal = Signal([1, 2, 3], 44100)
assert len(signal) == 3 | 10,051 |
def paramclass(cls: type) -> type:
""" Parameter-Class Creation Decorator
Transforms a class-definition full of Params into a type-validated dataclass,
with methods for default value and description-dictionary retrieval.
Hdl21's `paramclass`es are immutable, strongly-typed data-storage structures. ... | 10,052 |
def text_process(mess):
"""
Takes in a string of text, then performs the following:
1. Remove all punctuation
2. Remove all stopwords
3. Returns a list of the cleaned text
"""
# Check characters to see if they are in punctuation
nopunc = [char for char in mess if char not in string.punct... | 10,053 |
def IntCurveSurface_ThePolyhedronToolOfHInter_IsOnBound(*args):
"""
:param thePolyh:
:type thePolyh: IntCurveSurface_ThePolyhedronOfHInter &
:param Index1:
:type Index1: int
:param Index2:
:type Index2: int
:rtype: bool
"""
return _IntCurveSurface.IntCurveSurface_ThePolyhedronToolOf... | 10,054 |
def read_mrc_like_matlab(mrc_file):
""" Read MRC stack and make sure stack is 'Fortran indexed' before returning it. """
mrc_stack = mrcfile.open(mrc_file).data
fortran_indexed_stack = c_to_fortran(mrc_stack)
return fortran_indexed_stack | 10,055 |
def freeze_session(session: tf.Session,
keep_var_names: List[str] = None,
output_names: List[str] = None,
clear_devices: bool = True) -> tf.GraphDef:
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph w... | 10,056 |
async def test_hassio_dont_update_instance(hass):
"""Test we can update an existing config entry."""
entry = MockConfigEntry(
domain=config_flow.DOMAIN,
data={config_flow.CONF_BRIDGEID: "id", config_flow.CONF_HOST: "1.2.3.4"},
)
entry.add_to_hass(hass)
result = await hass.config_ent... | 10,057 |
def preprocess(songs_path = SONGS_PATH):
"""
1. Loads the songs
2. Encode each song with a music time series representation
3. Save songs to text file
Arguments:
songs_path (str): path of the songs to be loaded
Returns:
None
"""
# 1. Lo... | 10,058 |
def linear_regression_noreg(X, y):
"""
Compute the weight parameter given X and y.
Inputs:
- X: A numpy array of shape (num_samples, D) containing feature.
- y: A numpy array of shape (num_samples, ) containing label
Returns:
- w: a numpy array of shape (D, )
"""
######################################... | 10,059 |
def _update_core_rrds(data, core_metrics_dir, rrdclient, step, sys_maj_min):
"""Update core rrds"""
interval = int(step) * 2
total = 0
for cgrp in data:
rrd_basename = CORE_RRDS[cgrp]
rrdfile = os.path.join(core_metrics_dir, rrd_basename)
rrd.prepare(rrdclient, rrdfile, step, i... | 10,060 |
def evaluation(evaluators, dataset, runners, execution_results, result_data):
"""Evaluate the model outputs.
Args:
evaluators: List of tuples of series and evaluation functions.
dataset: Dataset against which the evaluation is done.
runners: List of runners (contains series ids and loss... | 10,061 |
def bestof(reps, func, *args, **kwargs):
"""Quickest func() among reps runs.
Returns (best time, last result)
"""
best = 2 ** 32
for i in range(reps):
start = timer()
ret = func(*args, **kwargs)
elapsed = timer() - start
if elapsed < best: best = elapsed
return (b... | 10,062 |
def gdal_aspect_analysis(dem, output=None, flat_values_are_zero=False):
"""Return the aspect of the terrain from the DEM.
The aspect is the compass direction of the steepest slope (0: North, 90: East, 180: South, 270: West).
Parameters
----------
dem : str
Path to file storing DEM.
outpu... | 10,063 |
def _handle_braze_response(response: requests.Response) -> int:
"""Handles server response from Braze API.
The amount of requests made is well
below the limits for the given API endpoint therefore Too Many Requests
API errors are not expected. In case they do, however, occur - the API
calls will be... | 10,064 |
def unpack_file(filepath, tmpdir):
"""
Attempt to unpack file.
filepath is the path to the file that should be attempted unpacked.
tmpdir is a path to a temporary directory unique to this thread where
the thread will attempt to unpack files to.
Returns a list of unpacked files or an empty list.
... | 10,065 |
def test_refunds_create():
"""Should refund a charge"""
amount = 1000
email = "test-pymango@example.org"
charge = mango.Charges.create(amount=amount, email=email, token=_create_token())
ok_(charge)
charge_uid = charge.get("uid")
ok_(charge_uid)
refund = mango.Refunds.create(charge=charge... | 10,066 |
def xarray_image_as_png(img_data, loop_over=None, animate=False, frame_duration=1000):
"""
Render an Xarray image as a PNG.
:param img_data: An xarray dataset, containing 3 or 4 uint8 variables: red, greed, blue, and optionally alpha.
:param loop_over: Optional name of a dimension on img_data. If set,... | 10,067 |
def x_section_from_latlon(elevation_file,
x_section_lat0,
x_section_lon0,
x_section_lat1,
x_section_lon1,
as_polygon=False,
auto_clean=False):
"""
This wor... | 10,068 |
def convert_not_inline(line):
""" Convert the rest of part which are not inline code but might impact inline code
This part will dealing with following markdown syntax
- strong
- scratch
- italics
- image
- link
- checkbox
- highlight
:param line: str, the not inline code part ... | 10,069 |
def uniform_square_aperture(side, skypos, frequency, skyunits='altaz',
east2ax1=None, pointing_center=None,
power=False):
"""
-----------------------------------------------------------------------------
Compute the electric field or power pattern p... | 10,070 |
def set_gps_location(file_name, lat, lng):
"""Adds GPS position as EXIF metadata
Keyword arguments:
file_name -- image file
lat -- latitude (as float)
lng -- longitude (as float)
"""
global attribute
lat_deg = to_deg(lat, ["S", "N"])
lng_deg = to_deg(lng, ["W", "E"])
#print lat_deg
#print lng_deg
# co... | 10,071 |
def sources_table(citator):
"""
Return the content for an HTML table listing every template that the
citator can link to.
"""
rows = []
for template in citator.templates.values():
# skip templates that can't make URLs
if not template.__dict__.get('URL_builder'):
con... | 10,072 |
def parse_bot_commands(data, starterbot_id):
"""
Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None.
"""
user_id, message ... | 10,073 |
def construct_obj_in_dict(d: dict, cls: Callable) -> dict:
"""
Args
d (dict):
d[name][charge][annotation]
"""
if not isinstance(d, dict):
return d
else:
new_d = deepcopy(d)
for key, value in d.items():
if value.get("@class", "") == cls.__name__... | 10,074 |
def signup_user(request):
"""
Function to sing up user that are not admins
:param request: This param contain all the information associated to the request
:param type request: Request
:return: The URL to render
:rtype: str
"""
try:
log = LoggerManager('info', 'singup_manager-in... | 10,075 |
def haar_rand_state(dim: int) -> np.ndarray:
"""
Given a Hilbert space dimension dim this function returns a vector
representing a random pure state operator drawn from the Haar measure.
:param dim: Hilbert space dimension.
:return: Returns a dim by 1 vector drawn from the Haar measure.
"""
... | 10,076 |
def is_src_package(path: Path) -> bool:
"""Checks whether a package is of the form:
├─ src
│ └─ packagename
│ ├─ __init__.py
│ └─ ...
├─ tests
│ └─ ...
└─ setup.py
The check for the path will be if its a directory with only one subdirectory
containing an __init__.py f... | 10,077 |
def plot_timeseries(
data=None,
cmap=None,
plot_kwargs=dict(marker=".", markersize=3),
figsize=(10, 5),
verbose=True,
**params,
):
"""
Plot timeseries from multiple stations on a single plot for each variable.
Parameters
----------
data : output from stations_timeseries or N... | 10,078 |
def value_element(units=(OneOrMore(T('NN')) | OneOrMore(T('NNP')) | OneOrMore(T('NNPS')) | OneOrMore(T('NNS')))('raw_units').add_action(merge)):
"""
Returns an Element for values with given units. By default, uses tags to guess that a unit exists.
:param BaseParserElement units: (Optional) A parser element ... | 10,079 |
def get_pattern(model_id, release_id) -> list:
"""
content demo:
[
'...',
{
0.1: [
['if', 'checker.check'],
3903,
['if', 'checker.check', '*', Variable(name="ip", value='10.0.0.1')],
['if checker.check():', 'if check... | 10,080 |
def bit_remove(bin_name, byte_offset, byte_size, policy=None):
"""Creates a bit_remove_operation to be used with operate or operate_ordered.
Remove bytes from bitmap at byte_offset for byte_size.
Args:
bin_name (str): The name of the bin containing the map.
byte_offset (int): Position of b... | 10,081 |
def _log_request(request):
"""Log a client request. Copied from msrest
https://github.com/Azure/msrest-for-python/blob/3653d29fc44da408898b07c710290a83d196b777/msrest/http_logger.py#L39
"""
if not logger.isEnabledFor(logging.DEBUG):
return
try:
logger.info("Request URL: %r", request... | 10,082 |
def visualize(temporal_networks,
frame_dt,
time_normalization_factor=1,
time_unit=None,
titles=None,
config=None,
port=8226,
export_path=None,
):
"""
Visualize a temporal network or a list of temporal... | 10,083 |
def has_session_keys_checksums(session_key_checksums):
"""Check if this session key is (likely) already used."""
assert session_key_checksums, 'Eh? No checksum for the session keys?'
LOG.debug('Check if session keys (hash) are already used: %s', session_key_checksums)
with connection.cursor() as cur:
... | 10,084 |
def four2five(data, format_, dst_dtype='float16', need_custom_tiling=True):
"""
Convert 4-dims "data" to 5-dims,the format of "data" is defined in "format_"
Args:
data (tvm.tensor.Tensor): 4-dims tensor of type float16, float32
format_ (str): a str defined the format of "data"
dst_d... | 10,085 |
def MT33_SDR(MT33):
"""Converts 3x3 matrix to strike dip and rake values (in radians)
Converts the 3x3 Moment Tensor to the strike, dip and rake.
Args
MT33: 3x3 numpy matrix
Returns
(float, float, float): tuple of strike, dip, rake angles in radians
(Note: Function from MTFIT.MTconv... | 10,086 |
def get_commits_by_tags(repository: Repo, tag_filter_pattern: str, starting_tag: Optional[str] = None) -> List[dict]:
"""
Group commits by the tags they belong to.
Args:
repository: The git repository object
tag_filter_pattern: A regular expression pattern that matches valid tags as version... | 10,087 |
def test_get_missing_recipe():
"""
Return 404 for a recipe that is not there.
"""
http = httplib2.Http()
response, content = http.request('http://our_test_domain:8001/recipes/not_there',
method='GET')
assert response['status'] == '404' | 10,088 |
def GetObject():
"""
Required module function.
@returns class object of the implemented adapter.
"""
return SpacePacketAdapter | 10,089 |
def prepare_environment(base_path):
"""
Creates ASSETS_PATH folder if not created and removes existing folder
"""
assets = Path(base_path)
if assets.exists():
shutil.rmtree(assets)
assets.mkdir(parents=True) | 10,090 |
def filter_paths(ctx, raw_paths, path_type="repo", **kwds):
"""Filter ``paths``.
``path_type`` is ``repo`` or ``file``.
"""
cwd = os.getcwd()
filter_kwds = copy.deepcopy(kwds)
changed_in_commit_range = kwds.get("changed_in_commit_range", None)
diff_paths = None
if changed_in_commit_ran... | 10,091 |
def hic2cool_convert(infile, outfile, resolution=0, nproc=1, show_warnings=False, silent=False):
"""
Main function that coordinates the reading of header and footer from infile
and uses that information to parse the hic matrix.
Opens outfile and writes in form of .cool file
Params:
<infile> str... | 10,092 |
def show_help( ):
""" displays the program parameter list and usage information """
stdout( "usage: " + sys.argv[0] + " -f <fasta> ")
stdout( " " )
stdout( " option description" )
stdout( " -h help (this text here)" )
stdout( " -f fasta file" )
stdout( " " )
sys.exit(1) | 10,093 |
def parse(args):
"""Parse the command-line arguments of the `inpaint` command.
Parameters
----------
args : list of str
List of arguments, without the command name.
Returns
-------
InPaint
Filled structure
"""
struct = InPaint()
struct.files = []
while cl... | 10,094 |
def test_taxi_trips_benchmark(
benchmark: BenchmarkFixture,
tmpdir: py.path.local,
pytestconfig: _pytest.config.Config,
number_of_tables: int,
write_data_docs: bool,
backend_api: str,
):
"""Benchmark performance with a variety of expectations using NYC Taxi data (yellow_trip_data_sample_2019... | 10,095 |
def log_context(servicer_context: Mock) -> LogContext:
"""Mock LogContext."""
context = LogContext(
servicer_context,
"/abc.test/GetTest",
Mock(name="Request"),
Mock(name="Response", ByteSize=Mock(return_value=10)),
datetime(2021, 4, 3, 0, 0, 0, 0, timezone.utc),
... | 10,096 |
def filename(name):
""" Get filename without extension"""
return os.path.splitext(name)[0] | 10,097 |
def test_get_processed_string_single_expression_keeps_type():
"""Process string with interpolation honors type."""
context = Context(
{'ctx1': 'ctxvalue1',
'ctx2': 'ctxvalue2',
'ctx3': [0, 1, 3],
'ctx4': 'ctxvalue4'})
input_string = '{ctx3}'
output = context.get_form... | 10,098 |
def base64_decode(string):
"""
Decodes data encoded with MIME base64
"""
return base64.b64decode(string) | 10,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.