content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def client():
"""Client Fixture."""
client_obj = Client(base_url=BASE_URL)
return client_obj | 36,000 |
def encode_one_hot(s):
"""One-hot encode all characters of the given string.
"""
all = []
for c in s:
x = np.zeros((INPUT_VOCAB_SIZE))
index = char_indices[c]
x[index] = 1
all.append(x)
return all | 36,001 |
def date_to_datetime(date, time_choice='min'):
"""
Convert date to datetime.
:param date: date to convert
:param time_choice: max or min
:return: datetime
"""
choice = getattr(datetime.datetime, 'min' if time_choice == 'min' else 'max').time()
return timezone.make_aware(
datetim... | 36,002 |
def standardize_cell(atoms, cell_type):
""" Standardize the cell of the atomic structure.
Parameters:
atoms: `ase.Atoms`
Atomic structure.
cell_type: { 'standard', 'standard_no_symmetries', 'primitive', None}
Starting from the input cell, creates a standard cell according to same stan... | 36,003 |
def test_store(benchmark):
"""Benchmark for creating and storing a node,
via the full ORM mechanism.
"""
_, node_dict = benchmark(get_data_node)
assert node_dict['node'].is_stored, node_dict | 36,004 |
def get_biggan_stats():
""" precomputed biggan statistics """
center_of_mass = [137 / 255., 127 / 255.]
object_size = [213 / 255., 210 / 255.]
return center_of_mass, object_size | 36,005 |
def get_input_var_value(soup, var_id):
"""Get the value from text input variables.
Use when you see this HTML format:
<input id="wired_config_var" ... value="value">
Args:
soup (soup): soup pagetext that will be searched.
var_id (string): The id of a var, used to find its value.
R... | 36,006 |
def _create_file(path):
"""Opens file in write mode. It also creates intermediate directories if
necessary.
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
return open(path, 'w') | 36,007 |
def get_top(metric: str, limit: int) -> List[List[Any]]:
"""Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor]
Parameters
----------
metric : str
Metric to get top tickers for
limit : int
Number of tickes to get
Returns
-------
List[List[A... | 36,008 |
def check_realm_emoji_update(var_name: str, event: Dict[str, object]) -> None:
"""
The way we send realm emojis is kinda clumsy--we
send a dict mapping the emoji id to a sub_dict with
the fields (including the id). Ideally we can streamline
this and just send a list of dicts. The clients can make
... | 36,009 |
def test_add_single_entities(
reference_data: np.ndarray,
upper_bound: np.ndarray,
lower_bound: np.ndarray,
ishan: Entity,
) -> None:
"""Test the addition of SEPTs"""
tensor1 = SEPT(
child=reference_data, entity=ishan, max_vals=upper_bound, min_vals=lower_bound
)
tensor2 = SEPT(
... | 36,010 |
def prob_get_expected_after_certain_turn(turns_later: int, turns_remain: int,
tiles_expect: int) -> float:
"""The probability of get expected tile after `turns_later` set of turns.
:param turns_later: Get the expected tile after `turns_after` set of turns
:param tur... | 36,011 |
def do_1D(g=GerryMander(algorithm="brute-force"), rounds=5):
""" """
for n_dists in [3, 9, 27]:
for units_in_dist in [3, 5, 9, 27]:
for unit_size in [1, 10, 100]:
m = Model(n_dims=1, unit_size=unit_size, n_dists=n_dists,
units_in_dist=units_in_dist)
... | 36,012 |
def build(gpu, cudnn, opencv, openmp, force, root):
"""Build darknet."""
darknet = pydarknet2.Darknet(root=root)
darknet.build(gpu=gpu, cudnn=cudnn, opencv=opencv, openmp=openmp, force=force) | 36,013 |
def get_gpcr_calpha_distances(pdb, xtc, gpcr_name, res_dbnum,
first_frame=0, last_frame=-1, step=1):
"""
Load distances between all selected atoms.
Parameters
----------
pdb : str
File name for the reference file (PDB or GRO format).
xtc : str
File ... | 36,014 |
def main(yumrepomap=None,
**kwargs):
"""
Checks the distribution version and installs yum repo definition files
that are specific to that distribution.
:param yumrepomap: list of dicts, each dict contains two or three keys.
'url': the url to the yum repo definition file
... | 36,015 |
def schedule_fetch():
"""Enqueues tasks to fetch instances."""
for instance_group_manager in models.InstanceGroupManager.query():
if instance_group_manager.url:
utilities.enqueue_task('fetch-instances', instance_group_manager.key) | 36,016 |
def detectRegions(image, er_filter1, er_filter2):
""" detectRegions(image, er_filter1, er_filter2) -> regions """
pass | 36,017 |
def zero_pad1d(inputs, padding=0):
"""Zero padding for 1d tensor
Args:
-----------------------------
inputs : tvm.te.tensor.Tensor
shape [batch, channel, length]
padding: (optional:0) int or tuple
-----------------------------
Returns:
-----------------------------
tvm.te.t... | 36,018 |
def gelu(x):
"""gelu activation function copied from pytorch-pretrained-BERT."""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) | 36,019 |
def section11():
"""
# Show Annotations Over Image
After uploading items and annotations with their metadata, you might want to see some of them and perform visual validation.
To see only the annotations, use the annotation type *show* option.
""" | 36,020 |
def stock_fund_stock_holder(stock: str = "600004") -> pd.DataFrame:
"""
新浪财经-股本股东-基金持股
https://vip.stock.finance.sina.com.cn/corp/go.php/vCI_FundStockHolder/stockid/600004.phtml
:param stock: 股票代码
:type stock: str
:return: 新浪财经-股本股东-基金持股
:rtype: pandas.DataFrame
"""
url = f"https://v... | 36,021 |
def set_to_available(request, slug, version):
"""
Updates the video status.
Sets the version already encoded to available.
"""
video = get_object_or_404(Video, slug=slug)
status, created = VideoStatus.objects.get_or_create(video_slug=slug)
if version == 'web':
status.web_availa... | 36,022 |
def run_test(test):
""" Make the request """
print(bcolors.HEADER + "Running test: "+ test + bcolors.ENDC)
results = dict()
with open(pathlib.Path(test,"test.ini"), "r") as testini:
testini_json = json.loads(testini.read())
if "IGNORE" in testini_json.keys():
results[testini... | 36,023 |
def datetime_to_str(dct, attr_name):
"""Convert datetime object in dict to string."""
if (dct.get(attr_name) is not None and
not isinstance(dct.get(attr_name), six.string_types)):
dct[attr_name] = dct[attr_name].isoformat(' ') | 36,024 |
def new_reps_reminder():
"""Send email to reps-mentors listing new subscribers the past month."""
prev = go_back_n_months(now().date())
prev_date = prev.strftime('%B %Y')
reps = UserProfile.objects
reps_num = reps.count()
new_reps = reps.filter(date_joined_program__month=prev.month)
email_... | 36,025 |
def generate_solve_c():
"""Generate C source string for the recursive solve() function."""
piece_letters = 'filnptuvwxyz'
stack = []
lines = []
add = lines.append
add('#define X_PIECE_NUM {}'.format(piece_letters.index('x')))
add("""
void solve(char* board, int pos, unsigned int used) {
... | 36,026 |
def process_ax_data(user, ax_data):
"""
Process OpenID AX data.
"""
import django_openidconsumer.config
emails = ax_data.get(django_openidconsumer.config.URI_GROUPS.get('email').get('type_uri', ''), '')
display_names = ax_data.get(django_openidconsumer.config.URI_GROUPS.get('alias').get('ty... | 36,027 |
def get_permission_info(room):
"""
Fetches permissions about the room, like ban info etc.
# Return Value
dict of session_id to current permissions,
a dict containing the name of the permission mapped to a boolean value.
"""
return jsonify({k: addExtraPermInfo(v) for k, v in room.permission... | 36,028 |
def ravel(m):
"""ravel(m) returns a 1d array corresponding to all the elements of it's
argument.
"""
return reshape(m, (-1,)) | 36,029 |
async def test_if_fires_on_zone_appear(hass, calls):
"""Test for firing if entity appears in zone."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "geo_location",
... | 36,030 |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
# My additions
print ("Printing this unstripped text:", line)
index.append(int(line.strip()))
return index | 36,031 |
def init():
"""Top level command handler."""
@click.command()
@click.option('--port', type=int, help='Port to listen.', default=0)
@click.option('--tun-dev', type=str, required=True,
help='Device to use when establishing tunnels.')
@click.option('--tun-addr', type=str, required=Fa... | 36,032 |
def check_collision(bird_rect:object, pipes:list, collide_sound:object):
""" Checks for collision with the Pipe and the Base """
for pipe in pipes:
if bird_rect.colliderect(pipe):
collide_sound.play()
return False
if bird_rect.bottom >= gv.BASE_TOP:
return False
r... | 36,033 |
def compute_ranking_scores(ranking_scores,
global_ranks_to_save,
rank_per_query):
""" Compute ranking scores (MRR and MAP) and a bunch of interesting ranks to save to file from a list of ranks.
Args:
ranking_scores: Ranking scores previously compute... | 36,034 |
def AirAbsorptionRelaxationFrequencies(T,p,H,T0, p_r):
"""
Calculates the relaxation frequencies for air absorption conforming to
ISO 9613-1. Called by :any:`AirAbsorptionCoefficient`.
Parameters
----------
T : float
Temperature in K.
p : float
Pressure in Pa.
H : float
... | 36,035 |
def test_plot_raw_ssp_interaction(raw, browser_backend):
"""Test SSP projector UI of plot_raw()."""
with raw.info._unlock():
raw.info['lowpass'] = 10. # allow heavy decim during plotting
# apply some (not all) projs to test our proj UI (greyed out applied projs)
projs = raw.info['projs'][-2:]
... | 36,036 |
def set_edit_mode(request, state):
"""
Enable the edit mode; placeholders and plugins will be wrapped in a ``<div>`` that exposes metadata for frontend editing.
"""
setattr(request, '_fluent_contents_edit_mode', bool(state)) | 36,037 |
def table_from_bool(ind1, ind2):
"""
Given two boolean arrays, return the 2x2 contingency table
ind1, ind2 : array-like
Arrays of the same length
"""
return [
sum(ind1 & ind2),
sum(ind1 & ~ind2),
sum(~ind1 & ind2),
sum(~ind1 & ~ind2),
... | 36,038 |
def test(device):
"""
Test if get_inlet_pressure_for_gain_correction() returns the value
previously set with set_inlet_pressure_for_gain_correction().
"""
result = device.set_inlet_pressure_for_gain_correction(2.345)
assert result is None
result = device.get_inlet_pressure_for_gain_correctio... | 36,039 |
def getHWBeatLEDState(*args, **kwargs):
""" get HWBeatLEDState """
pass | 36,040 |
def preprocess_skills(month_kpi_skills: pd.DataFrame, quarter_kpi_skills: pd.DataFrame) -> pd.DataFrame:
"""
Функция принимает на вход два DataFrame:
- с данными по KPI сотрудников ВЭД за последний месяц
- с данными по KPI сотрудников ВЭД за последний квартал
Возвращает объединенный DataFrame по дву... | 36,041 |
def bias_col_spline(im, overscan, dymin=5, dymax=2, statistic=np.mean, **kwargs):
"""Compute the offset by fitting a spline to the mean of each row in the
serial overscan region.
Args:
im: A masked (lsst.afw.image.imageLib.MaskedImageF) or unmasked
(lsst.afw.image.imageLib.ImageF) afw i... | 36,042 |
def read_config():
""" Returns the decoded config data in 'db_config.json'
Will return the decoded config file if 'db_config.json' exists and is a valid JSON format.
Otherwise, it will return a False.
"""
# Check if file exists
if not os.path.isfile('db_config.json'):
return False
#... | 36,043 |
def get_sub_title_from_series(ser: pandas.Series, decimals: int = 3) -> str:
"""pandas.Seriesから、平均値、標準偏差、データ数が記載されたSubTitleを生成する。"""
mean = round(ser.mean(), decimals)
std = round(ser.std(), decimals)
sub_title = f"μ={mean}, α={std}, N={len(ser)}"
return sub_title | 36,044 |
def pk_init():
"""PK项目初始化"""
for pk_data in setting.pk_datas():
if pk_data['title'] in pk_mission_started:
continue
if pk_data['battle_config']['type'] == 'increase':
if time.mktime(time.strptime(pk_data['start_time'],
'%Y-%m-%d %H... | 36,045 |
def deploy(branch='release', path='/readux.io/readux'):
"""Execute group of tasks for deployment.
:param branch: Git branch to clone, defaults to 'master'
:type branch: str, optional
"""
options = {
'REPO_URL': 'https://github.com/ecds/readux.git',
'ROOT_PATH': path,
'VENV_P... | 36,046 |
def write_pptables(f, dimension, captionStringFormat):
"""Writes line for pptables images."""
headerERT = 'Table showing the ERT in number of function evaluations divided by' \
'the best ERT measured during BBOB-2009 for dimension %d' % dimension
f.write("\n<H2> %s </H2>\n" % headerERT... | 36,047 |
def atand2(delta_y: ArrayLike, delta_x: ArrayLike) -> ArrayLike:
"""Return the arctan2 of an angle specified in degrees.
Returns
-------
float
An angle, in degrees.
"""
return numpy.degrees(numpy.arctan2(delta_y, delta_x)) | 36,048 |
def adjust_doy_calendar(
source: xr.DataArray, target: Union[xr.DataArray, xr.Dataset]
) -> xr.DataArray:
"""Interpolate from one set of dayofyear range to another calendar.
Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1
to 365).
Parameters... | 36,049 |
def _maintainer_change(change_list: ChangeList, old: Data, new: Data):
"""
Appends a summary of a change to a dataset's maintainer field between two
versions (old and new) to change_list.
"""
# if the old dataset had a maintainer
if old.get("maintainer") and new.get("maintainer"):
change... | 36,050 |
def iou(box_a, box_b):
"""Calculates intersection area / union area for two bounding boxes."""
assert area(box_a) > 0
assert area(box_b) > 0
intersect = np.array(
[[max(box_a[0][0], box_b[0][0]),
max(box_a[0][1], box_b[0][1])],
[min(box_a[1][0], box_b[1][0]),
min(box_a[1][1], box_b[... | 36,051 |
def view_routes_asa() -> None:
"""View all database entries"""
get_tables_names()
for table in route_tables:
get_table_rows = [row for row in cursor.execute('SELECT count(*) FROM {}'.format(table))]
if get_table_rows[0][0] == 0:
continue
else:
print(... | 36,052 |
def poll():
"""
The send buffer is flushed and any outstanding CA background activity is processed.
.. note:: same as pend_event(1e-12)
"""
status = libca.ca_pend_event(1e-12)
return ECA(status) | 36,053 |
def TopLevelWindow_GetDefaultSize(*args):
"""TopLevelWindow_GetDefaultSize() -> Size"""
return _windows_.TopLevelWindow_GetDefaultSize(*args) | 36,054 |
def human_size(numbytes):
"""converts a number of bytes into a readable string by humans"""
KB = 1024
MB = 1024*KB
GB = 1024*MB
TB = 1024*GB
if numbytes >= TB:
amount = numbytes / TB
unit = "TiB"
elif numbytes >= GB:
amount = numbytes / GB
unit = "GiB"
el... | 36,055 |
def parse_args():
"""
Parse command-line arguments to train and evaluate a multimodal network for activity recognition on MM-Fit.
:return: Populated namespace.
"""
parser = argparse.ArgumentParser(description='MM-Fit Demo')
parser.add_argument('--data', type=str, default='mm-fit/',
... | 36,056 |
def get_argument_defaults(node: ast.arguments) -> typing.Iterable:
"""Gets the defaults for the arguments in an ast.arguments node"""
total_positional_arguments = len(node.posonlyargs) + len(node.args)
positional_defaults = pad_defaults_list(node.defaults, total_positional_arguments)
for default in po... | 36,057 |
def node_definitions(
id_fetcher: Callable[[str, GraphQLResolveInfo], Any],
type_resolver: GraphQLTypeResolver = None,
) -> GraphQLNodeDefinitions:
"""
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
... | 36,058 |
def create_viewer_node(scene, preceeding_node_name, preceeding_channel_name):
"""
For debug purposes. Allows to visualize intermediate nodes.
:param scene:
:param preceeding_node_name:
:param preceeding_channel_name:
:return:
"""
logger.info('create_viewer_node: ...')
scene_nodes =... | 36,059 |
def get_image_from_request(request):
"""
This function is used to extract the image from a POST or GET request.
Usually it is a url of the image and, in case of the POST is possible
to send it as a multi-part data.
Returns a tuple with (ok:boolean, error:string, image:ndarray)
"""
if reques... | 36,060 |
def con_external():
"""Define a connection fixture.
Returns
-------
ibis.omniscidb.OmniSciDBClient
"""
omnisci_client = ibis.omniscidb.connect(
user=EXT_OMNISCIDB_USER,
password=EXT_OMNISCIDB_PASSWORD,
host=EXT_OMNISCIDB_HOST,
port=EXT_OMNISCIDB_PORT,
data... | 36,061 |
def parse_risk(data_byte_d):
"""Parse and arrange risk lists.
Parameters
----------
data_byte_d : object
Decoded StringIO object.
Returns
-------
neocc_lst : *pandas.Series* or *pandas.DataFrame*
Data frame with risk list data parsed.
"""
# Read data as csv
neoc... | 36,062 |
def prime_site_stats_cache():
"""
Collect stats for site and prime the cache. Run this as a scheduled task to
improve performance.
"""
logging.debug("Starting scheduled cache priming...")
cache.set("site_total_communities", social_models.GamerCommunity.objects.count())
cache.set("site_total_... | 36,063 |
def plot_step_w_variable_station_filters(df, df_stations=None, options=None):
"""
"""
p = PlotStepWithControls(df, df_stations, options)
return p.plot() | 36,064 |
def pick_random_element(count):
"""
Parameters
----------
count: {string: int}
A dictionary of all transition
counts from some state
we're in to all other states
Returns
-------
The next character, randomly sampled
from the empirical probabilities
determined f... | 36,065 |
def do_flake8() -> str:
"""
Flake8 Checks
"""
command = "flake8"
check_command_exists(command)
command_text = f"flake8 --config {settings.CONFIG_FOLDER}/.flake8"
command_text = prepinform_simple(command_text)
execute(*(command_text.split(" ")))
return "flake 8 succeeded" | 36,066 |
def _download_repo(repo_path):
"""
Download Google's repo.
"""
logger.info('Fetching repo')
repo_url = CONSTANTS['repo']['url']
response = requests.get(repo_url)
if response.status_code != 200:
raise CommandError('Unable to download repo from %s' % repo_url)
with open(repo_pat... | 36,067 |
def counter_current_heat_exchange(s0_in, s1_in, s0_out, s1_out,
dT, T_lim0=None, T_lim1=None,
phase0=None, phase1=None,
H_lim0=None, H_lim1=None):
"""
Allow outlet streams to exchange heat until either the give... | 36,068 |
def ReadCOSx1dsumSpectrum(filename):
"""
filename with full path
Purporse is to have other variation
of files and differnet way of reading in.
"""
wave,flux,dfp,dfm = np.loadtxt(filename,unpack=True,usecols=[0,1,4,5])
return np.array([wave,flux,dfp,dfm]) | 36,069 |
def parse_args():
"""Use argparse to get command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--task', '-t', choices=['seg', 'det', 'drivable',
'det-tracking'])
parser.add_argument('--gt', '-g', help='path to ground truth')
parser.add_argument('-... | 36,070 |
def op_atanh(x):
"""Returns the inverse hyperbolic tangent of this mathematical object."""
if isinstance(x, list):
return [op_atanh(a) for a in x]
elif isinstance(x, complex):
return cmath.atanh(x)
else:
return math.atanh(x) | 36,071 |
def find_intersections(
solutions: Mapping[Any, Callable],
ray_direction: Array,
target_center: Array,
) -> dict:
"""
find intersections between ray_direction and target_center given a mapping
of functions (like output of `solutions.make_ray_sphere_lambdas`)
"""
# suppress irrelevant war... | 36,072 |
def _add_url(id_or_url: str, new_url: str):
"""Add a url from a select novel"""
controllers.add_url(id_or_url, new_url) | 36,073 |
def Circum_O_R(vertex_pos, tol):
"""
Function finds the center and the radius of the circumsphere of the every tetrahedron.
Reference:
Fiedler, Miroslav. Matrices and graphs in geometry. No. 139. Cambridge University Press, 2011.
Parameters
-----------------
vertex_pos :
The positio... | 36,074 |
def reverse_one_hot(image):
"""
Transform a 2D array in one-hot format (depth is num_classes),
to a 2D array with only 1 channel, where each pixel value is
the classified class key.
#Arguments
image: The one-hot format image
#Returns
A 2D array with the same width and height a... | 36,075 |
def get_feature_clusters(x: torch.Tensor, output_size: int, clusters: int = 8):
""" Applies KMeans across feature maps of an input activations tensor """
if not isinstance(x, torch.Tensor):
raise NotImplementedError(f"Function supports torch input tensors only, but got ({type(x)})")
if x.ndim == 3:... | 36,076 |
def not_enough_params(user: server.UserConnection, command: str) -> None:
"""Sent when a user sends a command to the server that does not contain all required arguments."""
message = f"461 {user.nick} {command} :Not enough parameters"
user.send_que.put((message, "mantatail")) | 36,077 |
def get_phone_operator(phonenumber):
"""
Get operator type for a given phonenumber.
>>> get_phone_operator('+959262624625')
<Operator.Mpt: 'MPT'>
>>> get_phone_operator('09970000234')
<Operator.Ooredoo: 'Ooredoo'>
>>> get_phone_operator('123456789')
<Operator.Unknown: 'Unknown'>
"""... | 36,078 |
def projectpoints(P, X):
""" Apply full projection matrix P to 3D points X in cartesian coordinates.
Args:
P: projection matrix
X: 3d points in cartesian coordinates
Returns:
x: 2d points in cartesian coordinates
"""
X_hom = cart2hom(X)
X_pro = P.dot(X_hom) # 像素坐标系 齐次三维坐标
x = hom2cart(X_... | 36,079 |
def getDMI():
"""
Read hardware information from DMI.
This function attempts to read from known files in /sys/class/dmi/id/. If
any are missing or an error occurs, those fields will be omitted from the
result.
Returns: a dictionary with fields such as bios_version and product_serial.
"""
... | 36,080 |
def mdot(a,b):
"""
Computes a contraction of two tensors/vectors. Assumes
the following structure: tensor[m,n,i,j,k] OR vector[m,i,j,k],
where i,j,k are spatial indices and m,n are variable indices.
"""
if (a.ndim == 3 and b.ndim == 3) or (a.ndim == 4 and b.ndim == 4):
c = (a*b).sum... | 36,081 |
def GetDeviceProtocolController(protocol): # real signature unknown; restored from __doc__
"""
GetDeviceProtocolController(protocol)
Creates a :class:`DeviceProtocolController` that provides device-specific controls.
This interface is intended to allow closer integration with remote devices.
... | 36,082 |
def sample_duration(sample):
"""Returns the duration of the sample (in seconds)
:param sample:
:return: number
"""
return sample.duration | 36,083 |
def test_get_temperature_conv_errors(caplog):
"""Test errors when requesting temperature conversion"""
# ValueError should be raised if you try to convert a unit to itself
with pytest.raises(ValueError):
utils.get_temperature_conversion('degK', 'K')
assert 'Cannot convert unit to itself' in capl... | 36,084 |
def fetch_commons_memberships(from_date=np.NaN,
to_date=np.NaN,
on_date=np.NaN):
"""Fetch Commons memberships for all MPs.
fetch_commons_memberships fetches data from the data platform showing
Commons memberships for each MP. The memberships are ... | 36,085 |
def async_push_message(send_to, content):
"""
模拟异步推送消息
:param send_to:
:param content:
:return:
"""
logging.info('模拟异步推送消息')
logging.info('send_to: {}'.format(send_to))
logging.info('content: {}'.format(content))
# 休眠
sleep(10) | 36,086 |
def ensure_dir_empty(dirpath):
""" remove files from dir """
if not os.path.exists(dirpath):
os.mkdir(dirpath)
for fname in os.listdir(dirpath):
fpath = os.path.join(dirpath, fname)
if os.path.isfile(fpath):
os.remove(fpath) | 36,087 |
def check_single_row(row, msg):
"""Checks whether the provided list of rows has only 1 element.
Args:
row: the list of rows.
msg: the error message to raise if there are no rows found.
Raises:
ValueError: if no rows are found.
RuntimeError: if more than one row is found.
... | 36,088 |
def excel_col_w_fitting(excel_path, sheet_name_list):
"""
This function make all column widths of an Excel file auto-fit with the column content.
:param excel_path: The Excel file's path.
:param sheet_name_list: The sheet names of the Excel file.
:return: File's column width correctly formatted.
... | 36,089 |
def load_meetings(root=public_meetings.data_root,
ext=public_meetings.file_ext):
"""
Load all meetings from `root` ending with `ext`
Args:
root(str): root meeting directory
ext(str): file extension
Returns:
meetings(dict): a dictionnary... | 36,090 |
def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... | 36,091 |
def test_edge_init_no_direction(db_3_vertices):
"""Test if vertices are sorted by place when the edge is not oriented."""
db, v1, v2, v3 = db_3_vertices
e1 = Edge(v1, v2, has_direction=False)
assert e1.start is v1
assert e1.end is v2
e2 = Edge(v3, v2, has_direction=False)
assert e2.start is ... | 36,092 |
def padding_reflect(image, pad_size):
"""
Padding with reflection to image by boarder
Parameters
----------
image: NDArray
Image to padding. Only support 2D(gray) or 3D(color)
pad_size: tuple
Padding size for height adn width axis respectively
Returns
-------
ret: N... | 36,093 |
def check_if_all_elements_have_geometry(geodataframes_list):
"""
Iterates over a list and checks if all members of the list have geometry
information associated with them.
Parameters
----------
geodataframes_list : A list object
A list object that contains one or more geopandas.GeoDataF... | 36,094 |
def conference_schedule(parser, token):
"""
{% conference_schedule conference schedule as var %}
"""
contents = token.split_contents()
tag_name = contents[0]
try:
conference = contents[1]
schedule = contents[2]
var_name = contents[4]
except IndexError:
raise t... | 36,095 |
def test_trainer_loggers_property():
"""Test for correct initialization of loggers in Trainer."""
logger1 = CustomLogger()
logger2 = CustomLogger()
# trainer.loggers should be a copy of the input list
trainer = Trainer(logger=[logger1, logger2])
assert trainer.loggers == [logger1, logger2]
... | 36,096 |
def make_index(genome_fasta, output_dir, cores,
cg, chg, chh, cwg, triplet_seq, seq_context) -> None:
"""Create augmented index files
Can add triplet seq and more general sequence context information.
"""
if chg and cwg:
raise ValueError("--chg and --cwg are mutually exclusive!")... | 36,097 |
def run_delete_process() -> Tuple[str, http.HTTPStatus]:
"""Handles deleting tasks pushed from Task Queue."""
return _run_process(constants.Operation.DELETE) | 36,098 |
def annotate(f, expr, ctxt):
"""
f: function argument
expr: expression
ctxt: context
:returns: type of expr
"""
t = f(expr, ctxt)
expr.type = t
return t | 36,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.