content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_costate_rates(ham, states, costate_names, derivative_fn):
"""Make costates."""
costates = [SymVar({'name': lam, 'eom':derivative_fn(-1*(ham), s)})
for s, lam in zip(states, costate_names)]
return costates | 73,800 |
def test_store_status_called_without_args():
"""Tests that `store_status` calls the callback function without args."""
# Given
build_results = create_dummy_build_result()
mock_status_callback = MagicMock()
# When
build_results.store_status(mock_status_callback)
# Then
mock_status_callb... | 73,801 |
def projection():
""" RESTful CRUD controller """
if deployment_settings.get_security_map() and not s3_has_role("MapAdmin"):
unauthorised()
tablename = module + "_" + resourcename
table = db[tablename]
# CRUD Strings
ADD_PROJECTION = T("Add Projection")
LIST_PROJECTIONS = T("List... | 73,802 |
def parse_segments(segments_str):
"""
Parse segments stored as a string.
:param vertices: "v1,v2,v3,..."
:param return: [(v1,v2), (v3, v4), (v5, v6), ... ]
"""
s = [int(t) for t in segments_str.split(',')]
return zip(s[::2], s[1::2]) | 73,803 |
def print_attack_results(attack_name: str, attack_results: AttackResult):
"""
Takes the attack name and the attack result object and prints the results to the console.
"""
print(
f'{attack_name}: \n ' + f'\tRecall: {attack_results.recall:.4f} \t Precision: {attack_results.precision:.4f} ' +
... | 73,804 |
def GetFirstWord(buff, sep=None):#{{{
"""
Get the first word string delimited by the supplied separator
"""
try:
return buff.split(sep, 1)[0]
except IndexError:
return "" | 73,805 |
def setup_periodic_tasks(sender, **kwargs):
"""
Creates periodic tasks after celery is initialized
:param sender: Celery app
"""
sender.add_periodic_task(30.0, test_domains, name='Every 30s check domains') | 73,806 |
def reset():
"""
Resets the visited status of matrix and the operators in the generated AST.
"""
for m in matrix.visited:
m.visited = False
matrix.visited = []
matrix.ml = MLContext(matrix.sc)
matrix.dml = []
matrix.script = pydml('') | 73,807 |
def modify_bboxs_to_keypoints(json_src, pad_frac=0.1, plot=False):
"""Goes through any unidentified bboxs, and modifies them to be the bounding box of the joints, + padding.
pad_frac is a frac of avg(img height, img width)"""
img_dir = r"E:\IIB Project Data\Training data sets\Dogs\youtube_clips_1\output_frames"
w... | 73,808 |
def test_np_list_td_corr():
"""
correlation: comparing TLS emission corr. (np-list td format)
"""
# both H and c_ops are time-dependent
# calculate emission zero-delay second order correlation, g2[0], for TLS
# with following parameters:
# gamma = 1, omega = 2, tp = 0.5
# Then: g2(0)... | 73,809 |
def get_table(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTableResult:
"""
Resource Type definition for AWS::DynamoDB::Table
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts = pulumi.InvokeOptions()
if opts.versio... | 73,810 |
def load_perezfornos2012(shuffle=False, subjects=None, figures=None,
random_state=0):
"""Load data from [PerezFornos2012]_
Load the brightness associated with joystick position data described in
[PerezFornos2012]_.
Datapoints were extracted from Figures 3-7 of the paper.
... | 73,811 |
def add_actor_batch(asset_list):
""" Add an actor to the level for each entry in the asset_list
each value in the List has to be an `ObjectInfo` instance.
"""
msg = 'AddActorBatch'
for obj_info in asset_list:
line = object_info_to_string(obj_info)
msg = msg + "\n" + line
_lg.debu... | 73,812 |
def filter_tests(tests: Set[str], exclude_tests: List[str]) -> Set[str]:
"""
Exclude tests which have been denylisted.
:param tests: Set of tests to filter.
:param exclude_tests: Tests to filter out.
:return: Set of tests with exclude_tests filtered out.
"""
tests = {test for test in tests ... | 73,813 |
def setup_Component_with_parameters():
"""
Sets up a Component with parameters and all options used.
"""
comp = setup_Component_all_keywords()
comp._unfreeze()
# Need to set up attribute parameters
comp.new_par1 = 1.5
comp.new_par2 = 3
comp.new_par3 = None
comp.this_par = "test... | 73,814 |
def dpuSetTaskPriority(task, priority):
"""
Set the priority of one DPU task. Priority range is 0 to 15, 0 has the highest priority.
The priority of the task when it was created defaults to 15.
"""
return pyc_libn2cube.pyc_dpuSetTaskPriority(task, c_int(priority)) | 73,815 |
def find_std(arr):
"""
This function determines the standard deviation of the given array.
Args:
arr = numpy array for which the standard deviation and means are to be determined
Returns:
std = standard deviation of the given array
mean = mean value of the given array
Usage... | 73,816 |
def host(context):
"""
Bootstrap a machine to be an Ansible target host.
:param context: Click context
"""
context.obj.run_playbook(playbook_relative_path='bootstrap/host', ) | 73,817 |
def process(frame: np.ndarray, mask: np.ndarray = None, hsv: np.ndarray = None, *,
lower=(20, 100, 100), upper=(35, 255, 255),
min_area_prop=1/64, focal_length=208.5):
"""Find cubes using our vision algorithm.
Args
----
frame: the image to process
mask: optional array to sto... | 73,818 |
async def key(client, message, **kwargs):
"""Store your Challonge API key
Look for it here: https://challonge.com/settings/developer
Optional Argument:
key -- the Challonge API key
"""
if kwargs.get('key') and len(kwargs.get('key')) % 8 != 0:
await client.send_message(message.author, '❌ ... | 73,819 |
def required_daemons(instance):
"""
Return which daemon types are required by the instance
"""
daemons = [DaemonType.SENSOR]
if isinstance(instance.scheduler, DagsterDaemonScheduler):
daemons.append(DaemonType.SCHEDULER)
if isinstance(instance.run_coordinator, QueuedRunCoordinator):
... | 73,820 |
def get_matching_s3_objects(bucket, prefix="", suffix=""):
"""
Generate objects in an S3 bucket.
Parameters
----------
bucket : str
Name of the s3 bucket.
prefix : str, optional
Only fetch objects whose key starts with this prefix, by default ''
suffix : str, optional
... | 73,821 |
def SplitDictOfTensors(t_dict, num_splits):
"""Splits tensors in `t_dict` evenly into `num_splits` along the 1st dimenion.
Args:
t_dict: A dictionary of tensors. Each tensor's 1st dimension is the same
size.
num_splits: A python integer.
Returns:
A list of dictionaries of tensors, num elements... | 73,822 |
def add_gradient_noise(t, stddev=1e-3, name=None):
"""
Adds gradient noise as described in http://arxiv.org/abs/1511.06807 [2].
The input Tensor `t` should be a gradient.
The output will be `t` + gaussian noise.
0.001 was said to be a good fixed value for memory networks [2].
"""
with tf.name_scope(values... | 73,823 |
def _read_csv(
reader,
header=True,
skiprows=0,
numeric=True,
columns=None,
index=None,
index_col=None,
):
"""
Reads a file in as a DataFrame.
:param reader: A file handle or filename.
:param headers: True if headers are on the first line of data, false otherwise.
:param... | 73,824 |
def find_entering_variable(
tableau: npt.NDArray, pivot_row_index: int, non_basic_variables: set
) -> Any:
"""
Finds the non-basic variable which becomes basic after pivoting
Parameters
----------
tableau : array
A tableau corresponding to a vertex of a Polytope.
pivot_row_index : i... | 73,825 |
def activity_final(self):
"""Find or create a final node in a Activity
Note that while UML allows multiple final nodes, use of this routine assumes a single is sufficient.
:return: FinalNode for Activity
"""
final = [a for a in self.nodes if isinstance(a, FinalNode)]
if not final:
self.... | 73,826 |
def contar_caracteres(s):
"""
FUNÇÃO QUE CONTA OS CARACTERES DE UMA STRING
:param s: string a ser contada
"""
num_of_caracteres = {}
for caracter in s:
num_of_caracteres[caracter] = (num_of_caracteres.get(caracter, 0) + 1)
return num_of_caracteres | 73,827 |
def batch_and_learn(i, lock=threading.Lock()):
"""Thread target for the learning process."""
global step, stats
timings = Timings()
while step < args.total_steps:
timings.reset()
batch, agent_state = get_batch(
args,
free_queue,
full_queue,
... | 73,828 |
def parse_symmetric_morlet_single_scale_parameters( parameter_map ):
"""
Parses parameters for the single scale, symmetric Morlet wavelet generator.
Takes a dictionary of (key, string value)'s and casts the values to the
types expected by get_symmetric_morlet_single_scale_transform().
The following... | 73,829 |
def test_get_new_command():
""" Replace the Alt+Space character by a simple space """
assert get_new_command(Command(u"ps -ef | grep foo",
"")) == "ps -ef | grep foo" | 73,830 |
def keep_protein_class(data: Union[pd.DataFrame, PandasTextFileReader, Iterator], protein_data: pd.DataFrame,
classes: Optional[Union[dict, List[dict]]] = [{'l2': 'Kinase'}, {'l5': 'Adenosine receptor'}],
generic_regex: bool = False):
"""Keep only the data matching desi... | 73,831 |
def load_embeddings(env_config):
"""Attempt to loads user and movie embeddings from a json or pickle file.
Args:
env_config: `EnvConfig` class from movie_lens_simulator.py
Returns:
embedding_dict containing embeddings for movies and users
"""
path = env_config.embeddings_path
embedding_dict = load... | 73,832 |
def reset_db(ctx: click.Context, yes: bool) -> None:
"""
Wipes all user-created data and resets the database back to its freshly initialized state.
"""
config = ctx.obj["CONFIG"]
if yes:
are_you_sure = "y"
else:
echo_red(
"This will drop all data from the Fides databa... | 73,833 |
def find_one_file(directory, pattern):
"""
Use :func:`find_files()` to find a file and make sure a single file is matched.
:param directory: The pathname of the directory to be searched (a string).
:param pattern: The filename pattern to match (a string).
:returns: The matched pathname (a string).
... | 73,834 |
def image_hosting():
"""
图床
"""
# from app.util import file_list_qiniu
# imgs = file_list_qiniu()
page = request.args.get('page',1, type=int)
imgs = Picture.query.order_by(Picture.id.desc()). \
paginate(page, per_page=20, error_out=False)
return render_template('admin/image_hosti... | 73,835 |
def get_domain_ip(domain):
"""
Get the IP for the domain. Any IP that responded is good enough.
"""
if domain.canonical.ip is not None:
return domain.canonical.ip
if domain.https.ip is not None:
return domain.https.ip
if domain.httpswww.ip is not None:
return domain.http... | 73,836 |
def shutdown(exit_code=0) -> None:
"""
Safely close down the ingress application.
:param exit_code: raise a system exit with the provided exit code. Defaults to 0.
"""
LOG.info('Shutting Down.')
get_singleton_instance(tweepy.Stream).disconnect()
sys.exit(exit_code) | 73,837 |
def create_frame(i):
"""Helper function to create snapshot objects."""
snap = gsd.hoomd.Snapshot()
snap.configuration.step = i + 1
return snap | 73,838 |
def BPR_Loss(positive : torch.Tensor, negative : torch.Tensor) -> torch.Tensor:
"""
Given postive and negative examples, compute Bayesian Personalized ranking loss
"""
distances = positive - negative
loss = - torch.sum(torch.log(torch.sigmoid(distances)), 0, keepdim=True)
return loss | 73,839 |
def _add_line_rectangle_ellipse(layer, event, data, shape_type):
"""Helper function for adding a a line, rectangle or ellipse."""
# on press
# Start drawing rectangle / ellipse / line
layer.add(data, shape_type=shape_type)
layer.selected_data = {layer.nshapes - 1}
layer._value = (layer.nshapes ... | 73,840 |
def gen_segment(curr_img, curr_predictor,
try_bools = [False, False],
out_trk = None):
"""Apply different methods (see try_bools) iteratively to try to segment
a single shot (non-ALC) image. Because image source is not a mosaic,
extent jittering (zooming in and out) is ... | 73,841 |
def test_tips():
"""Test module tips.py by downloading
tips.csv and testing shape of
extracted data has 244 rows and 7 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = tips(test_path)
try:
assert x_train.shape == (244, 7)
except:
shutil.rmtree(test_path)
raise() | 73,842 |
async def test_relays_stop(control_motors_relays, hass, lcn_connection):
"""Test the relays cover stops."""
states = [MotorStateModifier.NOCHANGE] * 4
states[0] = MotorStateModifier.STOP
state = hass.states.get("cover.cover_relays")
state.state = STATE_CLOSING
# command failed
control_moto... | 73,843 |
def query(url):
"""Send the query url and return the DOM
Exception is raised if there is errors"""
u = urllib.FancyURLopener(HTTP_PROXY)
usock = u.open(url)
dom = minidom.parse(usock)
usock.close()
errors = dom.getElementsByTagName('Error')
if errors:
e = buildException(errors)
raise e
return dom | 73,844 |
def expandFilename(filename):
"""Get the actual file name.
Parameters
----------
filename: str
A file or directory name.
Returns
-------
full_file_name: str
The real directory name.
"""
fname = filename
done = False
count = 0
while not done:
tem... | 73,845 |
def reshape_img(image):
"""
Reshape an image into the form (height, width, channels).
:param image (np.array): Loaded image
:return: reshaped (np.array): Reshaped image
"""
img = []
for i in range(3):
img_c = np.reshape(image[channel * i:channel * (i + 1)], (image_size, image_size)... | 73,846 |
def clear():
"""
Clear all captured images in main code folder.
"""
files = os.listdir()
for file in files:
if 'snap' in file:
os.remove(file)
print('Trash files are clear') | 73,847 |
def test_svd_threshold():
"""
Test SVD threshold option of BDCSVD
"""
with pytest.raises(
ValueError,
match="The svd_threshold option is available only for non-sparse solvers.",
):
# 1D Lattice
g = nk.graph.Hypercube(length=20, n_dim=1, pbc=True)
# Hilbert sp... | 73,848 |
def RetArquivo(dir: str= '.',
prefix_data:bool= True,
radical_arquivo:str= 'arq',
dig_serial: int= 5,
extensao: str= 'dat',
incArq: int= 0,
) -> str:
"""
Gerar nomes de arquivos, com prefixo ... | 73,849 |
def set_levels(lst_all, lst_chiln, lng_level):
"""Top down recursive setting of nesting levels"""
lng_next = lng_level + 1
for id_child in lst_chiln:
dct_child = lst_all[id_child]
dct_child[ATT_LEVEL] = lng_level
lst_next = dct_child[ATT_CHILN]
if lst_next:
set_levels(lst_all, lst_next, lng_next)
return... | 73,850 |
def check_proplist(path, exp_out):
"""Verify that property list on PATH has a value of EXP_OUT"""
props = svntest.tree.get_props([path]).get(path, {})
if props != exp_out:
logger.warn("Expected properties: %s", exp_out)
logger.warn("Actual properties: %s", props)
raise svntest.Failure | 73,851 |
def ThreadPlugin():
"""
:return: thread plugin class
"""
from tests.test_plugins.threads_plugin import ThreadPlugin
return ThreadPlugin | 73,852 |
def get_distance(pos_1, pos_2):
"""Get the distance between two point
Args:
pos_1, pos_2: Coordinate tuples for both points.
"""
x1, y1 = pos_1
x2, y2 = pos_2
dx = x1 - x2
dy = y1 - y2
return math.hypot(dx, dy) | 73,853 |
def jsonContentCategories():
"""
Parses the Google Cloud content categories from a local txt file and returns a nested dictionary (ugly, but effective).
Returns:
Dictionary -- Nested dictionary of content categories.
"""
f = open("google_content_categories.txt", "r")
catArr = []
fo... | 73,854 |
def makeFigure():
"""
Makes figure 5.
"""
# Get list of axis objects
ax, f = getSetup((10, 10), (4, 3))
figureMaker(ax, *commonAnalyze(list_of_populations, 2), num_lineages=num_lineages)
subplotLabel(ax)
return f | 73,855 |
def test_is_not_empty_failure():
"""
validate_files.py: Run is_not_empty() with bad inputs
:raises ValidationException: always, if test is working
"""
a = []
assert v.is_not_empty(a) | 73,856 |
def preprocess_finance(decompressed_path, X_path, y_path):
"""Preprocess the Finance dataset for a Lasso problem.
Normalization performed:
- X with only columns with >= 3 non zero elements, norm-1 columns, and
a constant column to fit intercept
- y centered and set to std equal to 1
"""
n... | 73,857 |
def illust(illustration, directory, allow_duplicates, track):
"""Download an illustration by URL or ID."""
try:
download_image(
Client().fetch_illustration(illustration),
directory=(Path(directory or Config()["pixi"]["download_directory"])),
allow_duplicate=allow_dupl... | 73,858 |
def gauss2D_FIT(xy, x0, y0, sigma_x, sigma_y):
"""Version of gauss2D used for fitting (1 x_data input (xy)
and flattened output). Returns the value of a gaussian at a 2D set of points for the given
standard deviation with maximum normalized to 1.
The Gaussian axes are assumed to be 90 degrees from e... | 73,859 |
def insert_many(sql, *args):
"""
执行SQL语句
:param sql: insert的SQL语句,可含?
:param args: insert的SQL语句所对应的值
:return: 最后插入行的主键ID
"""
return _insert(sql, True, *args) | 73,860 |
def _sub_matches_cl(subs, state_expr, state):
""" Checks whether any of the substitutions in subs will be applied to
state_expr
Arguments:
subs: substitutions in tuple format
state_expr: target symbolic expressions in which substitutions will
be applied
state: target symboli... | 73,861 |
def get_full_json(job_id: str = None,
textract_api: Textract_API = Textract_API.DETECT,
boto3_textract_client=None,
job_done_polling_interval=1) -> dict:
"""returns full json for call, even when response is chunked"""
logger.debug(f"get_full_json: job_id: {j... | 73,862 |
def get_time_from_filename(file_name, date_extraction_pattern, date_pattern):
"""
@param file_name name of the file
@param date_extraction_pattern regular expression describing how the date is represented in the filename
@param date_pattern
"""
file_str = os.path.basename(file_name)
matches ... | 73,863 |
def calc_sense_prob(x, S):
"""
This function calculates the probabilities for x (can be a lemma or a key)
from S (can be a Semantic Class or a Wordnet Synset)
"""
if isinstance(S, Semantic_Class):
pass
elif isinstance(S, nltk.corpus.reader.wordnet.Synset):
if isinsta... | 73,864 |
def find_fxn(tu, fxn, call_graph):
"""
Looks up the dictionary associated with the function.
:param tu: The translation unit in which to look for locals functions
:param fxn: The function name
:param call_graph: a object used to store information about each function
:return: the dictionary for t... | 73,865 |
def _prepare_embeddings(h, m):
"""
Combine FCN outputs with segmentation masks to build a batch of
mask-pooled hidden vectors. Represents the calculation of h_{m}
in the first equation in Henaff et al's paper
:h: batch of embeddings; (N,w,h,d)
:m: batch of NORMALIZED segmentation tensors; ... | 73,866 |
def estimate_mode_width(distribution):
"""Estimate mode and width-at-half-maximum for a 1D distribution.
Parameters
----------
distribution : array of int or float
The input distribution. ``plt.plot(distribution)`` should look
like a histogram.
Returns
-------
mode : int
... | 73,867 |
def agent_hostname_by_id(agent_id):
"""Given a agent_id provides the agent ip"""
for agent in __get_all_agents():
if agent['id'] == agent_id:
return agent['hostname']
return None | 73,868 |
def detect_person(gcs_uri="gs://YOUR_BUCKET_ID/path/to/your/video.mp4"):
"""Detects people in a video."""
client = videointelligence.VideoIntelligenceServiceClient()
# Configure the request
config = videointelligence.types.PersonDetectionConfig(
include_bounding_boxes=True,
inc... | 73,869 |
def parse_tile_name(name: str):
""" Parse the tile """
match = reTILE.match(name)
if match is None:
return None
groups = match.groupdict() # type: Dict[str, Any]
groups['tile'] = int(groups['tile'])
return groups | 73,870 |
def save_format(file):
"""Return 'mat' or 'py' based on file name extension."""
ext = os.path.splitext(file)[1]
return ext[-(len(ext) - 1):] | 73,871 |
def test_metrics_aggerrs(monkeypatch):
"""Mock response to test metrics while aggregating errors."""
df = pd.DataFrame(dict(x=[1, 2, 3, 4], y=[1, 2, 3, 4]))
mock_predict = lambda *x, **y: df.x.rename("y") # perfect response
class Model(Normal):
dv = "y"
features = dict(x=dict(transform... | 73,872 |
def query_object_elasticsearch(query_string, item_type="tor"):
"""Return a dict of Elasticsearch results."""
# make an http request to elasticsearch
#pool = urllib3.HTTPSConnectionPool(settings.ELASTICSEARCH_HOST,
# settings.ELASTICSEARCH_PORT,
# assert_fingerprint=settings.ELASTICSEAR... | 73,873 |
def article_to_frequency(article: str) -> List[int]:
"""Convert an article or article description to a list of numbers.
:param article: The article or article description
:return: A list of numbers corresponding to the words
"""
numbers: List[int] = [0] * len(common_words)
article_words = artic... | 73,874 |
def test_actual_results_itakura_parallelogram(params, arr_desired):
"""Test that the actual results are the expected ones."""
arr_actual = itakura_parallelogram(**params)
np.testing.assert_allclose(arr_actual, arr_desired, atol=1e-5, rtol=0.) | 73,875 |
def track_requests(fn):
""" Decorator to log 21 sell request data.
Args:
fn: function to wrap
"""
@wraps(fn)
def decorator(*args, **kwargs):
service_name = os.environ["SERVICE"]
url = request.url
host = request.headers["Host"]
endpoint = url.strip("https:/... | 73,876 |
def Date(default=None, validator=None, repr=False, eq=True, order=True, # NOQA
converter=None, label=None, help=None,): # NOQA
"""
A date attribute. It always serializes to an ISO date string.
Behavior is TBD and for now this is exactly a string.
"""
return String(
default=defau... | 73,877 |
def compute_confuse_matrix_batch(y_targetlabel_list,y_logits_array,label_dict,name='default'):
"""
compute confuse matrix for a batch
:param y_targetlabel_list: a list; each element is a mulit-hot,e.g. [1,0,0,1,...]
:param y_logits_array: a 2-d array. [batch_size,num_class]
:param label_dict:{label:... | 73,878 |
def test_get_account_short_name_replaces_spaces_with_underscores():
"""It replaces spaces in account short names with underscores."""
pacioli = Pacioli(config_file="tests/resources/sample_config.yml")
name = pacioli.get_account_short_name("Assets:Longterm:Real Estate")
assert name == "real_estate" | 73,879 |
def jsonify_item(category_id, item_id):
"""Return an item information of a category in JSON"""
try:
item = db.session.query(Item).filter_by(
category_id=category_id, id=item_id).one()
return jsonify(Item=item.serialize)
except Exception as e:
abort(404) | 73,880 |
def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
custom_typing_module: str = None) -> MypyFile:
"""Parse a source file, without doing any semantic analysis.
Return the parse tree. If errors is not provided, ... | 73,881 |
def check_AP_raw(abf,n=10):
"""X"""
timePoints=get_AP_timepoints(abf)[:n] #first 10
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP shape (n=%d)"%n,xlabel="ms")
Ys=abf.get_data_around(timePoints,padding=.2)
Xs=(np.arange(len(Ys[0]))-len(Ys[0])/2)*1000/abf.rate
for i ... | 73,882 |
def encode_multipart_formdata(fields, files):
#http://code.activestate.com/recipes/146306/
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance... | 73,883 |
def test_get_chan_type(chan: str, expected: Union[str, None]) -> None:
"""Test to_resistics_chan"""
from resistics.common import get_chan_type
if expected is None:
with pytest.raises(ValueError):
get_chan_type(chan)
return
assert get_chan_type(chan) == expected | 73,884 |
def ParseMaxRevision(revision_list):
"""Returns the max revision from a list of url@revision string."""
revision_re = re.compile(r'.*@(\d+)')
def RevisionKey(revision):
return revision_re.match(revision).group(1)
max_revision = max(revision_list.split(), key=RevisionKey)
return max_revision.rpartition('... | 73,885 |
def get_resolv_conf_namservers() -> List[str]:
"""Return list of namserver IPs in /etc/resolv.conf."""
result = []
with open("/etc/resolv.conf") as f:
for line in f:
parts = line.lower().split()
if len(parts) >= 2 and parts[0] == 'nameserver':
result.append(pa... | 73,886 |
def get_sfcwind_6() -> None:
"""Get the CMIP6 surface wind from the figure data."""
# wsp = can_coords(return_figure_ds("5d")["wnspClim"])
wsp = can_coords(xr.open_dataarray(os.path.join(CMIP6_CLIM60_PATH, "wsp.nc")))
print(wsp.max())
print(wsp.min())
wsp = wsp.where(wsp < 20).fillna(20)
# w... | 73,887 |
def import_gloss_csv(request):
"""
Check which objects exist and which not. Then show the user a list of glosses that will be added if user confirms.
Store the glosses to be added into sessions.
"""
glosses_new = []
glosses_exists = []
# Make sure that the session variables are flushed befor... | 73,888 |
def _showvid(video_name, from_frame = 0):
"""
HELPER FUNCTION
Navigate through video frame by frame from a certain frame.
:param video_name: videopath
:param from_frame: show vid from this frame
:return: nothing
"""
cap = cv2.VideoCapture(str(video_name))
cap.set(1, from_frame)
... | 73,889 |
def transfer_cnn_weights(model, source_path, split, selection="best_balanced_accuracy", cnn_index=None):
"""
Set the weights of the model according to the CNN at source path.
:param model: (Module) the model which must be initialized
:param source_path: (str) path to the source task experiment
:para... | 73,890 |
def TweetColecting(list_of_kw, startdate, enddate, exclude, outfile):
"""
Function to parse tweets between period of time based on included/excluded keywords.
Tweet Manager has been modified to fixed the error of stopping halfway due to time limit exceed
Current info retrieved including:
- id
- text (with emojies... | 73,891 |
def vis_timeslices(vis: Visibility, timeslice='auto') -> int:
""" Calculate number of time slices in a visibility
:param vis: Visibility
:param timeslice: 'auto' or float (seconds)
:return: Number of slices
"""
assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis
tim... | 73,892 |
def alexnet_metapoison(widths=[16, 32, 32, 64, 64], in_channels=3, num_classes=10, batchnorm=False):
"""AlexNet variant as used in MetaPoison."""
def convblock(width_in, width_out):
if batchnorm:
bn = torch.nn.BatchNorm2d(width_out)
else:
bn = torch.nn.Identity()
... | 73,893 |
def test_wrong_negated_complex_conditions(
code,
template,
assert_errors,
parse_ast_tree,
default_options,
):
"""Testing complex conditions with nagated ``if`` condition."""
tree = parse_ast_tree(template.format(code))
visitor = IfStatementVisitor(default_options, tree=tree)
visitor... | 73,894 |
def find_paths_with_suid_sgid(root_path):
"""Finds all paths/files which have an suid/sgid bit enabled.
Starting with the root_path, this will recursively find all paths which
have an suid or sgid bit set.
"""
cmd = ['find', root_path, '-perm', '-4000', '-o', '-perm', '-2000',
'-type', '... | 73,895 |
def checksum(message):
"""
Calculate the GDB server protocol checksum of the message.
The GDB server protocol uses a simple modulo 256 sum.
"""
check = 0
for c in message:
check += ord(c)
return check % 256 | 73,896 |
def sds_bmm_torch(s_t1, d_t2):
"""
bmm (Batch Matrix Matrix) for sparse x dense -> sparse. This function doesn't support gradient.
And sparse tensors cannot accept gradient due to the limitation of torch implementation.
with s_t1.shape = (b, x, s), d_t2.shape = (b, s, y), the output shape is (b, x, y)
... | 73,897 |
def calc_fires(mappability_filename, cooler_filenames, bin_size, neighborhood_region, perc_threshold=.25, avg_mappability_threshold=0.9):
"""Perform FIREcaller algorithm.
Parameters:
----------
mappability_filename : str
Path to mappability file
cooler_filenames : str
List of paths ... | 73,898 |
def chown():
"""Sets proper permissions"""
sudo('chown -R www-data:www-data %s' % PROJECT_ROOT) | 73,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.