content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_permutation_matrix( m ):
"""
Test whether a numpy array is a `permutation matrix`_.
.. _permutation_matrix: https://en.wikipedia.org/wiki/Permutation_matrix
Args:
m (mp.matrix): The matrix.
Returns:
(bool): True | False.
"""
m = np.asanyarray(m)
return (m.nd... | 3,900 |
def bilogplot(V, f0, fbin, x, y, **fmt):
"""Plot the spectrum of a band-pass modulator in dB.
The plot is a logarithmic plot, centered in 0, corresponding to f0,
extending to negative frequencies, with respect to the center frequencies
and to positive frequencies.
The plot employs a logarithmic x-... | 3,901 |
def reproduce(param1: Param("The message", str)):
"""Function for reproducing results related to the library."""
pass | 3,902 |
def create_security_role(connection, body, error_msg=None):
"""Create a new security role.
Args:
connection: MicroStrategy REST API connection object
body: JSON-formatted definition of the dataset. Generated by
`utils.formjson()`.
error_msg (string, optional): Custom Error M... | 3,903 |
def dbm_to_w(dbm):
"""Convert dBm to W."""
return 10 ** (dbm / 10.) * sc.milli | 3,904 |
def print_usage( program_name, file_handle=sys.stdout ):
"""
Prints the script's usage to standard output.
Takes 2 arguments:
program_name - Name of the program currently executing.
file_handle - File handle to print to. If omitted, defaults to standard output.
Returns nothing.
"""... | 3,905 |
def lml(alpha, beta, Phi, Y):
"""
4 marks
:param alpha: float
:param beta: float
:param Phi: array of shape (N, M)
:param Y: array of shape (N, 1)
:return: the log marginal likelihood, a scalar
"""
N = len(Phi)
M = len(Phi[0])
part1 = (-N*0.5)*np.log(2*np.pi)
wholePhi = ... | 3,906 |
def convert_env_var(var_name: str, *, cast_type: Callable[..., Any] = float, default: Any = None) -> Any:
"""
Attempts to read an environment variable value and cast it to a type. For example it permits
getting numeric value(s) from os.environ
:param var_name: Key to lookup from environment variables.
... | 3,907 |
def balance_set(X, Y, adr_labels_size, nonadr_labels_size):
"""balances the set by doing up- and down -sampling to converge into the same class size
# Arguments
X - set samples
Y - set labels
adr_labels_size - ADR_MENTION_CLASS size
nonadr_labels_size - NON_ADR_MENTION_CLASS siz... | 3,908 |
def load_det_lcia(result_dir, method, act_code, det_lcia_dict=None):
"""Return precalculated deterministic LCIA score"""
result_dir = Path(_check_result_dir(result_dir))
method = _check_method(method)
if not det_lcia_dict:
det_lcia_dict = _get_det_lcia_dict(result_dir, method)
if not act_cod... | 3,909 |
def get_geometry(location, geolevel):
"""
Get geometry of a single location code/name
"""
if not utils.is_number(location) and location != "BR":
assert geolevel, "You need to specify which geographic level this location is"
location = ibgetools.ibge_encode(location, geolevel)
if loca... | 3,910 |
def render_to_string(template, context={}, processors=None):
"""
A function for template rendering adding useful variables to context
automatically, according to the CONTEXT_PROCESSORS settings.
"""
if processors is None:
processors = ()
else:
processors = tuple(processors)
for processor in get_st... | 3,911 |
def find_node_names(structure):
""" Return the names of the nodes for the structure """
# Look through all of the items in the structure for names
# Check through each of the lists and sub-lists
names=set()
for i in xrange(len(structure)):
if isinstance(structure[i],basestring):
... | 3,912 |
def wind(path_to_shapes_of_land_surface, path_to_shapes_of_water_surface, path_to_onshore_output,
path_to_offshore_output, config):
"""Create wind on- and offshore simulation input for renewables.ninja."""
write_parameters(
bounds=config["scope"]["bounds"],
resolution=config["parameters... | 3,913 |
def run_calcs(run_id, year, no_ef_countries, export_data=True, include_TD_losses=True, BEV_lifetime=180000, ICEV_lifetime=180000, flowtrace_el=True, allocation=True, production_el_intensity=679, incl_ei=False, energy_sens=False):
"""Run all electricity mix and vehicle calculations and exports results."""
# Kore... | 3,914 |
def handle_question():
"""Save response and redirect to next question."""
# get the response choice
choice = request.form['answer']
# add this response to the session
responses = session[RESPONSES_KEY]
responses.append(choice)
session[RESPONSES_KEY] = responses
if (len(responses) == l... | 3,915 |
def makeNotePlayer(seq: Sequencer, out: PortInfo
) -> Callable[[int, bool], None]:
"""Returns a callable object that plays midi notes on a port."""
def playNote(note: int, enabled: bool) -> None:
if enabled:
seq.sendEvent(NoteOn(0, 0, note, 127), out)
else:
seq.se... | 3,916 |
def se_resnet152(**kwargs):
"""TODO: Add Doc"""
return _resnet("se_resnet152", **kwargs) | 3,917 |
def file_to_attachment(filename):
"""
Convert a file to attachment
"""
with open(filename, 'rb') as _file:
return {'_name':filename,
'content':base64.b64encode(_file.read())
} | 3,918 |
def setup(bot: commands.Bot) -> None:
"""Load the Animals cog."""
bot.add_cog(Animals(bot)) | 3,919 |
def test_r2_7():
"""CCSD T2 Residual [Vvvov,T1] (7)"""
T1 = w.op("t", ["v+ o"])
Vvvov = w.op("v", ["v+ v+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Vvvov, T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("-1/2 t^{... | 3,920 |
def test_version() -> None:
"""Test version"""
assert __version__ == "0.1.1" | 3,921 |
def ratio_selection(
strain_lst,
ratio_lst,
pressure_lst,
temperature_lst,
ratio_boundary,
debug_plot=True,
):
"""
Args:
strain_lst:
ratio_lst:
pressure_lst:
temperature_lst:
ratio_boundary:
debug_plot:
Returns:
"""
if debug_... | 3,922 |
async def test_import(hass, client):
"""Test we can import yaml config."""
assert client
with patch("homeassistant.components.webostv.async_setup_entry", return_value=True):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={CONF_SOURCE: config_entries.SOUR... | 3,923 |
def close(device_handle):
"""
reset the instrument
"""
dwf.FDwfDigitalInReset(device_handle)
return | 3,924 |
def diff_mean(rolling_window, axis=-1):
"""For M5 purposes, used on an object generated by the
rolling_window function. Returns the mean of the first
difference of a window of sales."""
return np.diff(rolling_window, axis=axis).mean(axis=axis) | 3,925 |
def noiseFraction(truth_h5, measured_h5, tolerance):
"""
Return the fraction of measured localizations that are greater than
tolerance pixels from the nearest truth localization.
Note: This will return 0 if there are no measured localizations.
truth_h5 - A saH5Py.SAH5Py object with the ground trut... | 3,926 |
def iter_sliding_window(T, embedding):
""" Use a sliding window approach to iteratively transport the embedding
from one region of the Chimera graph to another.
Example:
>>> import embera
>>> import networkx as nx
>>> import dwave_networkx as dnx
>>> ... | 3,927 |
def prepare(compute: dict, script_id: str):
"""Prepare the script
:param compute: The instance to be attacked.
:param script_id: The script's filename without the filename ending. Is named after the activity name.
:return: A tuple of the Command Id and the script content
"""
os_type = __get_os_t... | 3,928 |
def compute_rigid_flow(depth, pose, intrinsics, reverse_pose=False):
"""Compute the rigid flow from target image plane to source image
Args:
depth: depth map of the target image [batch, height_t, width_t]
pose: target to source (or source to target if reverse_pose=True)
camera transformation matri... | 3,929 |
def get_versions(script_name):
""" 返回指定名称脚本含有的所有版本。"""
versions = repository.get(script_name, None)
if not versions:
return None
return sorted(versions, reverse=True) | 3,930 |
def data_static(filename):
"""
Get files
:param filename:
:return:
"""
_p, _f = os.path.split(filename)
print(_p, _f)
return flask.send_from_directory(os.path.join(
'/Users/dmitryduev/_caltech/python/deep-asteroids/data-raw/', _p), _f) | 3,931 |
def test_62_response():
"""
VEN, EiEvent Service, oadrDistributeEvent, oadrCreatedEvent Payload
The VEN must process EVERY oadrEvent event message (new, modified,
cancelled, etc.) that it receives from the VTN in an oadrDistributeEvent
payload and it MUST reply with a createdEvent message for every ... | 3,932 |
def get_key():
"""
Gets the private key used to access Transcriptic's services.
Returns
-------
str
"""
if TRANSCRIPTIC_KEY is not None:
return TRANSCRIPTIC_KEY
return os.environ['TRANSCRIPTIC_KEY'] | 3,933 |
def linear_search_while(lst: list, value: Any) -> int:
"""Return the index of the first occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search([2, 5, 1, -3], 5)
1
>>> linear_search([2, 4, 2], 2)
0
>>> linear_search([2, 5, 1, -3], 4)
-1
>>> linear_search([]... | 3,934 |
def get_pagerduty_secret_name():
"""
Get name of the PagerDuty secret for currently used addon.
Returns:
string: name of the secret
"""
return config.DEPLOYMENT["addon_name"] + constants.MANAGED_PAGERDUTY_SECRET_SUFFIX | 3,935 |
def get_dummies(
data: pandas.core.series.Series,
prefix: Literal["X"],
prefix_sep: Literal["-"],
dummy_na: bool,
columns: None,
sparse: bool,
drop_first: bool,
dtype: Type[numpy.uint8],
):
"""
usage.dask: 2
"""
... | 3,936 |
def check_docs(
doc_path: str, recurse: bool = True, max_threads: int = 10, delay: float = 0
) -> Dict[str, Dict[str, UrlResult]]:
"""
Check multiple HTML files in `doc_path`.
Parameters
----------
doc_path : str
Path
recurse: bool
If True, recurse subfolders, default is Tru... | 3,937 |
def get_cmd():
"""Return a Collection instance for commands collection/table"""
raise NotImplementedError() | 3,938 |
def create_graph(filepath, nodes_data, legend=False):
"""Visualizes the energy system as graph.
Creates, using the library Graphviz, a graph containing all
components and connections from "nodes_data" and returns this as a
PNG file.
----
Keyword arguments:
filepath : obj:'str'
... | 3,939 |
def exec_cmd(cmd, secrets=None, timeout=600, ignore_error=False, **kwargs):
"""
Run an arbitrary command locally
Args:
cmd (str): command to run
secrets (list): A list of secrets to be masked with asterisks
This kwarg is popped in order to not interfere with
subproce... | 3,940 |
def timeParser(dstr):
"""
parse clock time string into array
"""
hh, mm, ss = dstr.split(':')
return np.array([hh, mm, ss]).astype(int) | 3,941 |
def get_43_ai_core_data(input_file=None):
"""Function for getting datas from aicore: ov/cnt/total_cyc/ov_cyc/pmu_cnt/stream_id."""
result_data = []
with open(input_file, 'rb') as ai_core_file:
while True:
line_ = ai_core_file.read(128)
if line_:
if not line_.s... | 3,942 |
def get_configuration_class_with_attributes(
klass: Type[AlgorithmConfiguration],
) -> Type[AlgorithmConfiguration]:
"""Get AlgorithmConfiguration with set attributes.
Args:
klass: a class to be used to extract attributes from.
Returns:
a class with the attributes set.
"""
conf... | 3,943 |
def test_insertToTable(connect, cursor, refer_table):
"""Test inesrt to table function"""
result = insertToTable(connect, cursor, refer_table, ["TYPES"], ["file"])
assert isinstance(result, object) | 3,944 |
def main():
""" main fonksiyon; cerceve/iskelet/frame burada yaratiliyor """
reset_blend()
props = bpy.context.scene.QueryProps
height = props["height"]
width = props["width"]
depth = props["depth"]
column_longer = props["column_longer"]
row_longer = props["row_longer"]
# he... | 3,945 |
def verify_kernel_cmdline(kernel_cmdline_golden_file, scrutiny_out):
"""verify_kernel_cmdline verifies the kernel cmdline in ZBI image.
Raises:
VerificationError: If verification fails.
"""
gf_checker = GoldenFileChecker(kernel_cmdline_golden_file)
actual_cmd = []
if os.path.exists(os.p... | 3,946 |
def get_token_symbol(token_address: str):
"""
Gets the token symbol
If not have the external method `symbol` to get the score symbol,
it will raise JSONRPCException.
"""
call = CallBuilder()\
.from_(wallet.get_address())\
.to(token_address)\
.method("symbol")\
.b... | 3,947 |
def iceil(x):
"""
Return the ceiling of the input, element-wise.
The ceil of the scalar `x` is the smallest integer `i`, such
that `i >= x`. It is often denoted as :math:`\lceil x \rceil`.
Parameters
----------
x : array_like
Input data.
Returns
-------
y : {numpy.nda... | 3,948 |
def get_repo_version(filename: str, repo: str) -> Optional[str]:
"""Return the version (i.e., rev) of a repo
Args:
filename (str): .pre-commit-config.yaml
repo (str): repo URL
Returns:
Optional[str]: the version of the repo
"""
with open(filename, "r") as stream:
p... | 3,949 |
def write_readback(dic, data):
""" Write out a NMRPipe file and read back in. """
# write out and read back
tf = tempfile.mktemp(dir=".")
ng.pipe.write(tf, dic, data)
rdic, rdata = ng.pipe.read(tf)
os.remove(tf)
assert_array_equal(data, rdata)
assert dic == rdic | 3,950 |
def save_environment():
"""Save a copy of environment."""
global saved_env
u.verbose(1, "saving copy of environment")
saved_env = copy.deepcopy(os.environ) | 3,951 |
def plot_grad_flow(named_parameters: Iterator[Tuple[str, torch.nn.Parameter]]) -> plt.Figure:
"""
Plots the gradients flowing through different layers in the net during training.
Can be used for checking for possible gradient vanishing / exploding problems.
Usage: Plug this function in Trainer cla... | 3,952 |
def mk_cli_context_settings(
mk_db: CliCtxDbBase.MkFnT,
) -> Dict[str, Any]:
"""Create initial click context parameters for this cli application.
This is currently used as input for autocompletion.
Example:
`@click.group(context_settings=mk_cli_context_settings())`
See `init_cli_ctx` whic... | 3,953 |
def get_file_action(header: 'dict[str,str]') -> str:
"""Gets action file form main repo
Args:
header (dict[str,str]): Header with auth token
Raises:
get_aciton_file_e: Raised when no aciton file was collected
Returns:
str: The content of the action file... | 3,954 |
def sensor(raw_input_shape: StandardizedTensorShape, f: SensorFunction = None,
sensor_id: str = None, history: int = None) \
-> Union[Callable[[SensorFunction], SensorLambda], SensorLambda]:
"""Decorator for creating sensors from functions.
Usage:
@sensor((5, 8))
def my_senso... | 3,955 |
def convert_event(ui_event):
"""Converts ui.event into ecs.event
This maps keyboard entries into something that the system can handle
TODO: Add a movement system
"""
if isinstance(ui_event, KeyboardEvent):
vim_movement_mapper = {
# Cardinal
KeyboardEvent("h"): vecto... | 3,956 |
def collection(collection, _pod=None):
"""Retrieves a collection from the pod."""
return _pod.get_collection(collection) | 3,957 |
def appif(cfg):
"""
Return interface belonging to application
"""
return get_interface_of_network(appnet(cfg)['name']) | 3,958 |
def f(x):
"""
Try and have the NN approximate the
xor function.
"""
if x[0] == x[1]:
return 0.
else:
return 1. | 3,959 |
def dataframe_to_list(df: pandas.DataFrame) -> list:
"""
Use caution with datetime columns, as they may not be de/serialized as desired
"""
return json.loads(df.to_json(orient="records")) | 3,960 |
def decimal_to_binary(integer,nbits=8,grouped=0):
"""Converts integer to binary string of length nbits, sign bit and
then m.s.b. on the left. Negative numbers are twos-complements, i.e.,
bitwise complement + 1."""
# Just remember that minus sign and ignore it
if integer < 0:
negative = True... | 3,961 |
def line_integrals(state, uloc, vloc, kind="same"):
"""
calculate line integrals along all islands
Arguments:
kind: 'same' calculates only line integral contributions of an island with itself,
while 'full' calculates all possible pairings between all islands.
"""
vs = state.v... | 3,962 |
def _BBANDS(kwargs):
"""
布林带
技术参数
-------
使用21天,2倍
"""
df = kwargs.get('df')
limit_start = kwargs.get('limit_start')
limit_end = kwargs.get('limit_end')
ndays = 21
inds = indicators(
'BBANDS', df, timeperiod=ndays).loc[limit_start:limit_end, :]
traces = []
fo... | 3,963 |
def test_joint_refinement(dials_regression, run_in_tmpdir):
"""A basic test of joint refinement of the CS-PAD detector at hierarchy level 2
with 300 crystals."""
from dials.array_family import flex
bevington = pytest.importorskip("scitbx.examples.bevington")
if not hasattr(bevington, "non_linear_ls... | 3,964 |
def make_colors(color: OpColor, fill_color: OpColor, colors: Optional[Iterable[OpColor]]) -> Tuple[OpColor, ...]:
"""Creates final colors tuple."""
if colors is None:
return conform_color(color), conform_color(fill_color), *DEFAULT_COLORS[2:]
colors = [conform_color(c) for c, _ in zip(colors, range(... | 3,965 |
def print_qa(questions,
answers_gt,
answers_gt_original,
answers_pred,
era,
similarity=dirac,
path=''):
"""
In:
questions - list of questions
answers_gt - list of answers (after modifications like truncation)
a... | 3,966 |
def recast_to_supercell(z, z_min, z_max):
"""Gets the position of the particle at ``z`` within the simulation
supercell with boundaries ``z_min`` y ``z_max``. If the particle is
outside the supercell, it returns the position of its closest image.
:param z:
:param z_min:
:param z_max:
:retur... | 3,967 |
def set_transactions():
"""
Save to database all the transactions.
"""
print 'Updating transactions =>',
last_transaction = db.simple_query('SELECT MAX(date) FROM transactions')[0][0]
if last_transaction:
until_date = last_transaction - timedelta(days=10)
else:
until_date = d... | 3,968 |
def test_vacuum_hive_table(params, calls):
"""While writing create a hive table with and without ZOPTIMIZE."""
# Arrange
spark_session = Mock()
# Act
BatchDelta.vacuum(spark_session, "path/to/delta/files", **params)
# Assert
assert spark_session.sql.call_count == 1
spark_session.sql.as... | 3,969 |
def lca_operation(locator):
"""
Algorithm to calculate the primary energy and GHG_kgCO2MJ emissions of buildings according to the method used in the
integrated model of [Fonseca-Schlueter-2015]_ and the performance factors of [ecobau.ch].
:param locator: an InputLocator instance set to the scenario to ... | 3,970 |
def list_services(request):
""" Should probably move this to an Ajax JSON request like the probe. """
if request.method == "POST":
action = request.POST.get("action")
sid = request.POST.get("id")
logger.debug(f"-- action: {action} sid: {sid}")
if action == "delete":
l... | 3,971 |
def open_sat_data(
zarr_path: Union[Path, str],
convert_to_uint8: bool = True,
) -> xr.DataArray:
"""Lazily opens the Zarr store.
Args:
zarr_path: Cloud URL or local path pattern. If GCP URL, must start with 'gs://'
"""
_log.debug("Opening satellite data: %s", zarr_path)
# Silence t... | 3,972 |
async def get_pedigree(
internal_family_ids: List[int] = Query(None),
response_type: ContentType = ContentType.JSON,
replace_with_participant_external_ids: bool = True,
replace_with_family_external_ids: bool = True,
include_header: bool = True,
empty_participant_value: Optional[str] = None,
... | 3,973 |
def load_genesets():
"""
Action: Opens core_gene_sets file, sets gsa info with the same name to the current row.
Opens the WGCNA Modules, if a row has missing data, an error is raised, each row coulmn is then set to the values in loading.
Then we read the rgd vs go file. if values are blank, an exceptio... | 3,974 |
def lang_string_set_to_xml(obj: model.LangStringSet, tag: str) -> etree.Element:
"""
serialization of objects of class LangStringSet to XML
:param obj: object of class LangStringSet
:param tag: tag name of the returned XML element (incl. namespace)
:return: serialized ElementTree object
"""
... | 3,975 |
def grasp_from_contacts(contact1,contact2):
"""Helper: if you have two contacts, this returns an AntipodalGrasp"""
d = vectorops.unit(vectorops.sub(contact2.x,contact1.x))
grasp = AntipodalGrasp(vectorops.interpolate(contact1.x,contact2.x,0.5),d)
grasp.finger_width = vectorops.distance(contact1.x,contac... | 3,976 |
def choose_move(data: dict) -> str:
"""
data: Dictionary of all Game Board data as received from the Battlesnake Engine.
For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request
return: A String, the single move to make. One of "up", "down", "left" or "right".
... | 3,977 |
def get_fremont_data(filename='Fremont.csv', url=FREMONT_URL,
force_download=False):
"""Download and cache the fremont data
Parameters
----------
filename : string (optional)
location to save the data
url : string (optional)
web location of the data
... | 3,978 |
def boolean_dumper(dumper, value):
"""
Dump booleans as yes or no strings.
"""
value = u'yes' if value else u'no'
style = None
return dumper.represent_scalar(u'tag:yaml.org,2002:bool', value, style=style) | 3,979 |
def preprocess_data_4_catboost(data_df, output_path=None):
"""
preprocess data for working with gradient boosting techniques
specifically with the catboost library. since this is going to use
the preprocessing built into the catboost library there are slightly
different steps to be done
"""
... | 3,980 |
def conv_current_to_electrons_second(current):
"""
Convert a current in Amps to a number of
electrons per second.
"""
return int(current / const.electron_charge) | 3,981 |
def multigraph(der, prime):
"""
Graphs the analytical and discrete derivatives of a function.
"""
fig = plt.figure(1)
x = np.linspace(1/1000, 1, 101)
y1 = der
y2 = prime(x)
plt.plot(x, y1, 'b-')
plt.plot(x, y2, 'r-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Analytical v... | 3,982 |
def get_users():
"""
Use urllib3 to make a REST call to get list of Okta
Users for a given Okta Application
"""
request_url = f"{OKTA_URL}/apps/{OKTA_APP_ID}/users"
okta_users_request = HTTP.request(
'GET',
request_url,
headers={'Content-Type': 'application/json', 'Author... | 3,983 |
def n_sample_per_class_train_set(df, n_samples=3, class_column="category"):
"""
returns a subset of the provided df that contains n_samples instances of each class
:param df: panda dataframe that contains hidden_reps with class labels
:param n_samples: number of samples per class
:param class_column: column w... | 3,984 |
def clip_count(cand_d, ref_ds):
"""Count the clip count for each ngram considering all references."""
count = 0
for m in cand_d.keys():
m_w = cand_d[m]
m_max = 0
for ref in ref_ds:
if m in ref:
m_max = max(m_max, ref[m])
m_w = min(m_w, m_max)
count += m_w
return count | 3,985 |
def container_wrapper(directive, literal_node, caption, classes):
"""adapted from
https://github.com/sphinx-doc/sphinx/blob/master/sphinx/directives/code.py
"""
container_node = docutils.nodes.container(
'', literal_block=True, classes=classes) # ['literal-block-wrapper']
parsed = docutils.... | 3,986 |
def list_policies(Filter=None, NextToken=None, MaxResults=None):
"""
Retrieves the list of all policies in an organization of a specified type.
This operation can be called only from the organization's master account.
See also: AWS API Documentation
:example: response = client.list_policie... | 3,987 |
def tune_train(config):
"""Train the model with a hypyer-parameter tuner (ray).
Args:
config (dict): All the parameters for the model.
"""
data = config["data"]
train_engine = NeuCF(munchify(config))
result = train_engine.train(data)
while train_engine.eval_engine.n_worker > 0:
... | 3,988 |
def test_after_canonical_ife_is_finalized_inputs_are_not_exited_when_ife_is_restarted_and_non_canonical(testlang, plasma_framework, token):
"""
1. Alice and Bob send a canonical transaction transfering their funds to Alice.
2. Alice starts an in-flight exit and exits her output.
3. Bob creates a competi... | 3,989 |
def get_current_and_next_quarters(request, num):
"""
Returns the current and next num uw_sws.models.Term objects in a list
for the current quarter refered in the user session. Returns the next
num -1 quarters along with the current one.
"""
term = get_current_quarter(request)
quarters = [ter... | 3,990 |
def _create_metadata_from_dat_df(
csv_df: pd.DataFrame,
) -> Tuple[Dict[int, tuple], Pitch]:
"""Creates meta information from the CSV file as parsed by pd.read_csv().
Parameters
----------
csv_df: DataFrame
Containing all data from the positions CSV file as DataFrame.
Returns
-----... | 3,991 |
def _execute(workbench: thonny.workbench.Workbench, command: _Command) -> None:
"""
Execute the CrossHair command.
Depending on the ``command``, different checks are performed (*e.g.*,
whole file, single function, watch & check *etc.*).
"""
editor = workbench.get_editor_notebook().get_current_e... | 3,992 |
def setup_run_args(parser):
""" Add common arguments for all run scripts.
"""
parser.add_argument('--pennant-input', dest='pennant_input',
action='store', type=str,
default="PENNANT/test/leblancx4/leblancx4.pnt",
help='Path to the input... | 3,993 |
def main():
"""
Main function used in script, primarily used as a handle
to get the output into stdout.
"""
# There are no args, but parse them just so help works
print(process_files_json(), end="")
return None | 3,994 |
def train_generator(train_loader, test_loader, num_epoch=500,
lr=0.0001, beta1=0.9, beta2=0.999):
"""Train a generator on its own.
Args:
train_loader: (DataLoader) a DataLoader wrapping the training dataset
test_loader: (DataLoader) a DataLoader wrapping the test dataset
... | 3,995 |
def backup_file(filename, backup_dir=None):
"""Backup the file, if it exists. Backups versioning is supported."""
if isinstance(backup_dir, str):
newname = os.path.join(backup_dir, os.path.basename(filename))
else:
newname = filename
version = 1
while os.access(newname, os.F_OK):
... | 3,996 |
def configure_logger(verbose: bool):
"""Configure logging
:param verbose: display debug and info messages
:return: nothing
"""
logger = logging.getLogger()
logger.handlers = []
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(level=logging.WARNING)
stdout.setFormatter(logg... | 3,997 |
def expand(doc, doc_url="param://", params=None):
"""
ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE
EXPANDING FEATURE
USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY
:param doc: THE DATA STRUCTURE FROM JSON SOURCE
:param doc_url: THE URL THIS doc CAME... | 3,998 |
def get_model_creator(hparams):
"""Get the right model class depending on configuration."""
if hparams.architecture == 'peng':
model_creator = model.Model
"""vanilla lstm, seq2seq"""
return model_creator | 3,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.