content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_transformation_id(action):
""" Get the id of a transformation.
Parameters
----------
action: function
The transformation function
Returns
-------
int
The id of the action (-1 if not found)
"""
for index, trans in TRANSFORMATIONS.items():
if trans == ... | 2f08e7bb2b0418d39421e6b03e011d8ab4d68380 | 5,928 |
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_chars(t, byref(s), REP_UTF8|CVT_STRING):
return s.value
else:
raise InvalidTypeError("string") | 1f128369f1ce3950ed352e43eea5db30f6da2d6e | 5,929 |
def prep_data(filename, in_len, pred_len):
"""load data from the file and chunk it into windows of input"""
# Columns are
# 0:datetime, 1:temperature, 2:humidity, 3:pressure, 4:wind_direction, 5:wind_speed
data = np.genfromtxt(filename, delimiter=',', skip_header=1,
usecols=(1, ... | 33e1348acdcf6025159b7ed81e18358d56838d3e | 5,930 |
def _get_security_group_id(connection, security_group_name):
"""
Takes a security group name and
returns the ID. If the name cannot be
found, the name will be attempted
as an ID. The first group found by
this name or ID will be used.)
:param connection:
:param security_group_name:
:... | 70c9b8357a9634043f07ad0019ff3cc621ba859c | 5,932 |
def viz_preprocessing(df_path):
"""
Preprocess the aggregation csv into a good format for visualization
"""
df = pd.read_csv(df_path)
res = df.T
res = res.rename(columns=res.iloc[0]).drop(res.index[0])
res = res.astype("int64")
res.reset_index(inplace=True)
res["index"] = res["index"... | fc1c39d094934aa47ac26f6e5a70f071c1df4fbd | 5,933 |
def adjacency(G, nodelist=None, weight="weight"):
"""
Returns the sparse adjacency matrix
representation of the graph.
"""
if nodelist is None:
nodelist = G.nodes()
A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight, format="csr")
return A | e17c0030a7d2c4e13659ca3585820e1c8da89101 | 5,935 |
from datetime import datetime
def sample_movie(user, **params):
"""Create and return a movie"""
defaults = {
'title': 'A Walk to Remember',
'duration': datetime.timedelta(hours=2, minutes=15),
'price': 8.99
}
defaults.update(params)
return Movie.objects.create(user=user, *... | d07716fbe4b043022592ae2465bb02d02f45fe41 | 5,936 |
import difflib
def lines_diff(lines1, lines2):
"""Show difference between lines."""
is_diff = False
diffs = list()
for line in difflib.ndiff(lines1, lines2):
if not is_diff and line[0] in ('+', '-'):
is_diff = True
diffs.append(line)
return is_diff, diffs | 50916d46871980fadfd854dc698481a4b0f35834 | 5,937 |
import re
def parse_ipmi_hpm(output):
"""Parse the output of the hpm info retrieved with ipmitool"""
hrdw = []
line_pattern = re.compile(r'^\|[^0-9]*([0-9]+)\|[^a-zA-Z ]* ?([^\|]*)\|([^\|]*)\|([^\|]*)\|([^\|]*)\|')
for line in output:
match = line_pattern.match(line)
if match:
... | 001731ce46fa6bbdb5103727265a0bdd353773be | 5,938 |
def get_genes_and_pathways(reactions, r_numbers, species):
"""Returns a CSV-formatted string with the list of genes and pathways where
the reaction(s) of 'species' appear.
:param reactions: list of reactions for species
:param r_numbers: RNumbers object
:param species: KEGG organism code
:retur... | 0ecddcaf50650b04125be73bcf6b304a77df011d | 5,939 |
def relate_ca(assessment, template):
"""Generates custom attribute list and relates it to Assessment objects
Args:
assessment (model instance): Assessment model
template: Assessment Temaplte instance (may be None)
"""
if not template:
return None
ca_definitions = all_models.CustomAttri... | 31744ac40f385746e6d4e13a97ed461312280d99 | 5,941 |
def getSenderNumberMgtURL(request):
"""
발신번호 관리 팝업 URL을 반환합니다.
- 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
- https://docs.popbill.com/fax/python/api#GetSenderNumberMgtURL
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 팝빌회원 아이디
UserID = settings.testUserID
... | 371ca0a813c54061c68af34719ca132081f0bfda | 5,942 |
def closest_match(match, specs, depth=0):
"""
Recursively iterates over type, group, label and overlay key,
finding the closest matching spec.
"""
new_specs = []
match_lengths = []
for i, spec in specs:
if spec[0] == match[0]:
new_specs.append((i, spec[1:]))
else:... | 3a212d880004fad843fe2d254ac96315bd1d12cf | 5,943 |
def average(w, axis=-1):
"""Calculate average
Example:
>>> w1=Waveform([range(2), range(2)],array([[1.0, 3.0], [0.0, 5.0]]))
>>> average(w1)
Waveform(array([0, 1]), array([ 2. , 2.5]))
>>> w1=Waveform([range(2), range(2)],array([[1.0, 3.0], [0.0, 5.0]]), \
xlabels=['row'... | bd5510e78c995e0a9f656144393b0496e071cdf5 | 5,944 |
def random():
"""Return a random parameter set for the model."""
total_thickness = 10**np.random.uniform(2, 4.7)
Nlayers = np.random.randint(2, 200)
d_spacing = total_thickness / Nlayers
thickness = d_spacing * np.random.uniform(0, 1)
length_head = thickness * np.random.uniform(0, 1)
length_... | 958410bb8a696652b5a58cb15168719c2391179d | 5,945 |
def extract_features_to_dict(image_dir, list_file):
"""extract features and save them with dictionary"""
label, img_list = load_image_list(image_dir, list_file)
ftr = feature
integer_label = label_list_to_int(label)
feature_dict = {'features': ftr,
'label': integer_label,
... | 2fe641d7bcc24f293fae0c8badf274c9f32051d4 | 5,946 |
def capitalize(s):
"""capitalize(s) -> string
Return a copy of the string s with only its first character
capitalized.
"""
return s.capitalize() | 1c9b86e2bbffc486d624e7305f303d517a282b75 | 5,948 |
def S_tunnel_e0(self, mu, sig, Efl, Efr, Tl, Tr):
"""energy flux
Conduction band edge 0 at higher of the two
"""
a = mu-sig/2
b = mu+sig/2
kTl = sc.k*Tl
kTr = sc.k*Tr
Blr = (a/kTl+1)*np.exp(-a/kTl)-(b/kTl+1)*np.exp(-b/kTl)
Brl = (a/kTr+1)*np.exp(-a/kTr)-(b/kTr+1)*np.exp(-b/kTr)
S... | 224b115d7205994e897bc74010fd4f24d562cc6c | 5,949 |
def to_camel_java(text, first_lower=True):
"""Returns the text in camelCase or CamelCase format for Java
"""
return to_camelcase(text, first_lower=first_lower,
reserved_keywords=JAVA_KEYWORDS, suffix="_") | c14b102502d7caa1dc51511ffd3c97f736a5c17b | 5,950 |
def rectangle_field(N_1, N_2, B_1, B_2, H, D, r_b):
"""
Build a list of boreholes in a rectangular bore field configuration.
Parameters
----------
N_1 : int
Number of borehole in the x direction.
N_2 : int
Number of borehole in the y direction.
B_1 : float
Distance (... | 955bc7f2bf3a79d790683e7589010bc81af98f85 | 5,951 |
def convertHunit(conc, from_unit='H/10^6 Si', to_unit='ppm H2O', phase='Fo90',
printout=True):
"""
Convert hydrogen concentrations to/from H/10^6 Si and ppm H2O.
Based on Table 3 of Denis et al. 2013
"""
if phase == 'Fo90':
H_to_1_ppm = 16.35
elif phase == 'opx':
H_t... | fdd0646a09f3a2c3a8cbbc02410103caa9e023dd | 5,952 |
import re
def countBasesInFasta(fastaFile):
"""
Given a fasta file, return a dict where the number of records and
the total number of bases are given by 'records' and 'bases' respectively.
"""
recordRE = re.compile(r'^>')
whiteSpaceRE = re.compile(r'\s+')
total_bases = 0
total_seqs = 0... | 45eaa5b8d36b4bae6b97bb29fdead1efc0aed8c2 | 5,953 |
import torchvision
import torch
def load_mnist_denoising(path_raw_dataset, batch_size=1, mu=0., sigma=0.6, deterministic=True):
"""
1. Get the MNIST dataset via PyTorch built-in APIs.
2. Wrap it with customized wrapper with additive Gaussian noise processor
3. Build PyTorch data loader objects.
:... | 4dbd365a0fa6d795714aa90828fe7bb2cbc9b99f | 5,954 |
def make_triplet_freqs(sentence, triplet_freqs):
"""
文字列を3つ組にする
"""
# Janomeで単語に分割する
t = Tokenizer()
morphemes = [token.surface for token in t.tokenize(sentence)]
if len(morphemes) < 3:
return {}
# 繰り返し
for i in range(len(morphemes) - 2):
triplet = tuple(morphemes[i... | 97fc3affd841e148f58de487d171df61745d17a9 | 5,955 |
def test_train_val_split(patient_id,
sub_dataset_ids,
cv_fold_number):
""" if cv_fold_number == 1:
if patient_id in sub_dataset_ids[-5:]: return 'test'
elif patient_id in sub_dataset_ids[-7:-5]: return 'validation'
else: return 'train'
... | 129f3856875033505555241408577f8885c9c393 | 5,956 |
def test_striplog_colour_plot():
"""
Tests mpl image of striplog with the ladder option.
"""
legend = Legend.builtin('NSDOE')
imgfile = "tutorial/M-MG-70_14.3_135.9.png"
striplog = Striplog.from_image(imgfile, 14.3, 135.9, legend=legend)
for iv in striplog:
iv.data['porosity'] = i... | a76f01a5b6255a0dfe39aca7cc3e352787457d17 | 5,958 |
def searchArtist(artistName, session=models.session):
"""Search for artist. Returns models.ArtistSearch"""
return models.ArtistSearch(artistName, session) | 4fd9e45b633285a9ee1817a84508749d1ba724e7 | 5,960 |
def _ddnone():
"""allow defaultdict to be pickled"""
return defaultdict(_none) | 9a050e08b0c47bc789f0238489c679d01a42c1ba | 5,961 |
def filter_shapely(feature):
"""
feature1 = feature_extract(feature)
feature2 = filter_shapely(feature1)
"""
tmp = extract_Accumulation_entropy_list(feature)
tmp2=[]
for i in range(len(tmp)):
if i!=0:
tmp2.append(tmp[i]-tmp[i-1])
else:
tmp2.a... | 54654130340a3485a7de9a3d5a51d3def8a01037 | 5,963 |
def stations_by_river(stations):
"""Returns a dictionary mapping river names (key)
to a list of stations (object)"""
rivers_stations_dict = {} # Create empty dictionary
for i in range(len(stations)): # Iterate through list of stations
# Data type checks
if type(stations[i]) is ... | d57bc06b60d6669bf6a10b7ad05363124f2312b5 | 5,964 |
def getCurrentProfile():
"""
Get the name of the current profile.
"""
return __createJSON("GetCurrentProfile", {}) | 6627d01348d566f0d079b8e7bcf04e35ad6ed0ba | 5,965 |
def get_params_from_request(req: web.Request) -> QueryParams:
"""
This function need for convert query string to filter parameters.
"""
page = int(req.rel_url.query.get('page', '1'))
cursor = req.rel_url.query.get('cursor')
sort = req.rel_url.query.get('sort')
sort_dir = req.rel_url.query.ge... | b0deb4e5a1dc10fe82745e6c3c0869015424e2e0 | 5,966 |
def norm_mem_interval(pt):
"""Normalize membership in interval."""
return pt.on_prop(arg_conv(binop_conv(auto.auto_conv()))) | b50aa86d942fe1c2f35c6bcffae350042ff86090 | 5,967 |
def create_figure():
"""
Creates a simple example figure.
"""
fig = Figure()
a = fig.add_subplot(111)
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
a.plot(t, s)
return fig | 532a4eda745cb969f8ef60e66d6f63e761b8a5ff | 5,968 |
def rdf_reader(src):
"""rdf = rdf_reader(src)
src rdf filename
rdf The RDF mapping object"""
return RDF(*list(rdf_include(src))) | cf64ee6ed12a3e0d1667a537ac696918d26f80ba | 5,969 |
def draw_signalData(Nsamp=1, alpha=__alpha, beta=__beta, **kwargs):
"""
draw an SNR from the signal distribution
"""
return np.array([ncx2.rvs(__noise_df, nc) for nc in __draw_truncatedPareto(Nsamp, alpha=alpha, beta=beta)]) | 6dc320e2289c30a0e68696be71ded30066d7fa74 | 5,970 |
def choose_weighted_images_forced_distribution(num_images, images, nodes):
"""Returns a list of images to cache
Enforces the distribution of images to match the weighted distribution as
closely as possible. Factors in the current distribution of images cached
across nodes.
It is important to note... | 8cf49fd376893be254d5075930475de9cedee004 | 5,971 |
def predict_lumbar_ankles_model(data):
"""Generate lumbar + 2 ankles model predictions for data.
Args:
data (dict): all data matrices/lists for a single subject.
Returns:
labels (dict): columns include 'probas' (from model) and 'true'
(ground truth). One row for each fold.
... | 581a45a71bb17ebebf3a8ea63dbbfb898c6e3567 | 5,972 |
def linear_search(iterable, item):
"""Returns the index of the item in the unsorted iterable.
Iterates through a collection, comparing each item to the target item, and
returns the index of the first item that is equal to the target item.
* O(n) time complexity
* O(1) space complexity
Args:
iterable:... | bdbd7e70cea79deef1375648bde61067df1d2221 | 5,974 |
def create_MD_tag(reference_seq, query_seq):
"""Create MD tag
Args:
reference_seq (str) : reference sequence of alignment
query_seq (str) : query bases of alignment
Returns:
md_tag(str) : md description of the alignment
"""
no_change = 0
md = []
for ref_base, query_ba... | 4b711521d00af132e8e29fe4fc44785b985c2607 | 5,975 |
def split_last(dataframe, target_col, sort_col='date', cut=.9):
"""Splits the dataframe on sort_column at the given cut ratio, and splits
the target column
Args:
dataframe: dataframe to be cut
sort_col: column to be sorted on. Default='date'
cut: cut ratio for the train/eval sets
... | 090144fa9c68f8ffc9e9e7c2e9c8427f0aff862d | 5,977 |
def ignore_warnings(obj=None):
""" Context manager and decorator to ignore warnings
Note. Using this (in both variants) will clear all warnings
from all python modules loaded. In case you need to test
cross-module-warning-logging this is not your tool of choice.
Examples
--------
>>> with ig... | 2fc8c4d12467ab3c0b86201271f42b7d22130b82 | 5,978 |
import csv
def readCSV(associated_ipaddr, ipaddr, timestamp):
"""
Method that extracts observations from a CSV file.
Parameters:
associated_ipaddr (str): The name of the column that specifies IP addresses of VPN clients
ipaddr (str): The name of the column that specifies IP ad... | 77594e98b83cd5d49bd8a70b28b54cab92dcadeb | 5,979 |
def interp2d(x, y, z, outshape, verbose=True, doplot=True):
"""
Parameters
----------
x, y : int
X and Y indices of `z`.
z : float
Values for given `x` and `y`.
outshape : tuple of int
Shape of 2D output array.
verbose : bool, optional
Print info to screen.... | 05558e413139a0ad71a4240e3f44c4bb9019c314 | 5,980 |
def _nms_boxes(detections, nms_threshold):
"""Apply the Non-Maximum Suppression (NMS) algorithm on the bounding
boxes with their confidence scores and return an array with the
indexes of the bounding boxes we want to keep.
# Args
detections: Nx7 numpy arrays of
[[x, y, w, h, ... | 9d3ad16396f1e94e4ac8efe1e73e8f06b529ff0f | 5,982 |
import types
def dht_get_key(data_key):
"""
Given a key (a hash of data), go fetch the data.
"""
dht_client = get_dht_client()
ret = dht_client.get(data_key)
if ret is not None:
if type(ret) == types.ListType:
ret = ret[0]
if type(ret) == types.DictType and ret.h... | 0c8680996e21b7dcc02cd4b7d81f3fa500b02076 | 5,983 |
def get_dataframe_from_table(table_name, con):
"""
put table into DataFrame
"""
df = pd.read_sql_table(table_name, con)
return df | cdf94277c2f4e3acdd22b87de7cd9d0fee63b24c | 5,984 |
from typing import List
from typing import Dict
import requests
def _find_links_in_headers(*, headers, target_headers: List[str]) -> Dict[str, Dict[str, str]]:
"""Return a dictionary { rel: { url: 'url', mime_type: 'mime_type' } } containing the target headers."""
found: Dict[str, Dict[str, str]] = {}
lin... | ee23c9c7ca2633d11ea33ac2695a46eca4188af5 | 5,985 |
import re
def calc_word_frequency(my_string, my_word):
"""Calculate the number of occurrences of a given word in a given string.
Args:
my_string (str): String to search
my_word (str): The word to search for
Returns:
int: The number of occurrences of the given word in the given st... | 15ff723dd2ff089fb12cccb38283f1f75e37079d | 5,986 |
def _make_warmstart_dict_env():
"""Warm-start VecNormalize by stepping through BitFlippingEnv"""
venv = DummyVecEnv([make_dict_env])
venv = VecNormalize(venv)
venv.reset()
venv.get_original_obs()
for _ in range(100):
actions = [venv.action_space.sample()]
venv.step(actions)
... | 67e0ee3e8440c24a08e306afbb9891dee64dd11d | 5,988 |
def record_attendance(lesson_id):
"""
Record attendance for a lesson.
"""
# Get the UserLessonAssociation for the current and
# the given lesson id. (So we can also display attendance etc.)
lesson = Lesson.query.filter(Lesson.lesson_id == lesson_id).first()
# Ensure the lesson id/associatio... | 237fb1df5eaf1f1b7d9555ca636971318f23c360 | 5,989 |
def ts_to_datestr(ts, fmt="%Y-%m-%d %H:%M"):
"""可读性"""
return ts_to_datetime(ts).strftime(fmt) | 29b180c0d569768b173afb960d9cb09e86519741 | 5,990 |
def so3_rotate(batch_data):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_data = np.zero... | 84c184c920833bf2037b0f4181e9f25bcf6fd5ce | 5,992 |
import hashlib
def intmd5(source: str, nbytes=4) -> int:
"""
Generate a predictive random integer of nbytes*8 bits based on a source string.
:param source:
seed string to generate random integer.
:param nbytes:
size of the integer.
"""
hashobj = hashlib.md5(source.encode())
retu... | c03eb99a67af00a4a081423ecca3a724111514e1 | 5,993 |
def trisolve(a, b, c, y, inplace=False):
"""
The tridiagonal matrix (Thomas) algorithm for solving tridiagonal systems
of equations:
a_{i}x_{i-1} + b_{i}x_{i} + c_{i}x_{i+1} = y_{i}
in matrix form:
Mx = y
TDMA is O(n), whereas standard Gaussian elimination is O(n^3).
Argument... | ead814b1025e8458f7e1eabeecf3eb89cb9edd5d | 5,994 |
def calc_mean_pred(df: pd.DataFrame):
"""
Make a prediction based on the average of the predictions of phones
in the same collection.
from https://www.kaggle.com/t88take/gsdc-phones-mean-prediction
"""
lerp_df = make_lerp_data(df=df)
add_lerp = pd.concat([df, lerp_df])
# each time step =... | a4f6cdb0d5efb72cd6b503a8eb3a0f4b13cee0bf | 5,995 |
def get_meals(v2_response, venue_id):
"""
Extract meals into old format from a DiningV2 JSON response
"""
result_data = v2_response["result_data"]
meals = []
day_parts = result_data["days"][0]["cafes"][venue_id]["dayparts"][0]
for meal in day_parts:
stations = []
for station... | 9d27d225a39248690529167f7ff18777a086bcc6 | 5,996 |
async def async_setup(hass, config_entry):
""" Disallow configuration via YAML """
return True | 759cc705a82a0f9ff9d4d43cb14d641d7e552aaa | 5,997 |
def blend(im1, im2, mask):
"""
Blends and shows the given images according to mask
:param im1: first image
:param im2: second image
:param mask: binary mask
:return: result blend
"""
res = []
for i in range(3):
res.append(pyramid_blending(im1[:, :, i], im2[:, :, i], mask, 7, ... | 4b4a635d1f44ced411b9dfe2037b0f42805f38b2 | 5,998 |
def parse(fileName):
"""
Pull the EXIf info from a photo and sanitize it so for sending as JSON
by converting values to strings.
"""
f = open(fileName, 'rb')
exif = exifread.process_file(f, details=False)
parsed = {}
for key, value in exif.iteritems():
parsed[key] = str(value)
... | 3f5aca5b38dd7f3b3a9defae1fc5f645e255a191 | 5,999 |
from typing import Optional
from typing import Callable
import requests
def make_request(
endpoint: str, method: str = "get", data: Optional[dict] = None, timeout: int = 15
) -> Response:
"""Makes a request to the given endpoint and maps the response
to a Response class"""
method = method.lower()
... | 8dd88583f61e5c42689461dd6d316297d910f197 | 6,001 |
import socket
def _is_rpc_timeout(e):
""" check whether an exception individual rpc timeout. """
# connection caused socket timeout is being re-raised as
# ThriftConnectionTimeoutError now
return isinstance(e, socket.timeout) | ec832bec086b59698eed12b18b7a37e5eb541329 | 6,002 |
def fake_quantize_with_min_max(inputs,
f_min,
f_max,
bit_width,
quant_zero=True):
"""The fake quantization operation kernel.
Args:
inputs: a tensor containing values to be quantized.
... | 2034dbe02d50ce0317dc4dbb6f2ed59137e671d2 | 6,003 |
def lorentzian(coordinates, center, fwhm):
"""
Unit integral Lorenzian function.
Parameters
----------
coordinates : array-like
Can be either a list of ndarrays, as a meshgrid coordinates list, or a
single ndarray for 1D computation
center : array-like
Center of the lorentzian. Should be the same sh... | 8631ef30f0fd50ac516f279cd130d6d9b099d953 | 6,004 |
def _to_gzip_base64(self, **kwargs):
""" Reads the file as text, then turns to gzip+base64"""
data = self.read_text(**kwargs)
return Base.b64_gzip_encode(data) | bb3e01bcac5e551d862629e79f4c54827ca3783c | 6,005 |
import traceback
def get_recipe_data(published=False, complete_data=False):
"""Return published or unpublished recipe data."""
try:
Changed = User.alias()
recipes = recipemodel.Recipe.select(
recipemodel.Recipe, storedmodel.Stored,
pw.fn.group_concat(tagmodel.Tag.tagnam... | 35afc8247912bd6814b5f4e76716f39d9f244e90 | 6,006 |
def html_anchor_navigation(base_dir, experiment_dir, modules):
"""Build header of an experiment with links to all modules used for rendering.
:param base_dir: parent folder in which to look for an experiment folders
:param experiment_dir: experiment folder
:param modules: list of all loaded modules
... | 1fea16c0aae2f73be713271de5f003e608cee7e9 | 6,007 |
import typing
def _to_int_and_fraction(d: Decimal) -> typing.Tuple[int, str]:
"""convert absolute decimal value into integer and decimal (<1)"""
t = d.as_tuple()
stringified = ''.join(map(str, t.digits))
fraction = ''
if t.exponent < 0:
int_, fraction = stringified[:t.exponent], stringifi... | d1f83df06ae42cdc3e6b7c0582397ee3a79ff99b | 6,009 |
import json
def json_to_obj(my_class_instance):
"""
Получает на вход JSON-представление,
выдает на выходе объект класса MyClass.
>>> a = MyClass('me', 'my_surname', True)
>>> json_dict = get_json(a)
>>> b = json_to_obj(json_dict)
<__main__.MyClass object at 0x7fd8e9634510>
"""
some... | 1f881e609f1c895173f4c27ebdaf413a336a4b8f | 6,010 |
def all_tags(path) -> {str: str}:
"""Method to return Exif tags"""
file = open(path, "rb")
tags = exifread.process_file(file, details=False)
return tags | 29132ad176ba68d7026ebb78d9fed6170833255e | 6,011 |
def static(request):
"""
Backport django.core.context_processors.static to Django 1.2.
"""
return {'STATIC_URL': djangoSettings.STATIC_URL} | cf74daed50e7e15f15fbe6592f36a523e388e11e | 6,012 |
def genBoard():
"""
Generates an empty board.
>>> genBoard()
["A", "B", "C", "D", "E", "F", "G", "H", "I"]
"""
# Empty board
empty = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
# Return it
return empty | c47e766a0c897d3a1c589a560288fb52969c04a3 | 6,013 |
def _partition_at_level(dendrogram, level) :
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest snapshot_affiliations, and the best is len(dendrogram) - 1.
The higher the level ... | b179127076c386480c31a18a0956eb30d5f4ef2a | 6,014 |
def generate_ab_data():
"""
Generate data for a second order reaction A + B -> P
d[A]/dt = -k[A][B]
d[B]/dt = -k[A][B]
d[P]/dt = k[A][B]
[P] = ([B]0 - [A]0 h(t)) / (1 - h(t)) where
h(t) = ([B]0 / [A]0) e^(kt ([B]0 - [A]0))
Data printed in a .csv file
"""
times = np.linspace(0... | d36521953129b5e002d3a3d2bcf929322c75470c | 6,016 |
import typing
def autocomplete(segment: str, line: str, parts: typing.List[str]):
"""
:param segment:
:param line:
:param parts:
:return:
"""
if parts[-1].startswith('-'):
return autocompletion.match_flags(
segment=segment,
value=parts[-1],
sho... | 8d929e96684d8d1c3ad492424821d27c4d1a2e66 | 6,017 |
def elast_tri3(coord, params):
"""Triangular element with 3 nodes
Parameters
----------
coord : ndarray
Coordinates for the nodes of the element (3, 2).
params : tuple
Material parameters in the following order:
young : float
Young modulus (>0).
poisson ... | 5a0381bb7961b811650cc57af7317737995dd866 | 6,018 |
import torch
def make_offgrid_patches_xcenter_xincrement(n_increments:int, n_centers:int, min_l:float, patch_dim:float, device):
"""
for each random point in the image and for each increments, make a square patch
return: I x C x P x P x 2
"""
patches_xcenter = make_offgrid_patches_xcenter(n_center... | dc7fe393e6bee691f9c6ae399c52668ef98372c4 | 6,019 |
def load_gazes_from_xml(filepath: str) -> pd.DataFrame:
"""loads data from the gaze XML file output by itrace.
Returns the responses as a pandas DataFrame
Parameters
----------
filepath : str
path to XML
Returns
-------
pd.DataFrame
Gazes contained in the xml file
... | b1fd17eace5ea253ce82617f5e8c9238a78d925a | 6,020 |
def axis_rotation(points, angle, inplace=False, deg=True, axis='z'):
"""Rotate points angle (in deg) about an axis."""
axis = axis.lower()
# Copy original array to if not inplace
if not inplace:
points = points.copy()
# Convert angle to radians
if deg:
angle *= np.pi / 180
... | dccb663a9d8d4f6551bde2d6d26868a181c3c0a7 | 6,021 |
async def unhandled_exception(request: Request, exc: UnhandledException):
"""Raises a custom TableKeyError."""
return JSONResponse(
status_code=400,
content={"message": "Something bad happened" f" Internal Error: {exc.message!r}"},
) | bff466190f5804def1416ee6221dccb3739c7dec | 6,022 |
def register_view(request):
"""Render HTTML page"""
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, "Account was cre... | c129a561c31c442ca091cfe38cb2f7a27f94a25d | 6,023 |
def luv2rgb(luv, *, channel_axis=-1):
"""Luv to RGB color space conversion.
Parameters
----------
luv : (..., 3, ...) array_like
The image in CIE Luv format. By default, the final dimension denotes
channels.
Returns
-------
out : (..., 3, ...) ndarray
The image in R... | bac8e7155f2249135158786d39c1f2d95af22fc8 | 6,024 |
def deposit_fetcher(record_uuid, data):
"""Fetch a deposit identifier.
:param record_uuid: Record UUID.
:param data: Record content.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains
data['_deposit']['id'] as pid_value.
"""
return FetchedPID(
provider=Depos... | c4505eff50473204c5615991f401a45cc53779a1 | 6,025 |
import time
def make_filename():
""""This functions creates a unique filename."""
unique_filename = time.strftime("%Y%m%d-%H%M%S")
#unique_filename = str(uuid.uuid1())
#unique_filename = str(uuid.uuid1().hex[0:7])
save_name = 'capture_ferhat_{}.png'.format(unique_filename)
return(save_name) | bf16b642884381d795148e045de2387d0acaf23d | 6,026 |
import re
def compareLists(sentenceList, majorCharacters):
"""
Compares the list of sentences with the character names and returns
sentences that include names.
"""
characterSentences = defaultdict(list)
for sentence in sentenceList:
for name in majorCharacters:
if re.searc... | 4b41da794ff936a3769fe67580b989e0de343ee7 | 6,027 |
import re
def is_live_site(url):
"""Ensure that the tool is not used on the production Isaac website.
Use of this tool or any part of it on Isaac Physics and related websites
is a violation of our terms of use: https://isaacphysics.org/terms
"""
if re.search("http(s)?://isaac(physics|chemis... | 407624a049e92740eb82753d941780a446b1facf | 6,028 |
def score_false(e, sel):
"""Return scores for internal-terminal nodes"""
return e*(~sel).sum() | 077cd38c6d1186e2d70fd8a93f44249b0cef2885 | 6,029 |
import logging
import numpy
def retrieveXS(filePath, evMin=None, evMax=None):
"""Open an ENDF file and return the scattering XS"""
logging.info('Retrieving scattering cross sections from file {}'
.format(filePath))
energies = []
crossSections = []
with open(filePath) as fp:
... | 388986facd75540983870f1f7e0a6f51b6034271 | 6,031 |
import string
def _parse_java_simple_date_format(fmt):
"""
Split a SimpleDateFormat into literal strings and format codes with counts.
Examples
--------
>>> _parse_java_simple_date_format("'Date:' EEEEE, MMM dd, ''yy")
['Date: ', ('E', 5), ', ', ('M', 3), ' ', ('d', 2), ", '", ('y', 2)]
... | 3fe42e4fc96ee96c665c3c240cb00756c8534c84 | 6,032 |
import logging
def rekey_by_sample(ht):
"""Re-key table by sample id to make subsequent ht.filter(ht.S == sample_id) steps 100x faster"""
ht = ht.key_by(ht.locus)
ht = ht.transmute(
ref=ht.alleles[0],
alt=ht.alleles[1],
het_or_hom_or_hemi=ht.samples.het_or_hom_or_hemi,
#GQ=ht.samples.GQ,
HL=ht.samples.H... | 3e879e6268017de31d432706dab9e672e85673aa | 6,033 |
import collections
def _sample_prior_fixed_model(formula_like, data=None,
a_tau=1.0, b_tau=1.0, nu_sq=1.0,
n_iter=2000,
generate_prior_predictive=False,
random_state=None):
"""Sample from prior ... | 1e57cd3f8812e28a8d178199d3dd9c6a23614dc0 | 6,034 |
from typing import Any
async def validate_input(
hass: core.HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
zeroconf_instance = await zeroconf.async_get_ins... | 5ececb6dfc84e232d413b2ada6c6076a75420b49 | 6,035 |
def closeWindow(plotterInstance=None):
"""Close the current or the input rendering window."""
if not plotterInstance:
plotterInstance = settings.plotter_instance
if not plotterInstance:
return
if plotterInstance.interactor:
plotterInstance.interactor.ExitCallback()
... | af3df7fa07069413c59f498529f4d21a9b88e9f4 | 6,036 |
def _format_stages_summary(stage_results):
"""
stage_results (list of (tuples of
(success:boolean, stage_name:string, status_msg:string)))
returns a string of a report, one line per stage.
Something like:
Stage: <stage x> :: SUCCESS
Stage: <stage y> :: FAILED
Stage: <s... | 2f5c757342e98ab258bdeaf7ffdc0c5d6d4668ca | 6,037 |
import json
def pack(envelope, pack_info):
"""Pack envelope into a byte buffer.
Parameters
----------
envelope : data structure
pack_info : packing information
Returns
-------
packet : bytes
"""
ptype = pack_info.ptype
packer = packers[ptype]
payload = packer.pack(en... | 5202e9eef7fc658157798d7f0d64820b1dfa3ac3 | 6,038 |
import tempfile
def tmpnam_s():
"""Implementation of POSIX tmpnam() in scalar context"""
ntf = tempfile.NamedTemporaryFile(delete=False)
result = ntf.name
ntf.close()
return result | a8c193a0e1ed6cd386dda9e0c084805cbed5f189 | 6,039 |
def timezone_lookup():
"""Force a timezone lookup right now"""
TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/"
"DateAndTime.prefPane/Contents/"
"Resources/TimeZone.prefPane")
TimeZonePref = TZPP.classNamed_('TimeZoneP... | a78a7f32f02e4f6d33b91bb68c1330d531b0208e | 6,040 |
def rollingCPM(dynNetSN:DynGraphSN,k=3):
"""
This method is based on Palla et al[1]. It first computes overlapping snapshot_communities in each snapshot based on the
clique percolation algorithm, and then match snapshot_communities in successive steps using a method based on the
union graph.
[1] P... | b4050544cd8a98346f436c75e5c3eeeb9a64c030 | 6,041 |
def penalty_eqn(s_m, Dt):
"""
Description:
Simple function for calculating the penalty for late submission of a project.
Args:
:in (1): maximum possible score
:in (2): difference between the date of deadline and the date of assignment of the project (in hours)
:out (1): rounded result of ... | 694a2b77c1612d7036c46768ee834043a1af3902 | 6,042 |
import re
def stop(name=None, id=None):
"""
Stop (terminate) the VM identified by the given id or name.
When both a name and id are provided, the id is ignored.
name:
Name of the defined VM.
id:
VM id.
CLI Example:
.. code-block:: bash
salt '*' vmctl.stop name=... | 3dbb2771f7407f3a28a9249551268b9ba23d906e | 6,043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.