content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cmap_map(function, cmap):
""" from scipy cookbook
Applies function (which should operate on vectors of shape 3: [r, g, b], on colormap cmap.
This routine will break any discontinuous points in a colormap.
"""
cdict = cmap._segmentdata
step_dict = {}
# Firt get the list of points where th... | 5,318,800 |
def _save_video(img, fps, framejump, mode, ratio):
""" Saves the image to a video
Parameters
----------
img : np.ndarray - the image as an array
fps : int - the desired frames per second of the video
framejump : int - the number of pixels to move between frames
mode : str - "portrai... | 5,318,801 |
def get_legislation_passed_legislature_within_time_frame(
begin_date: datetime, end_date: datetime
) -> Dict[str, Any]:
"""See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetLegislationPassedLegislatureWithinTimeFrame"""
argdict: Dict[str, Any] = dict(beginDate=begin_date, endDate=end_date)... | 5,318,802 |
def find_output(directory, extension="out", abspath=True):
""" Find output file in a directory.
Parameters
----------
directory : str
Path to folder in which output should be located.
extension : str
File extension of output file (default: 'out').
abspath : bool
Whether ... | 5,318,803 |
def trim_mismatches(gRNA):
"""
trim off 3' mismatches
1. first trim to prevent long alignments past end of normal expressed gRNAs
2. second trim to mismatches close to end of gRNA
"""
pairing = gRNA['pairing']
# 1. index of right-most mismatch before index -40
# if no MM is... | 5,318,804 |
def validateRequest(endpoint, params):
"""Validate that a valid argument with the correct number of parameters has been supplied."""
if endpoint not in endpoints:
helpInfo = ", ".join(endpoints.keys())
print(f"Invalid endpoint. Please use one of the following: {helpInfo}")
return False
... | 5,318,805 |
def augment_sequence(seq):
""" Flip / rotate a sequence with some random variations"""
imw, imh = 1024, 570
if random.random()>0.5:
for frame in range(len(seq)):
for m in [0, 1]:
seq[frame][m][0] = imw-seq[frame][m][0] # X flip
if random.random()>0.5:
for fram... | 5,318,806 |
def show_rules():
"""Print all URL resolution rules
:return:
"""
if os.path.exists(PATHRULES):
rules = pickle.load(open(PATHRULES, "rb"))
for rule in rules:
print(rule + " : " + rules[rule])
else:
print("Rules file doesn't exist") | 5,318,807 |
def dme(network, threshold=90, n_components=10, return_result=False, **kwargs):
"""
Threshold, cosine similarity, and diffusion map embed `network`
Parameters
----------
network : (N, N) array_like
Symmetric network on which to perform diffusion map embedding
threshold : [0, 100] float,... | 5,318,808 |
def _calc_poly_pud(
local_qt_pickle_path, aoi_path, date_range, poly_test_queue,
pud_poly_feature_queue):
"""Load a pre-calculated quadtree and test incoming polygons against it.
Updates polygons with a PUD and send back out on the queue.
Parameters:
local_qt_pickle_path (string): ... | 5,318,809 |
def constant_substitution(text, constants_dict=None):
"""
Substitute some constant in the text.
:param text:
:param constants_dict:
:return:
"""
if not constants_dict:
# No constants, so return the same text
return text
template = Template(text)
return template.safe_... | 5,318,810 |
def zticks(model_name, dat, let):
"""
Read model name and return the corresponding
array of z-coordinates of front side of cells.
"""
delzarr = delz(model_name, dat, let)
arr = np.array([np.sum(delzarr[:i]) for i in range(delzarr.size+1)])
return arr | 5,318,811 |
def reformat_args(args):
"""
reformat_args(args)
Returns reformatted args for analyses, specifically
- Sets stimulus parameters to "none" if they are irrelevant to the
stimtype
- Changes stimulus parameters from "both" to actual values
- Changes grps string values to a l... | 5,318,812 |
def load_xlsx_to_plan_list(
filename, sort_by=["sample_num"], rev=[False], retract_when_done=False
):
"""
run all sample dictionaries stored in the list bar
@param bar: a list of sample dictionaries
@param sort_by: list of strings determining the sorting of scans
strings include ... | 5,318,813 |
def WTERMSIG(status):
"""Return the signal which caused the process to exit."""
return 0 | 5,318,814 |
def create_toplevel_function_string(args_out, args_in, pm_or_pf):
"""
Create a string for a function of the form:
def hl_func(x_0, x_1, x_2, ...):
outputs = (...) = calc_func(...)
header = [...]
return DataFrame(data, columns=header)
Parameters
---... | 5,318,815 |
def remove_duplicates(df: pd.DataFrame, **kwargs: dict) -> pd.DataFrame:
"""
Remove duplicates entries
Args:
df (pd.DataFrame): DataFrame to check
Returns:
pd.DataFrame: DataFrame with duplicates removed
"""
return df[~(df.duplicated(**kwargs))] | 5,318,816 |
def mainfrozen():
"""return True if we are a frozen executable.
The code supports py2exe (most common, Windows only) and tools/freeze
(portable, not much used).
"""
return (
pycompat.safehasattr(sys, "frozen") # new py2exe
or pycompat.safehasattr(sys, "importers") # old py2exe
... | 5,318,817 |
def test_model(models_path: str, model_id: str):
"""Send test request to the model and print reply."""
from npc_engine.exporters.base_exporter import Exporter
if not validate_local_model(models_path, model_id):
click.echo(
click.style(f"{(model_id)} is not a valid npc-engine model... | 5,318,818 |
def partitioned(items, n=3):
"""
>>> assert list(partitioned(range(10)))[0] == [0, 1, 2, 3]
"""
max_items_per_bucket, rem = divmod(len(items), n)
if rem:
max_items_per_bucket += 1
bucket = []
for item in items:
if len(bucket) >= max_items_per_bucket:
yield bucket... | 5,318,819 |
def create_x11_client_listener(loop, display, auth_path):
"""Create a listener to accept X11 connections forwarded over SSH"""
host, dpynum, _ = _parse_display(display)
auth_proto, auth_data = yield from lookup_xauth(loop, auth_path,
host, dpynum)
r... | 5,318,820 |
def expand_tile(expand_info):
"""Tile expander"""
# get op info.
input_desc = expand_info['input_desc'][0]
attrs = expand_info['attr']
multiples = None
for item in attrs:
if 'multiples' in item:
multiples = item['multiples']
output_shape, _, _, shape_compatible = _get_ti... | 5,318,821 |
def main():
"""
pipenv run python devops/remote_dispatcher.py -r ROLE -s SCRIPT -a "ARG1 ARG2"
:param -r ROLE - name of bin subdir holding the script
:param -s SCRIPT - name of script to invoke
:param -a ARGS - any args to invoke with script, as a string
"""
parsed = __use_argpar... | 5,318,822 |
def compare_system_and_attributes_csv(self, file_number):
"""compare systems and associated attributes"""
# get objects
analysisstatus_1 = Analysisstatus.objects.get(
analysisstatus_name='analysisstatus_1'
)
systemstatus_1 = Systemstatus.objects.get(systemstatus_name='systemstatus_1')
... | 5,318,823 |
def is_live_request(request):
"""
Helper to differentiate between live requests and scripts.
Requires :func:`~.request_is_live_tween_factory`.
"""
return request.environ.get("LIVE_REQUEST", False) | 5,318,824 |
def test_all():
"""GenericDB: the whole enchilada"""
config = {
'gdna': 'testdata/fasta/generic.gdna.fa.gz',
'gff3': 'testdata/gff3/generic.gff3',
'prot': 'testdata/fasta/generic.prot.fa',
'source': 'local',
'species': 'Gnrc',
}
db = GenericDB('Gnrc', config, work... | 5,318,825 |
async def test_no_implicit_state_topic_switch(hass, mqtt_mock, caplog):
"""Test no implicit state topic for switch."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, "homeassistant", {}, entry)
data = '{ "name": "Test1",' ' "command_topic": "cmnd"' "}"
async_fire_mqtt_messag... | 5,318,826 |
def download_model_from_s3(job_config, bucket, key, dest_dir):
"""
Download and untar a model file from S3; or print a warning message if it doesn't exist.
:return:
"""
logger = set_logger_handlers(module_logger, job_config)
s3 = job_config.initialize_s3()
mod_url = 's3://{}/{}'.format(bucke... | 5,318,827 |
def get_videos(episode):
"""
Get the list of videos.
:return: list
"""
videos = []
html = requests.get(episode).text
mlink = SoupStrainer('p', {'class':'vidLinksContent'})
soup = BeautifulSoup(html, parseOnlyThese=mlink)
items = soup.findAll('a')
for item in items:
try:
... | 5,318,828 |
def validate_documentation_files(documentation_dir: str,
files_to_validate: List[str] = None):
"""Validate documentation files in a directory."""
file_paths = list(filesystem_utils.recursive_list_dir(documentation_dir))
do_smoke_test = bool(files_to_validate)
validated = 0
for... | 5,318,829 |
def _add_reference_resources(data):
"""Add genome reference information to the item to process.
"""
aligner = data["config"]["algorithm"].get("aligner", None)
align_ref, sam_ref = genome.get_refs(data["genome_build"], aligner, data["dirs"]["galaxy"])
data["align_ref"] = align_ref
data["sam_ref"]... | 5,318,830 |
def parse_solid_selection(pipeline_def, solid_selection):
"""Take pipeline definition and a list of solid selection queries (inlcuding names of solid
invocations. See syntax examples below) and return a set of the qualified solid names.
It currently only supports top-level solids.
Query syntax exa... | 5,318,831 |
def _equal(v1, v2):
"""Same type as well."""
if isinstance(v2, float) and np.isinf(v2):
return True
if isinstance(v2, str):
v2 = th.string(v2)
return v1 == v2 | 5,318,832 |
def detete_instance_address(
session: boto3.Session,
allocation_id: str,
association_id: str,
) -> None:
"""
Removes the public ip described by the given allocation and association ids
"""
client = session.client("ec2")
client.disassociate_address(
AssociationId=association_id,
... | 5,318,833 |
def cli(context: click.Context):
"""Main CLI function
Load FB cookies into context
Args:
context (click.Context): click Context
"""
log.info("Loading cookies from environment variable.")
cookies = load_cookies()
context.obj = Fbook(cookies) | 5,318,834 |
def test_2d_cartesian_origin(k):
"""Test the value of the 2d Cartesian prior at the origin"""
assert priors.log_2d_cartesian_prior(0, 0, k=k) == -np.log(k) | 5,318,835 |
def setup_value_setter(node: TtkStyle, _: TkRenderingContext):
"""Sets TtkStyle attribute setter"""
node.set_attr = partial(_value_setter, node) | 5,318,836 |
def create():
"""
Create NFT
:return: None
"""
bpy.ops.scene.new()
for nft_number in range(0, 51):
generate_cubes()
create_light()
create_camera()
create_background()
# Render
render(nft_number)
# Remove assets... | 5,318,837 |
def dec_prefix(value, restricted=True):
"""Get an appropriate decimal prefix for a number.
:param value: the number
:type value: int or float
:param bool restricted: if ``True`` only integer powers of 1000 are used,
i.e. *hecto, deca, deci, centi* are skipped
:return: de... | 5,318,838 |
def _download_coaching(
loc_id: str,
start_date: datetime.datetime,
end_date: datetime.datetime = None,
collection: str = "CoachingActionEntries",
base = "prod",
pipeline_name = "sleep_quality"):
"""Queries the database for given location id, source id and in given datarange.
Returns ... | 5,318,839 |
def Make_Random(sents):
"""
Make random parses (from LG-parser "any"), to use as baseline
"""
any_dict = Dictionary('any') # Opens dictionary only once
po = ParseOptions(min_null_count=0, max_null_count=999)
po.linkage_limit = 100
options = 0x00000000 | BIT_STRIP #| BIT_ULL_IN
option... | 5,318,840 |
def on_join(bot, c, e):
"""."""
if e.source.nick == bot.config.get("nickname"):
bot.notify(c, "{} joined".format(e.target))
print(e)
if e.target not in bot.config["channels"]:
bot.config["channels"] += [str(e.target)]
bot.dump() | 5,318,841 |
def get_published_online_date(crossref_data):
"""
This function pulls the published online date out of the crossref data and returns it as an arrow date object
:param doi: the DOI of interest that you want the published online date for
:returns: arrow date object for published online date if it exists
... | 5,318,842 |
def ingredients_available(menu_item):
"""Accepts a dictionary of ingedients and checks if the machine has enough to make the drink"""
for item in MENU[menu_item]['ingredients']:
if resources[item] < MENU[menu_item]['ingredients'][item]:
print(f"There is not enough {item} to make your order.... | 5,318,843 |
def print_flow_info(flow):
"""Print a summary of the flow information"""
print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']),
len(flow['payload']), repr(flow['payload'])[:30])) | 5,318,844 |
def main():
""" Initialize data-analytics """
# configures basic logger
logger = logging.getLogger( __name__ )
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s ... | 5,318,845 |
def pyvcf_calls_to_sample_info_list(calls):
"""
Given pyvcf.model._Call instances, return a dict mapping each sample
name to its per-sample info:
sample name -> field -> value
"""
return OrderedDict(
(call.sample, call.data._asdict()) for call in calls) | 5,318,846 |
def DesignPatch(Er, h, Freq):
"""
Returns the patch_config parameters for standard lambda/2 rectangular microstrip patch. Patch length L and width W are calculated and returned together with supplied parameters Er and h.
Returned values are in the same format as the global patchr_config variable, so can be... | 5,318,847 |
def injection_file_name(
science_case: str, num_injs_per_redshift_bin: int, task_id: Optional[int] = None
) -> str:
"""Returns the file name for the raw injection data without path.
Args:
science_case: Science case.
num_injs_per_redshift_bin: Number of injections per redshift major bin.
... | 5,318,848 |
def setup_postgres_localhost(ctx):
"""
Sets up the postgres databases and roles with correct permissions on localhost
"""
# Setup auto-responder
postgres_user = ctx.config.postgres.user # should be root user at runtime
postgres_password = ctx.config.secrets.postgres.password
postgres_passwo... | 5,318,849 |
def focal_general_triplet_loss(embs, labels, minibatch_size, alpha=0.2):
"""
NOTE: In order for this loss to work properly, it is prefered that
labels contains several repetitions. In other word:
len(np.unique(labels))!=len(labels)
"""
classes = tf.one_hot(labels,depth=minibatch_size)
# Cla... | 5,318,850 |
def angle_between(v1, v2):
""" Returns the angle in degrees between vectors 'v1' and 'v2'."""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.degrees(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))) | 5,318,851 |
def SUM(A: pd.DataFrame, n) -> pd.DataFrame:
"""Sum (Time Series)
Args:
A (pd.DataFrame): factor data with multi-index
n: days
Returns:
pd.DataFrame: sum data with multi-index
"""
At = pivot_table(A)
res = At.rolling(n, min_periods=int(n/2)).sum()
res = stac... | 5,318,852 |
def _combine_batch_params(params):
"""Transform batch parameter strings into records.
Parameters
----------
params : list of str
The string should have the form "key=val1,val2,val3".
Returns
-------
A generator that yields a record, computing the product from the values.
>>> f... | 5,318,853 |
def load_properties(filepath, sep='=', comment_char='#'):
"""
Read the file passed as parameter as a properties file.
"""
props = {}
with open(filepath, 'rt') as f:
for line in f:
l = line.strip()
if l and not l.startswith(comment_char):
key_value = l.... | 5,318,854 |
def resolveComponents(url):
"""
>>> resolveComponents('http://www.example.com/foo/bar/../../baz/bux/')
'http://www.example.com/baz/bux/'
>>> resolveComponents('http://www.example.com/some/path/../file.ext')
'http://www.example.com/some/file.ext'
"""
parts = list(urlparse.urlparse(url))
p... | 5,318,855 |
def write(path, data):
"""
Writes the given data to the given file on disk
:param path: str
:param data: str
"""
path = path_utils.normalize_path(path)
data = path_utils.get_relative_path(data, path)
tmp = path + '.tmp'
bak = path + '.bak'
dirname = os.path.dirname(path)
i... | 5,318,856 |
def query_add(session, *objs):
"""Add `objs` to `session`."""
for obj in objs:
session.add(obj)
session.commit()
return objs | 5,318,857 |
def scale_streams(s: Stream[T], factor: T) -> Stream[T]:
"""
scale streams
"""
def scale_generator(g: Iterator[T]) -> Iterator[T]:
"""
scale generator
"""
yield next(iter(g)) * factor
yield from scale_generator(g)
return make_stream(scale_generator(s)) | 5,318,858 |
def sd_title(bs4_object, target=None):
"""
:param bs4_object: An object of class BeautifulSoup
:param target: Target HTML tag. Defaults to class:title-text, a dict.
:return: Returns paper title from Science Direct
"""
if target is None:
target = {"class": "title-text"}
return bs4_o... | 5,318,859 |
def generate_word_feat(sentence,
word_vocab_index,
word_max_size,
word_pad):
"""process words for sentence"""
sentence_words = tf.string_split([sentence], delimiter=' ').values
sentence_words = tf.concat([sentence_words[:word_max_size],
... | 5,318,860 |
def summarize_worker_statistics(stats, stream=sys.stdout):
"""Writes a summary of workers statistics to an
output stream.
Parameters
----------
stats : dict
A dictionary of worker statistics returned from
a call to :func:`collect_worker_statistics`.
stream : file-like object, or... | 5,318,861 |
def report(results, n_top = 3):
"""
Utility function to report best scores of grid/randomsearch.
results should be grid_search.cv_results_ or random_search_object.cv_results_.
"""
for i in range(1, n_top + 1):
candidates = np.flatnonzero(results['rank_test_score'] == i)
for candidate in candidates:
... | 5,318,862 |
def split_formula(formula, net_names_list):
"""
Splits the formula into two parts - the structured and unstructured part.
Parameters
----------
formula : string
The formula to be split, e.g. '~ 1 + bs(x1, df=9) + dm1(x2, df=9)'.
net_names_list : list of strings
A... | 5,318,863 |
def joinHostmask(nick, ident, host):
"""nick, user, host => hostmask
Joins the nick, ident, host into a user hostmask."""
assert nick and ident and host
return intern('%s!%s@%s' % (nick, ident, host)) | 5,318,864 |
def message(
command=0,
payload_size=0,
data_type=0,
data_count=0,
parameter1=0,
parameter2=0,
payload=b"",
):
"""Assemble a Channel Access message datagram for network transmission"""
if type(command) == str:
command = commands[command]
assert data_type is not None
a... | 5,318,865 |
def polynomial(x, degree=1, add_bias_coefs=False):
"""used to calculate the polynomial coefficients of a given array.
Args:
x (array): the input array to be calculated.
degree (int, optional): polynominal degree. Defaults to 1.
add_bias_coefs (bool, optional): set True if you wan to add... | 5,318,866 |
def run_function(
function, function_args=(), function_kwargs={},
cancel_pending_on_interrupt=True
):
"""Run a function and handle interrupt signals."""
loop = asyncio.get_event_loop()
task = loop.create_task(function(*function_args, **function_kwargs))
with contextlib.suppress(Keybo... | 5,318,867 |
def plot_energy_group_comparison(df: pd.DataFrame, reverse_axes: bool = False, size: float = 5.0) -> \
sns.axisgrid.FacetGrid:
"""
Plot energy level recovery for a group of conformation sets.
:param df: DataFrame where the columns are Energy, Method, and Discovery. Energy is the energy level (kc... | 5,318,868 |
def release(increment, debug):
"""Performs new application version release."""
if debug:
configure_logging(logging.DEBUG)
project = Project()
project.pull()
version_str, version_summary = project.get_release_info(increment)
if not version_summary:
click.secho('No changes fou... | 5,318,869 |
def get_summary_mapping(inputs_df, oed_hierarchy, is_fm_summary=False):
"""
Create a DataFrame with linking information between Ktools `OasisFiles`
And the Exposure data
:param inputs_df: datafame from gul_inputs.get_gul_input_items(..) / il_inputs.get_il_input_items(..)
:type inputs_df: pandas.Da... | 5,318,870 |
def reduce_puzzle(values):
"""Reduce a Sudoku puzzle by repeatedly applying all constraint strategies
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary after continued application o... | 5,318,871 |
def run_tests():
"""Run test suite.
"""
with virtualenv("benlew.is"):
with cd('~/repos/me'):
return run("nosetests") | 5,318,872 |
def ls( # pylint: disable=invalid-name
url: str, resource_type: str, headers: Dict[str, str]
) -> requests.Response:
"""
Get a list of all of the resources of a certain type.
"""
resource_url = generate_resource_url(url, resource_type)
return requests.get(resource_url, headers=headers) | 5,318,873 |
def uniform(iterable):
"""
Returns a random variable that takes each value in `iterable` with equal
probability.
"""
iterable = tuple(iterable)
return RandomVariable({val: 1 for val in iterable}) | 5,318,874 |
def remove_id3v2_footer( data ):
"""Remove ID3v2 footer tag if present"""
pos = len( data ) - 10
while pos > 0:
if data[pos:pos+3] == b'ID3' and data[pos+4] == 0:
if data[pos+3] == 2 or data[pos+3] == 3:
return data[:pos] + data[pos+decode_synchsafe_int( data[6:10] )+10:]
elif data[pos+3] == 4:
if da... | 5,318,875 |
def get_ilorest_client(oneview_client, server_hardware):
"""Generate an instance of the iLORest library client.
:param oneview_client: an instance of a python-hpOneView
:param: server_hardware: a server hardware uuid or uri
:returns: an instance of the iLORest client
:raises: InvalidParameterValue ... | 5,318,876 |
def get_metric(metric):
"""获取使用的评估函数实例.
Arguments:
metric: str or classicML.metrics.Metric 实例,
评估函数.
Raises:
AttributeError: 模型编译的参数输入错误.
"""
if isinstance(metric, str):
if metric == 'binary_accuracy':
return metrics.BinaryAccuracy()
elif met... | 5,318,877 |
def validate_ucodereset(ucode):
"""validate that RU is asserted to reset the ucode counter at the end of the instruction"""
# check conditional instructions true and false case
if isinstance(ucode, dict):
validate_ucodereset(ucode[False])
validate_ucodereset(ucode[True])
else:
if... | 5,318,878 |
def build_model(model_params):
"""
Generates OpenSeesPy model of an elastic cantilever and runs gravity analysis.
Assumes that length is measured in inches and acceleration in in/s2
Parameters
----------
NumberOfStories: int
Number of stories
StructureType: string
Type of s... | 5,318,879 |
def compute_ld(chromosome, position, genotype_name, N=20):
"""
Returns ordered list of the N neighboring SNPs positions in high LD
---
parameters:
- name: snp_pk
description: pk of the SNP of interest
required: true
type: string
paramType: path
- n... | 5,318,880 |
def load_user(userid):
"""
Flask-Login user_loader callback.
The user_loader function asks this function to get a User Object or return
None based on the userid.
The userid was stored in the session environment by Flask-Login.
user_loader stores the returned User object in current_user dur... | 5,318,881 |
def flow_read(input_file, format=None):
"""
Reads optical flow from file
Parameters
----------
output_file: {str, pathlib.Path, file}
Path of the file to read or file object.
format: str, optional
Specify in what format the flow is raed, accepted formats: "png" or "flo"
... | 5,318,882 |
def max_triple_product_bare_bones(nums: List[int]) -> int:
"""
A bare-bones O(n3) method to determine the largest product of three numbers in a list
:param nums: the list of numbers
:return: the highest prodict
"""
from itertools import combinations
return max([reduce(mul, lst, 1) for lst i... | 5,318,883 |
def is_number(s: str):
"""
Args:
s: (str) string to test if it can be converted into float
Returns:
True or False
"""
try:
# Try the conversion, if it is not possible, error will be raised
float(s)
return True
except ValueError:
return False | 5,318,884 |
def killServe():
""" In the event that our local server does not get
invoked, we need to kill it tenderly
"""
try:
get("http://localhost:%s" % state.external_port, timeout=1.0)
except:
pass | 5,318,885 |
def get_multiple_rs_200_albums_pages(start_date: str, end_date: str) -> None:
"""
downloads and saves multiple pages of the rolling stone top 200 albums list
for every week within the dates specified.
Note: start date must be a thursday
saves files for each week in form: 'canned_soup_of_rs_200_album... | 5,318,886 |
def getProxyVirtualHostConfig( nodename, proxyname,):
"""Gets or creates a ProxyVirtualHostConfig object."""
m = "getProxyVirtualHostConfig:"
sop(m,"Entry. nodename=%s proxyname=%s" % ( nodename, proxyname, ))
proxy_id = AdminConfig.getid( '/Node:%s/Server:%s' % ( nodename, proxyname ) )
sop(m,"pro... | 5,318,887 |
def relu6(name=None, collect=False):
"""Computes Rectified Linear 6: `min(max(features, 0), 6)`.
Args:
name: operation name.
collect: whether to collect this metric under the metric collection.
"""
return built_activation(tf.nn.relu6, name, collect) | 5,318,888 |
def announcements(soup):
"""
** Announcements Tab**
"""
try:
_div = soup.find('div', {'class':'ex1'})
z= _div.find_all('a')
return True,collection(z)
except Exception as e:
return False,[str(e)] | 5,318,889 |
def main():
"""MinCostFlow simple interface example."""
# Define four parallel arrays: start_nodes, end_nodes, capacities, and unit costs
# between each pair. For instance, the arc from node 0 to node 1 has a
# capacity of 15 and a unit cost of 4.
start_nodes = [0, 0, 1, 1, 1, 2, 2, 3, 4]
end_nodes = [1, 2... | 5,318,890 |
def _capture(cam, *args):
"""
Responsible for capturing images from the camera.
!!Do not call this method manually!!
.. note: Refer `_initialize()`
Parameters:
----------
cam: ICDA320 camera object
Camera object using which capture
operations needs to be performed
"""
... | 5,318,891 |
def analyze_comments_page(username, repo, per_page, page, print_comments, print_stage_results):
"""
Analyzes one page of GitHub comments. Helping function.
Parameters
----------
username : str
The GitHub alias of the repository owner
repo : str
The GitHub repository name
pe... | 5,318,892 |
def get_remotes(y, x):
"""
For a given pair of ``y`` (tech) and ``x`` (location), return
``(y_remote, x_remote)``, a tuple giving the corresponding indices
of the remote location a transmission technology is connected to.
Example: for ``(y, x) = ('hvdc:region_2', 'region_1')``,
returns ``('hvdc... | 5,318,893 |
def test_compositions():
""" TEST: composition of elementary functions:
(i) compositions of multiple elementary functions
(ii) compositions of elementary functions & other ops (Fluxions)
"""
theta_vec = np.expand_dims(np.linspace(-5,5,21) * np.pi, axis=1)
# composition of 2 ele... | 5,318,894 |
def ingrid(x: float, y: float, subgrid: List[int]) -> bool:
"""Check if position (x, y) is in a subgrid"""
i0, i1, j0, j1 = subgrid
return (i0 <= x) & (x <= i1 - 1) & (j0 <= y) & (y <= j1 - 1) | 5,318,895 |
def load_jsonl(path: Union[Path, str]) -> list[dict[str, Any]]:
""" Load from jsonl.
Args:
path: path to the jsonl file
"""
path = Path(path)
return [json.loads(line) for line in path.read_text().splitlines()] | 5,318,896 |
def getComUser(userId):
"""ユーザー情報を取得を処理するMapperを呼び出す
サービス層のExceptionをキャッチし、処理します。
:param userId: ユーザーデータID
"""
try:
result = __selectUser(userId)
return result
except OperationalError:
abort(500) | 5,318,897 |
def to_rgb_array(image):
"""Convert a CARLA raw image to a RGB numpy array."""
array = to_bgra_array(image)
# Convert BGRA to RGB.
#print(array.shape)
array = array[:, :, :3]
array = array[:, :, ::-1]
return array | 5,318,898 |
def git_version():
""" Get the full and python standardized version from Git tags (if possible) """
try:
# Full version includes the Git commit hash
full_version = subprocess.check_output('git describe --dirty', shell=True).decode("utf-8").strip(" \n")
# Python standardized version in f... | 5,318,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.