content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_molecules(filename):
"""Read a file into an OpenEye molecule (or list of molecules).
Parameters
----------
filename : str
The name of the file to read (e.g. mol2, sdf)
Returns
-------
molecule : openeye.oechem.OEMol
The OEMol molecule read, or a list of molecules i... | 5,332,000 |
def euler(derivative):
"""
Euler method
"""
return lambda t, x, dt: (t + dt, x + derivative(t, x) * dt) | 5,332,001 |
def detect_encoding_type(input_geom):
"""
Detect geometry encoding type:
- ENC_WKB: b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@'
- ENC_EWKB: b'\x01\x01\x00\x00 \xe6\x10\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@'
- ENC_WKB_HEX: '01010000000000000... | 5,332,002 |
def GetFilesToConcatenate(input_directory):
"""Get list of files to concatenate.
Args:
input_directory: Directory to search for files.
Returns:
A list of all files that we would like to concatenate relative
to the input directory.
"""
file_list = []
for dirpath, _, files in os.walk(input_dire... | 5,332,003 |
def square_spiral(turn=5, size=75):
"""
Draws a "spiral" of squares.
Works best if `turn` is a factor of 360.
"""
rect_spiral(turn, size, size) | 5,332,004 |
def unet_weights(input_size = (256,256,1), learning_rate = 1e-4, weight_decay = 5e-7):
"""
Weighted U-net architecture.
The tuple 'input_size' corresponds to the size of the input images and labels.
Default value set to (256, 256, 1) (input images size is 256x256).
The float 'learni... | 5,332,005 |
def std(x, axis=None, keepdims=False):
"""Standard deviation of a tensor, alongside the specified axis. """
return T.std(x, axis=axis, keepdims=keepdims) | 5,332,006 |
def validate_email_address(
value=_undefined,
allow_unnormalized=False,
allow_smtputf8=True,
required=True,
):
"""
Checks that a string represents a valid email address.
By default, only email addresses in fully normalized unicode form are
accepted.
Validation logic is based on the... | 5,332,007 |
def help():
"""Help"""
print("hello, world!") | 5,332,008 |
def rotation_matrix_from_quaternion(quaternion):
"""Return homogeneous rotation matrix from quaternion."""
q = numpy.array(quaternion, dtype=numpy.float64)[0:4]
nq = numpy.dot(q, q)
if nq == 0.0:
return numpy.identity(4, dtype=numpy.float64)
q *= math.sqrt(2.0 / nq)
q = numpy.outer(q, q)... | 5,332,009 |
def get_woosh_dir(url, whoosh_base_dir):
"""
Based on the bigbed url and base whoosh directory
from settings generate the path for whoosh directory for index of this bed file
"""
path = urlparse(url).path
filename = path.split('/')[-1]
whoosh_dir = os.path.join(whoosh_base_dir, filename)
... | 5,332,010 |
def get_metadata(doi):
"""Extract additional metadata of paper based on doi."""
headers = {"accept": "application/x-bibtex"}
title, year, journal = '', '', ''
sessions = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
sessions.mount('h... | 5,332,011 |
def format_channel(channel):
""" Returns string representation of <channel>. """
if channel is None or channel == '':
return None
elif type(channel) == int:
return 'ch{:d}'.format(channel)
elif type(channel) != str:
raise ValueError('Channel must be specified in string format.... | 5,332,012 |
def make_mask(img_dataset,mask_parms,storage_parms):
"""
.. todo::
This function is not yet implemented
Make a region to identify a mask for use in deconvolution.
One or more of the following options are allowed
- Supply a mask in the form of a cngi.image.region
- Run an a... | 5,332,013 |
def parse_standards_from_spreadsheeet(
cre_file: List[Dict[str, Any]], result: db.Standard_collection
) -> None:
"""given a yaml with standards, build a list of standards in the db"""
hi_lvl_CREs = {}
cres = {}
if "CRE Group 1" in cre_file[0].keys():
hi_lvl_CREs, cres = parsers.parse_v1_stan... | 5,332,014 |
def download_emoji_texture(load=True): # pragma: no cover
"""Download emoji texture.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Text... | 5,332,015 |
def create_tables_in_database(
db_configuration: DatabaseConnectionConfig, model_base: Type[declarative_base], schema_name: str):
"""Creates the tables for the models in the database"""
with DatabaseConnection.get_db_connection(
db_connection_config=db_configuration) as db_connection:
... | 5,332,016 |
def the_task_is_created(step):
""" Assertions to check if TASK is created with the expected data """
assert_true(world.response.ok, 'RESPONSE BODY: {}'.format(world.response.content))
response_headers = world.response.headers
assert_equals(response_headers[CONTENT_TYPE], world.headers[ACCEPT_HEADER],
... | 5,332,017 |
def shuffle_sequence(sequence: str) -> str:
"""Shuffle the given sequence.
Randomly shuffle a sequence, maintaining the same composition.
Args:
sequence: input sequence to shuffle
Returns:
tmp_seq: shuffled sequence
"""
tmp_seq: str = ""
while len(sequence) > 0:
m... | 5,332,018 |
def hibernate(debug=False):
"""
Shortcut for hibernate command (need sudo).
:param debug: flag for using debug mode
:type debug:bool
:return: None
"""
power_control("pm-hibernate", debug) | 5,332,019 |
def bayesian_twosample(countsX, countsY, prior=None):
"""
Calculates a Bayesian-like two-sample test between `countsX` and `countsY`.
The idea is taken from [1]_. We assume the counts are generated IID. Then
we use Dirichlet prior to infer the underlying discrete distribution.
In the null hypothes... | 5,332,020 |
def load_image(image_path):
"""
loads an image from the specified image path
:param image_path:
:return: the loaded image
"""
image = Image.open(image_path)
image = loader(image)
image = image.unsqueeze(0)
image = image.to(device, torch.float)
return image | 5,332,021 |
def feed_reader(url):
"""Returns json from feed url"""
content = retrieve_feed(url)
d = feed_parser(content)
json_string = json.dumps(d, ensure_ascii=False)
return json_string | 5,332,022 |
def create_app(env_name):
"""
Create app
"""
# app initiliazation
app = Flask(__name__)
app.config.from_object(app_config[env_name])
cors = CORS(app)
# initializing bcrypt and db
bcrypt.init_app(app)
db.init_app(app)
app.register_blueprint(book_blueprint, url_prefix='/api/v1/books')
@app... | 5,332,023 |
def test_md020_bad_multiple_within_paragraph_separated_shortcut_image_multi():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md020 directory that has a closed atx heading with bad spacing
inside of the start hashes, multiple times in the same... | 5,332,024 |
def test_update_rate():
"""
Testing that the update methods get a correct timedelta
"""
# TODO : investigate if node multiprocessing plugin would help simplify this
# playing with list to pass a reference to this
testing_last_update = [time.time()]
testing_time_delta = []
acceptable_time... | 5,332,025 |
def get_shed_tool_conf_dict( app, shed_tool_conf ):
"""Return the in-memory version of the shed_tool_conf file, which is stored in the config_elems entry in the shed_tool_conf_dict associated with the file."""
for index, shed_tool_conf_dict in enumerate( app.toolbox.shed_tool_confs ):
if shed_tool_conf ... | 5,332,026 |
def _improve_attribute_docs(obj, name, lines):
"""Improve the documentation of various attributes.
This improves the navigation between related objects.
:param obj: the instance of the object to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
... | 5,332,027 |
def validate_environment(args):
"""
Validate an environment description for JSSPP OSP.
:param args: The command line arguments passed to this command.
"""
logging.info('Processing file %s', args.file.name)
logging.info('Validating structural requirements')
schema = load_environment_schema()... | 5,332,028 |
def write(data, filename):
"""Write a dictionary of FASTA sequences to file.
Arguments:
---------
data: dict Dictionary of {sid: sequence}
filename: str Filename to write
"""
w = open(filename, 'w')
write_list = []
for title, sequence in data.items():
sequence_list = []
... | 5,332,029 |
def get_column_interpolation_dust_raw(key, h_in_gp1, h_in_gp2, index,
mask1, mask2, step1_a, step2_a,
target_a, dust_factors,
kdtree_index=None,
luminosity_factors = No... | 5,332,030 |
def configure_bgp_additional_paths(device, bgp_as):
""" Configure additional_paths on bgp router
Args:
device ('obj'): device to use
bgp_as ('int'): bgp router to configure
Returns:
N/A
Raises:
SubCommandFailure: Failed executing configure com... | 5,332,031 |
def _get_next_foldername_index(name_to_check,dir_path):
"""Finds folders with name_to_check in them in dir_path and extracts which one has the hgihest index.
Parameters
----------
name_to_check : str
The name of the network folder that we want to look repetitions for.
dir_path : str
... | 5,332,032 |
def index_hydrate(params, container, cli_type, key, value):
"""
Hydrate an index-field option value to construct something like::
{
'index_field': {
'DoubleOptions': {
'DefaultValue': 0.0
}
}
}
"""
if 'IndexFiel... | 5,332,033 |
def test_state_apply_aborts_on_pillar_error(
salt_cli,
salt_minion,
base_env_pillar_tree_root_dir,
):
"""
Test state.apply with error in pillar.
"""
pillar_top_file = textwrap.dedent(
"""
base:
'{}':
- basic
"""
).format(salt_minion.id)
b... | 5,332,034 |
def oio_make_subrequest(env, method=None, path=None, body=None, headers=None,
agent='Swift', swift_source=None,
make_env=oio_make_env):
"""
Same as swift's make_subrequest, but let some more headers pass through.
"""
return orig_make_subrequest(env, method... | 5,332,035 |
def offline_data_fetcher(cfg: EasyDict, dataset: Dataset) -> Callable:
"""
Overview:
The outer function transforms a Pytorch `Dataset` to `DataLoader`. \
The return function is a generator which each time fetches a batch of data from the previous `DataLoader`.\
Please refer to the link h... | 5,332,036 |
def graph_methods_for_all_datasets(trunc, series, output_dir):
"""
Graphs the statistics from series for all of the datasets.
Args:
df (pandas dataframe) : The dataframe containing the data series.
num_epochs (int) : How many epochs to graph (always includes last epoch)
series (str)... | 5,332,037 |
def get_channel(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetChannelResult:
"""
Resource schema for AWS::MediaPackage::Channel
:param str id: The ID of the Channel.
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
o... | 5,332,038 |
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return torch.nn.functional.relu
if activation == "gelu":
return torch.nn.functional.gelu
if activation == "glu":
return torch.nn.functional.glu
raise RuntimeError(F... | 5,332,039 |
def make_05dd():
"""移動ロック終了(イベント終了)"""
return "" | 5,332,040 |
def lambda_handler(request, context):
"""Main Lambda handler.
Since you can expect both v2 and v3 directives for a period of time during the migration
and transition of your existing users, this main Lambda handler must be modified to support
both v2 and v3 requests.
"""
try:
logger.in... | 5,332,041 |
def test_lfa_tested_nodes_make_more_contacts_if_risky(
simple_model_risky_behaviour_2_infections: simple_model_risky_behaviour_2_infections
):
"""Create 2 initial infections, one who engages in risky behaviour while LFA tested
and one who doesn't.
Set both to being lfa tested.
Sets the househ... | 5,332,042 |
def batch_flatten(x):
"""Turn a n-D tensor into a 2D tensor where
the first dimension is conserved.
"""
y = T.reshape(x, (x.shape[0], T.prod(x.shape[1:])))
if hasattr(x, '_keras_shape'):
if None in x._keras_shape[1:]:
y._keras_shape = (x._keras_shape[0], None)
else:
... | 5,332,043 |
def msg_constant_to_behaviour_type(value: int) -> typing.Any:
"""
Convert one of the behaviour type constants in a
:class:`py_trees_ros_interfaces.msg.Behaviour` message to
a type.
Args:
value: see the message definition for details
Returns:
a behaviour class type (e.g. :class:... | 5,332,044 |
def calc_skewness(sig):
"""Compute skewness along the specified axes.
Parameters
----------
input: ndarray
input from which skewness is computed.
Returns
-------
s: int
skewness result.
"""
return skew(sig) | 5,332,045 |
def im2vid(img_path, name):
"""
Creates video from corresponding frames
:param img_path: path where the images are located. End of path must be /*.{image extension}, e.g. /*.jpg
:param name: name of the video
:return:
"""
img_array = []
for filename in tqdm(glob.glob(img_path), desc='Lo... | 5,332,046 |
def upload_usp_family(folder,
group_label,
group_description,
stop_if_existing=True):
"""
Upload a set of usp/recpot files in a give group
:param folder: a path containing all UPF files to be added.
Only files ending in .usp/.recpot ... | 5,332,047 |
def check_is_pandas_dataframe(log):
"""
Checks if a log object is a dataframe
Parameters
-------------
log
Log object
Returns
-------------
boolean
Is dataframe?
"""
if pkgutil.find_loader("pandas"):
import pandas as pd
return type(log) is pd.Dat... | 5,332,048 |
def mk_creoson_post_sessionId(monkeypatch):
"""Mock _creoson_post return dict."""
def fake_func(client, command, function, data=None, key_data=None):
return "123456"
monkeypatch.setattr(
creopyson.connection.Client, '_creoson_post', fake_func) | 5,332,049 |
def test_make_student_folder(clean_dir):
"""Test our utility function
"""
student_dir = make_student_folder(clean_dir, "jtd111")
# Check the folder we made
assert os.path.join(clean_dir, "jtd111") == student_dir
assert os.path.isdir(student_dir)
# Make sure that's all we've got in there
... | 5,332,050 |
def isUsernameFree(name):
"""Checks to see if the username name is free for use."""
global username_array
global username
for conn in username_array:
if name == username_array[conn] or name == username:
return False
return True | 5,332,051 |
def test_transform_bitmap_dark():
"""
Check function transform_bitmap_dark function on the
BMP_FILE_PATH define above.
Check: whether for each element in color map it has become smaller.
"""
# Instantiate Bitmap object with original file
original_bitmap = Bitmap.read_file(BMP_FILE_PATH)
... | 5,332,052 |
def get_quadrangle_dimensions(vertices):
"""
:param vertices:
A 3D numpy array which contains a coordinates of a quadrangle, it should look like this:
D---C
| |
A---B
[ [[Dx, Dy]], [[Cx, Cy]], [[Bx, By]], [[Ax, Ay]] ].
:return:
width, height (which are integers)
"""
temp = np.zeros((4, 2), dtype=int)... | 5,332,053 |
def optimal_r(points, range_min, range_max):
"""
Computes the optimal Vietoris-Rips parameter r for the given list of points.
Parameter needs to be as small as possible and VR complex needs to have 1 component
:param points: list of tuples
:return: the optimal r parameter and list of (r, n_componen... | 5,332,054 |
def get_root_path():
"""
this is to get the root path of the code
:return: path
"""
path = str(Path(__file__).parent.parent)
return path | 5,332,055 |
def usage(msg = None):
"""
Print a usage message and exit
"""
sys.stdout = sys.stderr
if msg != None:
print(msg)
print("Usage:")
print("dcae_admin_db.py [options] configurationChanged json-file")
print("dcae_admin_db.py [options] suspend")
print("dcae_admin_db.py [options] re... | 5,332,056 |
def _handle_requirements(hass: core.HomeAssistant, component,
name: str) -> bool:
"""Install the requirements for a component."""
if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'):
return True
for req in component.REQUIREMENTS:
if not pkg_util.instal... | 5,332,057 |
def check_image(filename):
""" Check if filename is an image """
try:
im = Image.open(filename)
im.verify() # is it an image?
return True
except OSError:
return False | 5,332,058 |
def encode_save(sig=np.random.random([1, nfeat, nsensors]), name='simpleModel_ini', dir_path="../src/vne/models"):
"""
This function will create a model, test it, then save a persistent version (a file)
Parameters
__________
sig:
a numpy array with shape (nsamples, nfeatures, nsensors). in ... | 5,332,059 |
def _imports_to_canonical_import(
split_imports: Set[Tuple[str, ...]],
parent_prefix=(),
) -> Tuple[str, ...]:
"""Extract the canonical import name from a list of imports
We have two rules.
1. If you have at least 4 imports and they follow a structure like
'a', 'a.b', 'a.b.c', 'a.b.d'
... | 5,332,060 |
def _bin_file(script):
"""Return the absolute path to scipt in the bin directory"""
return os.path.abspath(os.path.join(__file__, "../../../bin", script)) | 5,332,061 |
def r12writer(stream: Union[TextIO, str], fixed_tables: bool=False) -> 'R12FastStreamWriter':
"""
Context manager for writing DXF entities to a stream/file. `stream` can be any file like object
with a :func:`write` method or just a string for writing DXF entities to the file system.
If `fixed_tables` is... | 5,332,062 |
def test_get_time_step(initialized_bmi):
"""Test that there is a time step."""
time_step = initialized_bmi.get_time_step()
assert isinstance(time_step, float) | 5,332,063 |
def score_hmm_logprob(bst, hmm, normalize=False):
"""Score events in a BinnedSpikeTrainArray by computing the log
probability under the model.
Parameters
----------
bst : BinnedSpikeTrainArray
hmm : PoissonHMM
normalize : bool, optional. Default is False.
If True, log probabilities ... | 5,332,064 |
def rotate_2d_list(squares_list):
"""
http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python
"""
return [x for x in zip(*squares_list[::-1])] | 5,332,065 |
def next_ticket(ticket):
"""Return the next ticket for the given ticket.
Args:
ticket (Ticket): an arbitrary ticket
Returns:
the next ticket in the chain of tickets, having the next
pseudorandom ticket number, the same ticket id, and a
generation number that is one larger.
... | 5,332,066 |
def icecreamParlor4(m, arr):
"""I forgot about Python's nested for loops - on the SAME array - and how
that's actually -possible-, and it makes things so much simplier.
It turns out, that this works, but only for small inputs."""
# Augment the array of data, so that it not only includes the item, but
... | 5,332,067 |
def test_player_stats_bad(start_date='2020-02-28', end_date='2019-10-02'):
"""
Test function to check that function gracefully hanldes errors
when it is supposed to.
Keyword Arguments:
start_date {str} -- start_date to query (default: {'2020-02-28'})
end_date {str} -- end_date to query ... | 5,332,068 |
def insert_train_val_data(article_list, table_name):
"""
Inserts Train and Val data in the table name specified
Args:
article_list (list[dict]): Data to be stored in the database
table_name (str): name of the database table
Returns:
None
"""
for ... | 5,332,069 |
def get_data(filepath, transform=None, rgb=False):
"""
Read in data from the given folder.
Parameters
----------
filepath: str
Path for the file e.g.: F'string/containing/filepath'
transform: callable
A function which tranforms the data to the required format
rgb: bool
... | 5,332,070 |
def setup(hass, config):
"""Set up the Ecovacs component."""
_LOGGER.debug("Creating new Ecovacs component")
hass.data[ECOVACS_DEVICES] = []
hass.data[ECOVACS_CONFIG] = []
from ozmo import EcoVacsAPI, VacBot
ecovacs_api = EcoVacsAPI(
ECOVACS_API_DEVICEID,
config[DOMAIN].get(CO... | 5,332,071 |
def read_input_files(input_file: str) -> frozenset[IntTuple]:
"""
Extracts an initial pocket dimension
which is a set of active cube 3D coordinates.
"""
with open(input_file) as input_fobj:
pocket = frozenset(
(x, y)
for y, line in enumerate(input_fobj)
fo... | 5,332,072 |
def _set_span_yields(span_yields: Optional[SpanYields]):
"""Sets the current parent span list."""
task = _current_task()
if task is None:
# There is no current task, so we're not running in an async context.
# Set the spans for the current thread.
_non_async_span_yields.set(span_yields)
else:
se... | 5,332,073 |
def resnet101(pretrained=False, root='./pretrain_models', **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load... | 5,332,074 |
def insert_left_side(left_side, board_string):
"""
Replace the left side of the Sudoku board 'board_string' with 'left_side'.
"""
# inputs should match in upper left corner
assert(left_side[0] == board_string[0])
# inputs should match in lower left corner
assert(left_side[8] == low_left_digi... | 5,332,075 |
def collect_story_predictions(story_file, policy_model_path, nlu_model_path,
max_stories=None, shuffle_stories=True):
"""Test the stories from a file, running them through the stored model."""
def actions_since_last_utterance(tracker):
actions = []
for e in reverse... | 5,332,076 |
def get_plaintext_help_text(testcase, config):
"""Get the help text for this testcase for display in issue descriptions."""
# Prioritize a HELP_FORMAT message if available.
formatted_help = get_formatted_reproduction_help(testcase)
if formatted_help:
return formatted_help
# Show a default message and HEL... | 5,332,077 |
def test_encode_erc721_asset_data_type_error_on_token_id():
"""Test that passing a non-int for token_id raises a TypeError."""
with pytest.raises(TypeError):
encode_erc721_asset_data("asdf", "asdf") | 5,332,078 |
def xml_out(db):
"""XML output of basic stats"""
stats = basic_stats(db)
print('<?xml version="1.0"?>')
print('<idp-audit rps="%d" logins="%d" users="%d">'
% (stats['rps'], stats['logins'], stats['users']))
for rp, i in list(db['rp'].items()):
print(' <rp count="%d">%s</rp>' % (i,... | 5,332,079 |
def sniff(store=False, prn=None, lfilter=None,
count=0,
stop_event=None, refresh=.1, *args, **kwargs):
"""Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args)
store: wether to store sniffed packets or discard them
prn: function to ap... | 5,332,080 |
def generate_margined_binary_data ( num_samples, count, limits, rng ):
"""
Draw random samples from a linearly-separable binary model
with some non-negligible margin between classes. (The exact
form of the model is up to you.)
# Arguments
num_samples: number of samples to generate
... | 5,332,081 |
def import_timeseries(context, file, firstyear, lastyear):
"""Import time series data."""
context["scen"].read_file(Path(file), firstyear, lastyear) | 5,332,082 |
def _brighten_images(images: np.ndarray, brightness: int = BRIGHTNESS) -> np.ndarray:
"""
Adjust the brightness of all input images
:params images: The original images of shape [H, W, D].
:params brightness: The amount the brighness should be raised or lowered
:return: Images with adjusted brightne... | 5,332,083 |
def findBaseDir(basename, max_depth=5, verbose=False):
"""
Get relative path to a BASEDIR.
:param basename: Name of the basedir to path to
:type basename: str
:return: Relative path to base directory.
:rtype: StringIO
"""
MAX_DEPTH = max_depth
BASEDIR = os.path.abspath(os.path.dirna... | 5,332,084 |
def CreateMovie(job_name, input_parameter, view_plane, plot_type):
"""encoder = os.system("which ffmpeg")
print encoder
if(len(encoder) == 0):
feedback['error'] = 'true'
feedback['message'] = ('ERROR: Movie create encoder not found')
print feedback
return
"""
movie_name = job_name + '_' + input_parameter+ ... | 5,332,085 |
def _increment(i):
"""Generate a incrementing integer count, starting at and including i."""
while True:
yield i
i += 1 | 5,332,086 |
def describe_recurrence(recur, recurrence_dict, connective="and"):
"""Create a textual description of the recur set.
Arguments:
recur (Set): recurrence pattern as set of day indices eg Set(["1","3"])
recurrence_dict (Dict): map of strings to recurrence patterns
connective (Str): word to... | 5,332,087 |
def route_image_zoom_in():
"""
Zooms in.
"""
result = image_viewer.zoom_in()
return jsonify({'zoom-in' : result}) | 5,332,088 |
def evaluate_flow_file(gt_file, pred_file):
"""
evaluate the estimated optical flow end point error according to ground truth provided
:param gt_file: ground truth file path
:param pred_file: estimated optical flow file path
:return: end point error, float32
"""
# Read flow files and calcula... | 5,332,089 |
def get_heavy_load_rses(threshold, session=None):
"""
Retrieve heavy load rses.
:param threshold: Threshold as an int.
:param session: Database session to use.
:returns: .
"""
try:
results = session.query(models.Source.rse_id, func.count(models.Source.rse_id).label('load'))\
... | 5,332,090 |
def facetcolumns(table, key, missing=None):
"""
Like :func:`petl.util.materialise.columns` but stratified by values of the
given key field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 2, True],
...... | 5,332,091 |
def unzip_file(filename, target_directory):
"""
Given a filename, unzip it into the given target_directory.
"""
with zipfile.ZipFile(filename) as z:
z.extractall(target_directory) | 5,332,092 |
def divide_set(vectors, labels, column, value):
"""
Divide the sets into two different sets along a specific dimension and value.
"""
set_1 = [(vector, label) for vector, label in zip(vectors, labels) if split_function(vector, column, value)]
set_2 = [(vector, label) for vector, label in zip(vectors... | 5,332,093 |
def execute_freezerc(dict, must_fail=False, merge_stderr=False):
"""
:param dict:
:type dict: dict[str, str]
:param must_fail:
:param merge_stderr:
:return:
"""
return execute([FREEZERC] + dict_to_args(dict), must_fail=must_fail,
merge_stderr=merge_stderr) | 5,332,094 |
def train_model(model, device, data_train, data_dev, x_dev, y_dev, optimizer, criterion,
num_epochs, model_save_path, window_len, stride_len, valid_period):
"""Training function"""
print('Start training the model')
writer = SummaryWriter(comment='__' + 'Overtesting')
# weight decay
schedul... | 5,332,095 |
def corField2D_vector(field):
"""
2D correlation field of a vector field. Correlations are calculated with
use of Fast Fourier Transform.
Parameters
----------
field : (n, n, 2) shaped array like
Vector field to extract correlations from.
Points are supposed to be uniformly dist... | 5,332,096 |
def load_json_fixture(filename: str):
"""Load stored JSON data."""
return json.loads((TEST_EXAMPLES_PATH / filename).read_text()) | 5,332,097 |
def stat_list_card(
box: str,
title: str,
items: List[StatListItem],
name: Optional[str] = None,
subtitle: Optional[str] = None,
commands: Optional[List[Command]] = None,
) -> StatListCard:
"""Render a card displaying a list of stats.
Args:
box: A string ... | 5,332,098 |
def test_DataGeneratorAllSpectrums_fixed_set():
"""
Test whether use_fixed_set=True toggles generating the same dataset on each epoch.
"""
# Get test data
binned_spectrums, tanimoto_scores_df = create_test_data()
# Define other parameters
batch_size = 4
dimension = 88
# Create norm... | 5,332,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.