content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_tracks(filename="tracks.csv"):
"""
Builds the tracks matrix #tracks x #attributes (20635 x 4)
where attributes are track_id,album_id,artist_id,duration_sec
"""
with open(os.path.join(data_path, filename), "r") as f:
# Discard first line
lines = f.readlines()[1:]
num... | 15,600 |
def match_seq_len(*arrays: np.ndarray):
"""
Args:
*arrays:
Returns:
"""
max_len = np.stack([x.shape[-1] for x in arrays]).max()
return [np.pad(x, pad_width=((0, 0), (0, 0), (max_len - x.shape[-1], 0)), mode='constant', constant_values=0) for x
in arrays] | 15,601 |
def get_cmws_5_loss(
generative_model, guide, memory, obs, obs_id, num_particles, num_proposals, insomnia=1.0
):
"""Normalize over particles-and-memory for generative model gradient
Args:
generative_model
guide
memory
obs: tensor of shape [batch_size, *obs_dims]
obs_... | 15,602 |
def getTerm(Y):
"""Prints index and basis function based on Y index"""
for y in Y:
print(y)
d, t, c, m = coeffs[y - 1]
print("Delta^%f Tau^%f np.exp(-Delta^%f) np.exp(-Tau^%f)" % (d, t, c, m)) | 15,603 |
def chemin_absolu(relative_path):
"""
Donne le chemin absolu d'un fichier.
PRE : -
POST : Retourne ''C:\\Users\\sacre\\PycharmProjects\\ProjetProgra\\' + 'relative_path'.
"""
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
correct = base_path.index("ProjetPr... | 15,604 |
def check_entity_value(step,entity_property,value):
"""
Function checks to see if entity_property is of the expected value
:param entity_property: Entity property being tested
:param value: Entity property value being tested
"""
assert entity_property == world.redis_property_key
assert worl... | 15,605 |
def to_float_tensor(np_array):
"""
convert to long torch tensor
:param np_array:
:return:
"""
return torch.from_numpy(np_array).type(torch.float) | 15,606 |
def display_heatmap(salience_scores,
salience_scores_2=None,
title=None,
title_2=None,
cell_labels=None,
cell_labels_2=None,
normalized=True,
ui=False):
"""
A utility funct... | 15,607 |
def _cleanse_line(line, main_character):
"""
Cleanse the extracted lines to remove formatting.
"""
# Strip the line, just in case.
line = line.strip()
# Clean up formatting characters.
line = line.replace('\\' , '') # Remove escape characters.
line = line.replace('[mc]', main_char... | 15,608 |
def require_pandapower(f):
"""
Decorator for functions that require pandapower.
"""
@wraps(f)
def wrapper(*args, **kwds):
try:
getattr(pp, '__version__')
except AttributeError:
raise ModuleNotFoundError("pandapower needs to be manually installed.")
r... | 15,609 |
def optimal_path_fixture():
"""An optimal path, and associated distance, along the nodes of the pyramid"""
return [0, 1, 2, 3], 10 + 2 + 5 | 15,610 |
def evaluate_DynamicHashtablePlusRemove(output=True):
"""
Compare performance using ability in open addressing to mark deleted values.
Nifty trick to produce just the squares as keys in the hashtable.
"""
# If you want to compare, then add following to end of executable statements:
# print([e... | 15,611 |
def closest(lat1, lon1):
"""Return distance (km) and city closest to given coords."""
lat1, lon1 = float(lat1), float(lon1)
min_dist, min_city = None, None
for city, lat2, lon2 in CITIES:
dist = _dist(lat1, lon1, lat2, lon2)
if min_dist is None or dist < min_dist:
min_dist, ... | 15,612 |
def get_previous_term():
"""
Returns a uw_sws.models.Term object,
for the previous term.
"""
url = "{}/previous.json".format(term_res_url_prefix)
return Term(data=get_resource(url)) | 15,613 |
def used(obj: T) -> T:
"""Decorator indicating that an object is being used.
This stops the UnusedObjectFinder from marking it as unused.
"""
_used_objects.add(obj)
return obj | 15,614 |
def fit_double_gaussian(x_data, y_data, maxiter=None, maxfun=5000, verbose=1, initial_params=None):
""" Fitting of double gaussian
Fitting the Gaussians and finding the split between the up and the down state,
separation between the max of the two gaussians measured in the sum of the std.
Args:
... | 15,615 |
def test_bascis():
"""
Test mean/sd/var/mode/entropy functionality of Cauchy.
"""
net = CauchyBasics()
ans = net()
assert isinstance(ans, Tensor)
with pytest.raises(ValueError):
net = CauchyMean()
ans = net()
with pytest.raises(ValueError):
net = CauchyVar()
... | 15,616 |
def test_logging_warning(capsys):
"""
Should output the debug logs
"""
logger = setup_logging(module_name, 'WARNING')
logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARN')
captured = capsys.readouterr()
assert "WARN" in captured.err
assert "INFO" not in capture... | 15,617 |
def _set_advanced_network_attributes_of_profile(config, profile):
"""
Modify advanced network attributes of profile.
@param config: current configparser configuration.
@param profile: the profile to set the attribute in.
@return: configparser configuration.
"""
config = _set_attribute_of_pr... | 15,618 |
def Environ(envstring):
"""Return the String associated with an operating system environment variable
envstring Optional. String expression containing the name of an environment variable.
number Optional. Numeric expression corresponding to the numeric order of the
environment string in the environme... | 15,619 |
def ring_bond_equal(b1, b2, reverse=False):
"""Check if two bonds are equal.
Two bonds are equal if the their beginning and end atoms have the same symbol and
formal charge. Bond type not considered because all aromatic (so SINGLE matches DOUBLE).
Parameters
----------
b1 : rdkit.Chem.rdchem.B... | 15,620 |
def test_tensor_symmetrize():
""" test advanced tensor calculations """
grid = CartesianGrid([[0.1, 0.3], [-2, 3]], [2, 2])
t1 = Tensor2Field(grid)
t1.data[0, 0, :] = 1
t1.data[0, 1, :] = 2
t1.data[1, 0, :] = 3
t1.data[1, 1, :] = 4
# traceless = False
t2 = t1.copy()
t1.symme... | 15,621 |
def survey_aligned_velocities(od):
"""
Compute horizontal velocities orthogonal and tangential to a survey.
.. math::
(v_{tan}, v_{ort}) = (u\\cos{\\phi} + v\\sin{\\phi},
v\\cos{\\phi} - u\\sin{\\phi})
Parameters
----------
od: OceanDataset
oceandataset used to compute... | 15,622 |
def insertion_sort(numbers):
"""
At worst this is an O(n2) algorithm
At best this is an O(n) algorithm
"""
for index in xrange(1, len(numbers)):
current_num = numbers[index]
current_pos = index
while current_pos > 0 and numbers[current_pos - 1] > current_num:
numb... | 15,623 |
def p_ppjoin_block_2(p):
"""
pjoin_block : empty
"""
p[0] = [] | 15,624 |
def applyEffectiveDelayedNeutronFractionToCore(core, cs):
"""Process the settings for the delayed neutron fraction and precursor decay constants."""
# Verify and set the core beta parameters based on the user-supplied settings
beta = cs["beta"]
decayConstants = cs["decayConstants"]
# If beta is int... | 15,625 |
def ratio_shimenreservoir_to_houchiweir():
"""
Real Name: Ratio ShiMenReservoir To HouChiWeir
Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir/Sum Allcation From ShiMenReservoir
Units: m3/m3
Limits: (None, None)
Type: component
"""
return sum_allocation_shimenreserv... | 15,626 |
def torch_profiler_full(func):
"""
A decorator which will run the torch profiler for the decorated function,
printing the results in full.
Note: Enforces a gpu sync point which could slow down pipelines.
"""
@wraps(func)
def wrapper(*args, **kwargs):
with torch.autograd.profiler.pr... | 15,627 |
def bias_add(x, bias, data_format=None):
"""Adds a bias vector to a tensor.
# Arguments
x: Tensor or variable.
bias: Bias tensor to add.
data_format: string, `"channels_last"` or `"channels_first"`.
# Returns
Output tensor.
# Raises
ValueError: In one of the tw... | 15,628 |
def get_news_with_follow(request, user_id):
"""
获取用户关注类型的前30条,未登录300未登录
:param request: 请求对象
:return: Json数据
"""
data = {}
try:
user = User.objects.get(pk=user_id)
follow_set = user.follow_type.value_list('id').all()
follow_list = [x[0] for x in follow_set]
n... | 15,629 |
def get_ngd_dir(config, absolute = False):
"""Returns the ngd output directory location
Args:
config (dictionary): configuration dictionary
absolute (boolean):
False (default): Relative to project base
True: Absolute
Returns:
(string): string representation ... | 15,630 |
def __setup_row_data_validation(
sheet,
status_data_validation,
priority_data_validation
):
"""
Apply proper style and url for 'Reference' column
Parameters
----------
sheet: Sheet
sheet to setup data validation for
status_data_validation: DataValidation
data validat... | 15,631 |
def trigger():
"""Trigger salt-api call."""
data = {'foo': 'bar'}
return request('/hook/trigger', data=data) | 15,632 |
def fitness_function(cams: List[Coord], pop: List[Coord]) -> int:
"""
Function to calculate number of surveilled citizens.
Check if all the cameras can see them, if any can score increases
"""
score = []
for cit in pop:
test = False
for cam in cams:
if (
... | 15,633 |
def main():
"""Get Message and Process."""
# Get the queue
try:
queue = sqs.get_queue_by_name(QueueName=os.environ["SQS_NAME"])
except ClientError:
print("SQS Queue {SQS_NAME} not found".format(SQS_NAME=os.environ["SQS_NAME"]))
sys.exit(1)
while True:
message = False... | 15,634 |
def set_cross_correction_positive_length(element: int, value: float) -> None:
"""set cross correction positive length
Args:
element (int): element ID
value (float): a value
""" | 15,635 |
def scrape_opening_hours():
""""scrape opening hours from https://www.designmuseumgent.be/bezoek"""
r = requests.get("https://www.designmuseumgent.be/bezoek")
data = r.text
return data | 15,636 |
def _demo_mm_inputs(input_shape=(1, 3, 256, 256)):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
"""
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
imgs = rng.rand(*input_shape)
target =... | 15,637 |
def compute_one_epoch_baseline():
"""
Function to compute the performance of a simple one epoch baseline.
:return: a line to display (string reporting the experiment results)
"""
best_val_obj_list = []
total_time_list = []
for nb201_random_seed in nb201_random_seeds:
for random_see... | 15,638 |
def generate_random_string( length ):
"""Generate a random string of a given length containing uppercase and lowercase letters, digits and ASCII punctuation."""
source = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
return ''.join( random.choice( source ) for i in rang... | 15,639 |
def create(params):
"""Handles the 'change' operation for modifying a dataset.
Expected flags in 'params' are translated to Json Field names for creation content
"""
expectedArgs = {'--name': 'name'}
kwargs = translate_flags(expectedArgs, params)
rsp = server.datasets.create(**kwargs)
if ... | 15,640 |
def start_session(Target=None, DocumentName=None, Parameters=None):
"""
Initiates a connection to a target (for example, an instance) for a Session Manager session. Returns a URL and token that can be used to open a WebSocket connection for sending input and receiving outputs.
See also: AWS API Documentatio... | 15,641 |
def start_cmd(cmd, use_file=False):
"""Start command and returns proc instance from Popen."""
orig_cmd = ""
# Multi-commands need to be written to a temporary file to execute on Windows.
# This is due to complications with invoking Bash in Windows.
if use_file:
orig_cmd = cmd
temp_f... | 15,642 |
def pretty_table(rows, header=None):
"""
Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most plain python objects) which is
equivalent to passing ... | 15,643 |
def initGlobals():
"""
function: init global variables
input: NA
output: NA
"""
global g_oldVersionModules
global g_clusterInfo
global g_oldClusterInfo
global g_logger
global g_dbNode
# make sure which env file we use
g_opts.userProfile = g_opts.mpprcFile
# init g_lo... | 15,644 |
def interpolate_trajectory(world_map, waypoints_trajectory, hop_resolution=1.0):
"""
Given some raw keypoints interpolate a full dense trajectory to be used by the user.
Args:
world: an reference to the CARLA world so we can use the planner
waypoints_trajectory: the current coarse trajectory... | 15,645 |
def import_data(filepath="/home/vagrant/countries/NO.txt", mongodb_url="mongodb://localhost:27017"):
"""
Import the adress data into mongodb
CLI Example:
salt '*' mongo.import_data /usr/data/EN.txt
"""
client = MongoClient(mongodb_url)
db = client.demo
address_col = db.address
... | 15,646 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Enphase Envoy sensor."""
ip_address = config[CONF_IP_ADDRESS]
monitored_conditions = config[CONF_MONITORED_CONDITIONS]
name = config[CONF_NAME]
username = config[CONF_USERNAME]
password = config[... | 15,647 |
def _get_piping_verb_node(calling_node: ast.Call) -> ast.Call:
"""Get the ast node that is ensured the piping verb call
Args:
calling_node: Current Call node
Returns:
The verb call node if found, otherwise None
"""
from .register import PIPING_SIGNS
from .verb import Verb
... | 15,648 |
def files_to_yaml(*files: str):
""" Reads sample manifests from files."""
for name in files:
with open(name, 'r') as stream:
manifest = yaml.load(stream)
yield (name, manifest) | 15,649 |
def slot(**kwargs):
"""Creates a SlotConfig instance based on the arguments.
Args:
**kwargs: Expects the following keyed arguments.
in_dist: Distribution for inbound in msec. Optional
in_max_bytes: Optional. Ignored when in_dist is missing.
in_max_pkts: Optional. Ign... | 15,650 |
def get_agent_type(player):
""" Prompts user for info as to the type of agent to be created """
print('There are two kinds of Agents you can initialise.')
print(' 1 - <Human> - This would be a totally manually operated agent.')
print(' You are playing the game yourself.')
print(' ... | 15,651 |
def xml_generation():
"""generate all xml needed for the sizes mode
"""
for max_size in sizes:
byte_file = open(xml_filepath, "rb")
filename = working_dir + "ssxtd_test_" + str(max_size) +".xml"
with open(filename, 'wb') as new_file:
#new_file.write(b"<?xml version=\... | 15,652 |
def _try_match_and_transform_pattern_1(reduce_op, block) -> bool:
"""
Identify the pattern:
y = gamma * (x - mean) / sqrt(variance + epsilon) + beta
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
x --> reduce_mean --> sub --> square --> reduce_mean --> a... | 15,653 |
def cli_resize(maxsize):
"""Resize images to a maximum side length preserving aspect ratio."""
click.echo("Initializing resize with parameters {}".format(locals()))
def _resize(images):
for info, image in images:
yield info, resize(image, maxsize)
return _resize | 15,654 |
def _fetch_object_array(cursor):
"""
_fetch_object_array() fetches arrays with a basetype that is not considered
scalar.
"""
arrayShape = cursor_get_array_dim(cursor)
# handle a rank-0 array by converting it to
# a 1-dimensional array of size 1.
if len(arrayShape) == 0:
arraySh... | 15,655 |
def sldParse(sld_str):
"""
Builds a dictionary from an SldStyle string.
"""
sld_str = sld_str.replace("'", '"').replace('\"', '"')
keys = ['color', 'label', 'quantity', 'opacity']
items = [el.strip() for el in sld_str.split('ColorMapEntry') if '<RasterSymbolizer>' not in el]
sld_items = []
... | 15,656 |
def x_ideal(omega, phase):
"""
Generates a complex-exponential signal with given frequency
and phase. Does not contain noise
"""
x = np.empty(cfg.N, dtype=np.complex_)
for n in range(cfg.N):
z = 1j*(omega * (cfg.n0+n) * cfg.Ts + phase)
x[n] = cfg.A * np.exp(z)
return x | 15,657 |
def _wrap_stdout(outfp):
"""
Wrap a filehandle into a C function to be used as `stdout` or
`stderr` callback for ``set_stdio``. The filehandle has to support the
write() and flush() methods.
"""
def _wrap(instance, str, count):
outfp.write(str[:count])
outfp.flush()
retu... | 15,658 |
def svn_fs_apply_textdelta(*args):
"""
svn_fs_apply_textdelta(svn_fs_root_t root, char path, char base_checksum,
char result_checksum, apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_apply_textdelta(*args) | 15,659 |
def find(x):
"""
Find the representative of a node
"""
if x.instance is None:
return x
else:
# collapse the path and return the root
x.instance = find(x.instance)
return x.instance | 15,660 |
def convert_shape(node, **kwargs):
"""Map MXNet's shape_array operator attributes to onnx's Shape operator
and return the created node.
"""
return create_basic_op_node('Shape', node, kwargs) | 15,661 |
def _UploadScreenShotToCloudStorage(fh):
""" Upload the given screenshot image to cloud storage and return the
cloud storage url if successful.
"""
try:
return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT,
_GenerateRemotePath(fh), fh.GetAbsPath())
except cloud_stor... | 15,662 |
def get_timestamp(prev_ts=None):
"""Internal helper to return a unique TimeStamp instance.
If the optional argument is not None, it must be a TimeStamp; the
return value is then guaranteed to be at least 1 microsecond later
the argument.
"""
t = time.time()
t = TimeStamp(*time.gmtime(t)[:5... | 15,663 |
def mintos(input_file, input_directory, calculation):
"""Calculates income and tax from Mintos transaction log, using D-1 NBP PLN exchange rate."""
account = MintosAccount()
if input_file:
account.load_transaction_log(input_file)
else:
account.load_transaction_logs(input_directory)
a... | 15,664 |
def get_element_as_string(element):
"""
turn xml element from etree to string
:param element:
:return:
"""
return lxml.etree.tostring(element, pretty_print=True).decode() | 15,665 |
def get(dirPath):
"""指定したパスのファイル一覧を取得する"""
if sys.version_info.major != 3:
print("Error!!\nPython 3.x is required.")
exit()
if sys.version_info.minor >= 5:
# python 3.5以降
fileList = []
fileList = glob.glob(dirPath, recursive=True)
return fileList
else:
... | 15,666 |
def _select_ports(count, lower_port, upper_port):
"""Select and return n random ports that are available and adhere to the given port range, if applicable."""
ports = []
sockets = []
for i in range(count):
sock = _select_socket(lower_port, upper_port)
ports.append(sock.getsockname()[1])
... | 15,667 |
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xrepla... | 15,668 |
def is_callable(x):
"""Tests if something is callable"""
return callable(x) | 15,669 |
def validate_version_argument(version, hint=4):
""" validate the version argument against the supported MDF versions. The
default version used depends on the hint MDF major revision
Parameters
----------
version : str
requested MDF version
hint : int
MDF revision hint
Retur... | 15,670 |
def test_default_logger():
"""Create a logger with default options.
Only stdout logger must be used."""
capture = CaptureStdOut()
with capture:
test_logger = pyansys_logging.Logger()
test_logger.info("Test stdout")
assert "INFO - - test_pyansys_logging - test_default_logger - Test... | 15,671 |
def test_created_nostartup(mock_clean_state, mock_vm_one):
"""
Test with one image and startup_import_event unset/false
"""
# NOTE: this should yield 0 created event _ one state event
with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
vmadm.__salt__, {"vmadm.list": MagicMock(r... | 15,672 |
def roc_auc(probs, labels):
"""
Computes the area under the receiving operator characteristic between output probs
and labels for k classes.
Source: https://github.com/HazyResearch/metal/blob/master/metal/utils.py
args:
probs (tensor) (size, k)
labels (tensor) (size, 1)
... | 15,673 |
def test_FUNC_default_WITH_map_attribute_EXPECT_successful_serialization() -> None:
"""
Checks whether serialization works.
:return: No return.
"""
d = MapAttribute(attributes={
'key': Decimal(1),
'key2': {1, 2, 3, 3, 3, 3}
})
try:
json.dumps(d)
except TypeError... | 15,674 |
def show_collection(request, collection_id):
"""Shows a collection"""
collection = get_object_or_404(Collection, pk=collection_id)
# New attribute to store the list of problems and include the number of submission in each problem
collection.problem_list = collection.problems()
for problem in collect... | 15,675 |
def alpha(
data: np.ndarray,
delta: Union[Callable[[int, int], float], List[List[float]], str] = "nominal",
):
"""Calculates Krippendorff's alpha coefficient [1, sec. 11.3] for
inter-rater agreement.
[1] K. Krippendorff, Content analysis: An introduction to its
methodology. Sage publications, 2... | 15,676 |
def enforce(action, target, creds, do_raise=True):
"""Verifies that the action is valid on the target in this context.
:param creds: user credentials
:param action: string representing the action to be checked, which
should be colon separated for clarity.
O... | 15,677 |
def query_data(session, agency_code, period, year):
""" Request A file data
Args:
session: DB session
agency_code: FREC or CGAC code for generation
period: The period for which to get GTAS data
year: The year for which to get GTAS data
Returns:
... | 15,678 |
def vocublary(vec_docs):
""" vocabulary(vec_docs) -> tuple: (int avg_doc_len, updated vec_docs, corpus Vocabulary dictionary {"word": num_docs_have__this_term, ...})
vec_docs = list of documents as dictionaries [{ID:"word_i word_i+1 ..."} , {ID:"word_i word_i+1"}, ...}]
"""
vocabulary = {}
count_v... | 15,679 |
def plot_bursts(odf,
bdf,
lowest_level=0,
title=True,
daterange=None,
xrangeoffsets=3,
s=None,
gamma=None):
"""Plots burst and offset data.
odf = an offsets dataframe
bdf = an edgeburst dataframe... | 15,680 |
def main(unused_argv):
"""Main entry.
Args:
* unused_argv: unused arguments (after FLAGS is parsed)
"""
try:
# setup the TF logging routine
tf.logging.set_verbosity(tf.logging.INFO)
# set the learning phase to 'inference'; data format may be changed if needed
set_learning_phase()
# ins... | 15,681 |
def load_staging_tables(cur, conn, schema):
"""
The Function load data from S3 to staging tables which user made.
Args:
cur: Database cursor.
conn: Connection for database
schema: Schema for selected talbe
Returns:
None
"""
for query in copy_table_queries:
cur.... | 15,682 |
def _build_type(type_, value, property_path=None):
""" Builds the schema definition based on the given type for the given value.
:param type_: The type of the value
:param value: The value to build the schema definition for
:param List[str] property_path: The property path of the current type,
... | 15,683 |
def lidar_2darray_to_rgb(array: np.ndarray) -> np.ndarray:
"""Returns a `NumPy` array (image) from a 4 channel LIDAR point cloud.
Args:
array: The original LIDAR point cloud array.
Returns:
The `PyGame`-friendly image to be visualized.
"""
# Get array shapes.
W, H, C = array.shape
assert C == 2
... | 15,684 |
def changed_files(include_added_files=True):
"""
Return a generator of filenames changed in this commit. Excludes files that were just deleted.
"""
diff_filter = "CMRTUXB"
if include_added_files:
diff_filter += "A"
git_diff_command = "git diff-index --cached --name-only --diff-filter=%s... | 15,685 |
def args():
"""
--all (some subset that is useful for someone)
--packages (maybe positional?)
"""
parser = argparse.ArgumentParser("serviced-tests")
parser.add_argument("-v", "--verbose", action="store_true", help="verbose logging")
types = parser.add_argument_group("Test Type")
types.... | 15,686 |
def rollout(dataset: RPDataset,
env: RPEnv,
policy: Policy,
batch_size: int,
num_workers: int = 4,
disable_progress_bar: bool = False,
**kwargs) -> Tuple[Tensor, Union[List, Dict]]:
"""Policy evaluation rollout
Args:
dataset: datas... | 15,687 |
def test_coinco_bert(bert_subst_generator, coinco_dataset_reader):
"""
Reproduction command:
python lexsubgen/evaluations/lexsub.py solve
--substgen-config-path configs/subst_generators/lexsub/bert.jsonnet
--dataset-config-path configs/dataset_readers/lexsub/coinco.jsonnet
--run-dir=... | 15,688 |
def merge(fname1, fname2, how="inner", on=None):
"""
Merging two csv files.
Usage: ph merge a.csv b.csv --on=ijk
"""
hows = ("left", "right", "outer", "inner")
if how not in hows:
sys.exit("Unknown merge --how={}, must be one of {}".format(how, hows))
df1 = pd.read_csv(fname1)
... | 15,689 |
def regex_ignore_case(term_values):
"""
turn items in list "term_values" to regexes with ignore case
"""
output=[]
for item in term_values:
output.append(r'(?i)'+item)
return output | 15,690 |
def check_aws_installed():
"""Checks that AWS CLI is installed."""
if which('aws') is None:
raise ValueError('AWS CLI is not installed.') | 15,691 |
def importance_sampling_integrator(function: Callable[..., np.ndarray],
pdf: Callable[..., np.ndarray],
sampler: Callable[..., int],
n: int = 10000,
seed: int = 1
... | 15,692 |
def r1_gradient_penalty_loss(discriminator,
real_data,
mask=None,
norm_mode='pixel',
loss_scaler=None,
use_apex_amp=False):
"""Calculate R1 gradient penalty for WGAN-GP.
... | 15,693 |
def stop_all():
"""stop all running animations. see pygame_animation.Animation.stop for more information."""
while _running:
_running[0].stop(noerror=True) | 15,694 |
def assert_synced_channel_state(
token_network_identifier: TokenNetworkID,
app0: App,
balance0: Balance,
pending_locks0: List[HashTimeLockState],
app1: App,
balance1: Balance,
pending_locks1: List[HashTimeLockState],
) -> None:
""" Assert the values of two synced channels.
Note:
... | 15,695 |
def visualize(args):
"""Return the visualized output"""
ret = ""
cmd_list = json.load(args.results)['cmd_list']
cmd_list = util.filter_cmd_list(cmd_list, args.labels_to_include, args.labels_to_exclude)
(cmd_list, label_map) = util.translate_dict(cmd_list, args.label_map)
for cmd in cmd_list:
... | 15,696 |
def send_request(apikey, key_root, data, endpoint):
"""Send a request to the akismet server and return the response."""
url = 'http://%s%s/%s/%s' % (
key_root and apikey + '.' or '',
AKISMET_URL_BASE,
AKISMET_VERSION,
endpoint
)
try:
response = open_url(url, data=... | 15,697 |
def request_set_bblk_trace_options(*args):
"""
request_set_bblk_trace_options(options)
Post a 'set_bblk_trace_options()' request.
@param options (C++: int)
"""
return _ida_dbg.request_set_bblk_trace_options(*args) | 15,698 |
def range_str(values: iter) -> str:
"""
Given a list of integers, returns a terse string expressing the unique values.
Example:
indices = [0, 1, 2, 3, 4, 7, 8, 11, 15, 20]
range_str(indices)
>> '0-4, 7-8, 11, 15 & 20'
:param values: An iterable of ints
:return: A string of u... | 15,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.