content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_instantiate_document() -> None:
"""It does not raise an exception."""
try:
_ = FoafDocument()
except Exception:
pytest.fail("Unexpected Exception ..") | 5,290,200 |
def pen_gfield(nx=0, ny=0, off_x=OFF_X, off_y=OFF_Y):
"""
Move the pen above field (nx, ny) so we can begin writing a number in this field.
(off_x, off_y) is the relative offset between the color sensor and the pen (in motor angles).
"""
xmod = -round(PEN_GX_CORR * b.position / (RX * 9))
fy = n... | 5,290,201 |
def spellcheck(request):
"""
Spellcheck some POST data.
"""
jsondata = request.POST.get("data")
print "Spellcheck data: %s" % jsondata
if not jsondata:
return HttpResponseServerError(
"No data passed to 'spellcheck' function.")
data = json.loads(jsondata)
aspell =... | 5,290,202 |
def contains(value, lst):
""" (object, list of list of object) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
found = False # We have not yet found value in the list.
for i in... | 5,290,203 |
def populate_targets(index_of_prev, index_of_next):
"""
Update the prev/next time/temp variables using the index of the prev/next values in the schedule.
"""
global prev_temp_time
global prev_temp
global next_temp_time
global next_temp
prev_temp_time = parse_time_from_schedule(SCHEDULE[i... | 5,290,204 |
def filter_component_names(raw_npm_list):
"""Filter the raw NPM list to get list of proper component names."""
pattern = re.compile("^[0-9]+.")
components = []
for line in raw_npm_list.splitlines():
if pattern.match(line):
try:
i1 = line.index("[")
i2 ... | 5,290,205 |
def hide_property(properties, prop_name):
"""
Hide a property, if it exists and is not empty.
This is done by modifying the value of the property in the 'properties'
parameter.
Parameters:
properties(dict): Dict of properties (name/value). May be changed.
prop_name(string): Property na... | 5,290,206 |
def dispersion_2D(syst, args=None, lim=1.5*np.pi, num_points=200):
"""A simple plot of 2D band structure."""
if args is None:
args = []
momenta = np.linspace(-lim, lim, num_points)
energies = []
for kx in momenta:
for ky in momenta:
lattice_k = momentum_to_lattice([kx, ky... | 5,290,207 |
def dispImg(img):
"""
This does the min-max scaling the images to 0 and 1
"""
try:
h, w, d = img.shape
img_tmp = (img - np.min(img)) / (np.max(img) - np.min(img))
plt.matshow(img_tmp)
plt.show(block=False)
except ValueError:
try:
h, w = img.shape
... | 5,290,208 |
def get_all_matches(sub, twod, match_constraints, write_all=False):
"""
Returns all matches as a list of pymatgen structure objects
Writes all of them as POSCAR files in a directory 'all_interface_poscars'
"""
# variables from the keys
max_area = match_constraints['max_area']
max_mismatch = ... | 5,290,209 |
def PerteVie(vals,elements):
"""Subtract amount from penalty"""
amt = int(int(elements[0])/120.0*100)
vals["postcode"] = "penalty -%d"%(amt,) | 5,290,210 |
def test_cfreds_macwd_properties():
"""
These were drawn from a CFReDS sample Mac disk image.
"""
dobj = Objects.DFXMLObject(version="1.2.0")
pobj = Objects.PartitionObject()
dobj.append(pobj)
pobj.ptype_str = "Apple_Boot"
pobj.partition_index = 8
# Do file I/O round trip.
(tmp... | 5,290,211 |
def download_metadata_file_for_1minute_data(metadatafile: str) -> BytesIO:
""" A function that simply opens a filepath with help of the urllib library and then writes the content to a BytesIO
object and returns this object. For this case as it opens lots of requests (there are approx 1000 different files
to... | 5,290,212 |
def AddXsd(basePath):
"""Use CodeSynthesis XSD from a non-standard location."""
CheckPathExists(basePath, 'XSD')
# Remove existing include path
RemoveFromPath(conf.other_includepaths, 'libxsd')
# Add new location
conf.other_includepaths.append(os.path.join(basePath, 'libxsd'))
conf.tools['xs... | 5,290,213 |
def check_format_input_obj(
inp,
allow: str,
recursive=True,
typechecks=False,
) -> list:
"""
Returns a flat list of all wanted objects in input.
Parameters
----------
input: can be
- objects
allow: str
Specify which object types are wanted, separate by +,
... | 5,290,214 |
def sleeper(sleep_time):
""" Function to execute in parallel.
"""
sleep(sleep_time)
return {"sleep_time": sleep_time} | 5,290,215 |
def get_bias(config, logtable):
"""Get bias image.
Args:
config (:class:`configparser.ConfigParser`): Config object.
logtable (:class:`astropy.table.Table`): Table of Observing log.
Returns:
tuple: A tuple containing:
* **bias** (:class:`numpy.ndarray`) – Output bias i... | 5,290,216 |
def get_login_server_suffix(cli_ctx):
"""Get the Azure Container Registry login server suffix in the current cloud."""
try:
return cli_ctx.cloud.suffixes.acr_login_server_endpoint
except CloudSuffixNotSetException as e:
logger.debug("Could not get login server endpoint suffix. Exception: %s"... | 5,290,217 |
def construct_sent(word, table):
"""Prints a random sentence starting with word, sampling from
table.
>>> table = {'Wow': ['!'], 'Sentences': ['are'], 'are': ['cool'], 'cool': ['.']}
>>> construct_sent('Wow', table)
'Wow!'
>>> construct_sent('Sentences', table)
'Sentences are cool.'
"""... | 5,290,218 |
def test_partly_solar():
"""
Solar thermal is present would provide enough heat.
However, only half of it can be used because of the temperature level
right in the middle between forward and backward flow temperatures.
"""
heat_demand = 1
st_generation = 1
st_generation = {"ST_20": 3 * ... | 5,290,219 |
def sequence_proto_to_midi_file(sequence, output_file,
is_drum=False,
drop_events_n_seconds_after_last_note=None):
"""Convert tensorflow.magenta.NoteSequence proto to a MIDI file on disk.
Time is stored in the NoteSequence in absolute values (seco... | 5,290,220 |
def writebinary(filename, infile):
"""Given a filename and a string, write the file in binary mode. """
filehandle = open(filename, 'wb')
filehandle.write(infile)
filehandle.close() | 5,290,221 |
def process_sources(source_list):
"""
We now want to process the dictionary and
output a list of objects - news_results.
We process results will transform our dictionary into a list of objects.
"""
news_results = []
for source in source_list:
id = source.get('id')
print(id)
... | 5,290,222 |
def _preprocess(expr, func=None, hint='_Integral'):
"""Prepare expr for solving by making sure that differentiation
is done so that only func remains in unevaluated derivatives and
(if hint doesn't end with _Integral) that doit is applied to all
other derivatives. If hint is None, don't do any different... | 5,290,223 |
def read_lisp_filter(path):
"""Reads a lisp filter from a file.
For example:
(> (/ (+ (- (field "00000") 4.4)
(field 23)
(* 2 (field "Class") (field "00004")))
3)
5.5)
"""
return read_description(path) | 5,290,224 |
def team_games(results, team='Northeastern'):
"""
Collect all games by given team.
Parameters
----------
results : TYPE
DESCRIPTION.
team : TYPE, optional
DESCRIPTION. The default is 'Northeastern'.
Returns
-------
teamGames : TYPE
DESCRIPTION.
"""
... | 5,290,225 |
def sparse_rec_pogm(gradient_op, linear_op, prox_op, cost_op=None,
max_nb_of_iter=300, metric_call_period=5, sigma_bar=0.96,
metrics={}, verbose=0):
"""
Perform sparse reconstruction using the POGM algorithm.
Parameters
----------
gradient_op: instance of cla... | 5,290,226 |
def get_dataset_phase(prefixf):
"""
Return the execution time dataset
from a folder "prefixf" and return the
execution time for the phases
Also filter out the zero values.
"""
#start_time = timeit.default_timer()
tmp = pd.read_csv(prefixf+"/dataset_ph1.cs... | 5,290,227 |
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
): # pylint: disable=unused-argument
"""Setup sensor platform."""
async_add_entities([ynabSensor(hass, discovery_info)], True) | 5,290,228 |
def autocomplete_switches(
service_switches,
specified_tech_enduse_by,
s_tech_by_p,
enduses,
sectors,
crit_all_the_same=True,
regions=False,
f_diffusion=False,
techs_affected_spatial_f=False,
service_switches_from_capacity=[]
):
"""... | 5,290,229 |
def UnbiasPmf(pmf, label=''):
"""Returns the Pmf with oversampling proportional to 1/value.
Args:
pmf: Pmf object.
label: string label for the new Pmf.
Returns:
Pmf object
"""
new_pmf = pmf.Copy(label=label)
for x, p in pmf.Items():
new_pmf.Mult(x, 1.0/x)
... | 5,290,230 |
def constant_init(value=0):
""" Constant Initializer
The resulting tensor is populated with values of type dtype, as specified by arguments value
following the desired shape.
The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length
of the l... | 5,290,231 |
def ConfusionMatrix(ftrue, fpred, nf):
"""
CONFUSION MATRIX
Computes the confusion matrix of a discrete classification.
Written by Dario Grana (August 2020)
Parameters
----------
ftrue : array_like
true model
fpred : array_like
predicted model
nf : int
nu... | 5,290,232 |
def drop_na_1d(df, axis=0, how='all'):
"""
:param df:
:param axis: int;
:param how:
:return:
"""
if axis == 0:
axis_name = 'column'
else:
axis_name = 'row'
if how == 'any':
nas = df.isnull().any(axis=axis)
elif how == 'all':
nas = df.isnull().al... | 5,290,233 |
def solve_1(x):
"""Returns the checksum (sum of the difference between the biggest and smallest number in each row)"""
return sum(map(get_diff, format_input(x))) | 5,290,234 |
def resnet34(pretrained=False, filter_size=1, pool_only=True, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
if pretrain... | 5,290,235 |
def selvita_sukupuoli(hetu):
"""Selvittää järjestynumeron perusteella sukupuolen: parillinen -> nainen, pariton -> mies
Args:
hetu (string): Henkilötunnus
Returns:
string: Nainen tai mies
"""
# Otetaan hetusta järjestysnumero-osa
jarjestysnumero_str = hetu[7:10]
# Muuteta... | 5,290,236 |
def search_unknown(filename, dictionary):
""" Searches the words that are misspelled/not in the dictionary"""
numbers = re.findall('[\d]+', filename)
words = filename.lower().replace('?', ' ').replace('!',' ').replace('.',' ').replace('-',' ').replace(':',' ').replace(';',' ').replace(',',' ').replace('(',' ').repla... | 5,290,237 |
def cpp_bindata_subtype_type_name(name):
# type: (unicode) -> unicode
"""Return the C++ type name for a bindata subtype."""
assert is_valid_bindata_subtype(name)
return _BINDATA_SUBTYPE[name]['bindata_enum'] | 5,290,238 |
def common_error(data: str):
"""
捕获异常时打印详细错误信息,用于 except 后
:param data:
:return:
"""
info = sys.exc_info()
print(f"{data}: {info[0]}, {info[1]}") | 5,290,239 |
def avg_spectra(im):
"""
avg_spectra(im)
Returns numpy.ndarray of mean spectrum, averaged over the image pixels
Parameters
----------
im : image passed as numpy array
Returns
-------
out : ndarray
An array object satisfying the specified requirements.
"""
... | 5,290,240 |
def handler(event, context):
""" CloudFormation Custom Resource Lambda Handler
"""
import cfnresponse
logger.info('event: {}'.format(cfnresponse.json_dump_format(event)))
request_type = event.get('RequestType')
resource_properties = event.get('ResourceProperties')
bot_name= resource_propert... | 5,290,241 |
def moving_average(x, n, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
x = np.asarray(x)
if type == 'simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
# print ("Weigh... | 5,290,242 |
def changeContagion(G, A, i):
"""
change statistic for Contagion (partner attribute)
*--*
"""
delta = 0
for u in G.neighbourIterator(i):
if A[u] == 1:
delta += 1
return delta | 5,290,243 |
def collect(config, pconn):
"""
All the heavy lifting done here
"""
branch_info = get_branch_info(config)
pc = InsightsUploadConf(config)
output = None
collection_rules = pc.get_conf_file()
rm_conf = pc.get_rm_conf()
blacklist_report = pc.create_report()
if rm_conf:
logg... | 5,290,244 |
def _check_verbosity(verbosity: str) -> str:
"""
Check function used by verbosity setter as a callback.
:param verbosity: verbosity level to apply to resto_client.
:raises ValueError: when verbosity has a wrong value
:returns: the uppercase verbosity level
"""
if verbosity is not None:
... | 5,290,245 |
def local():
"""Run all local tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(HomelandTestCase, 'test_local'))
return suite | 5,290,246 |
def walk_packages(packages: List[str], verbose: bool = False) -> Iterator[str]:
"""Iterates through all packages and sub-packages in the given list.
This uses runtime imports to find both Python and C modules. For Python packages
we simply pass the __path__ attribute to pkgutil.walk_packages() to get the c... | 5,290,247 |
def test_delete_files_and_folders(store_id, tmpdir):
"""Test deleting folders in the file store."""
# -- Setup ----------------------------------------------------------------
# Initialize the file store and create files in the file store base
# direcory.
fs = create_store(store_id, str(tmpdir))
... | 5,290,248 |
def test_input_task():
"""Test basic functionalities of InputTask"""
task = InputTask(value=31)
assert task.execute() == 31
assert task.execute(value=42) == 42
task = InputTask()
assert task.execute() is None
assert task.execute(value=42) == 42 | 5,290,249 |
def cycle_check(classes):
"""
Checks for cycle in clazzes, which is a list of (class, superclass)
Based on union find algorithm
"""
sc = {}
for clazz, superclass in classes:
class_set = sc.get(clazz, clazz)
superclass_set = sc.get(superclass, superclass)
if class_set !=... | 5,290,250 |
def test_matrix_message_retry(
local_matrix_servers,
retry_interval_initial,
retry_interval_max,
retries_before_backoff,
):
"""Test the retry mechanism implemented into the matrix client.
The test creates a transport and sends a message. The receiver
doesn't respond in time. The retrier shou... | 5,290,251 |
def setcharheight(height):
"""
Set the current character height.
**Parameters:**
`height` :
Text height value
`setcharheight` defines the height of subsequent text output primitives. Text height
is defined as a percentage of the default window. GR uses the default text height of
0... | 5,290,252 |
def bivariate_histogram(xsample, ysample, reference_value_mean=None,\
reference_value_covariance=None, bins=None, matplotlib_function='imshow',\
xlabel='', ylabel='', title='', fontsize=28, ax=None, show=False,\
contour_confidence_levels=0.95, reference_color='r', reference_alpha=1,\
minima=None, maxima... | 5,290,253 |
def arrayToVec(array, arrType=carmcmcLib.vecD):
"""
Convert the input numpy array to a python wrapper of a C++ std::vector<double> object.
"""
vec = arrType()
vec.extend(array)
return vec | 5,290,254 |
def moma(model, reference=None, cache=None, reactions=None, *args, **kwargs):
"""
Minimization of Metabolic Adjustment[1]
Parameters
----------
model: cobra.Model
reference: FluxDistributionResult, dict
cache: ProblemCache
reactions: list
Returns
-------
FluxDistributionRes... | 5,290,255 |
def api_v2_url(path_str,
params=None,
base_route=settings.API_BASE_URL,
**kwargs):
"""
Convenience function for APIv2 usage: Concatenates parts of the absolute API url based on arguments provided
For example: given path_str = '/nodes/abcd3/contributors/' and par... | 5,290,256 |
def RunWebkitLayoutTests(options):
"""Run layout tests on an actual device."""
buildbot_report.PrintNamedStep('webkit_tests')
cmd_args = [
'--no-show-results',
'--no-new-test-results',
'--full-results-html',
'--clobber-old-results',
'--exit-after-n-failures', '5000',
... | 5,290,257 |
def test_get_equipment_detail(api_client, detail_url, equipment, equipment_alias):
"""
Tests that equipment detail endpoint returns equipment data in correct form.
"""
response = api_client.get(detail_url)
_check_keys_and_values(response.data) | 5,290,258 |
def treeify(body):
""" GETS FLAT ARRAY IN JSON""" | 5,290,259 |
def serialize_timingsession(session_pk, pk_offset=0):
"""Serialize all data associated with a timing session into JSON."""
session = TimingSession.objects.get(pk=session_pk)
data_to_dump = [
[session],
[session.coach],
[session.coach.user],
Split.objects.filter(timingsession=... | 5,290,260 |
def send_via_mail_to(request):
"""
send email to list of freinds
:param request:
in the square represented by :
west < longitude < east
north < latitude < south
"""
idAlert = int(request.POST['id'])
emails = request.POST['list']
text = request.POST['text']
lis... | 5,290,261 |
def getdata():
"""Returns a numpy array containing the most recently written EDA spectrum.
Return None,None if the most recent file is older than MAXAGE seconds.
NOTE - this will only work when run on 'bigdas', where live spectrum data is written to /tmp every second.
"""
if not BIGDAS:
... | 5,290,262 |
def get_tables_from_url(url, url_to_html='requests'):
"""Get's a list of pandas dataframes from tables scraped from a url.
Note that this will only work with static pages. If the html needs to be rendered dynamically,
you'll have to get your needed html otherwise (like with selenium).
>>> url = 'https:... | 5,290,263 |
def hamming_neighbors(i, bits, distance):
"""Yield numbers with given Hamming distance to i."""
if distance == 0:
yield i
else:
mask = int(distance * '1', 2)
while mask < 1 << bits:
yield i ^ mask
mask = lex_next_bits(mask) | 5,290,264 |
def saveChemkinFile(path, species, reactions, verbose = True, checkForDuplicates=True):
"""
Save a Chemkin input file to `path` on disk containing the provided lists
of `species` and `reactions`.
If checkForDuplicates is False then we don't check for unlabeled duplicate reactions,
thus saving time (... | 5,290,265 |
def matrix_split(interaction_dataset, user_test_ratio=0.2, item_test_ratio=0.2, min_user_interactions=0,
seed=0, max_concurrent_threads=4, **kwds):
"""Dataset split method that uses a matrix split strategy. More specifically, item_test_ratio items from
user_test_ratio users are sampled out of t... | 5,290,266 |
def Loadexc(casefile_dyn):
""" Loads exciter data.
@param casefile_dyn: m-file or struct with dynamic data
@return: exciter parameter matrix
@see: U{http://www.esat.kuleuven.be/electa/teaching/matdyn/}
"""
# Load data
if isinstance(casefile_dyn, dict):
exc = casefile_dyn["exc"]
... | 5,290,267 |
def _num_requests_needed(num_repos, factor=2, wiggle_room=100):
"""
Helper function to estimate the minimum number of API requests needed
"""
return num_repos * factor + wiggle_room | 5,290,268 |
def linebreakshtml(value, autoescape=True):
"""
Replaces double line breaks in HTML to a paragraph break (``</p>``).
This tag ignores single line breaks.
"""
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(force_text(value))
if autoescape:
value... | 5,290,269 |
def season(date, hemisphere, isleapyear):
"""
date is a datetime object
hemisphere is either 'north' or 'south', dependent on long/lat.
https://stackoverflow.com/questions/16139306/determine-season-given-timestamp-in-python-using-datetime
"""
if isleapyear:
dd = date.day + 1
... | 5,290,270 |
def test_get_read_only_client(mock_session, mock_client):
"""It should correctly call the Uber Session and pass it to the Client."""
core.get_read_only_client('APIKEY123')
mock_session.assert_called_once_with(server_token='APIKEY123')
mock_client.assert_called_once_with(mock_session()) | 5,290,271 |
def run_command_in_dir(cmd: list, directory: str):
""" Run a command in a specific dir
Args:
cmd (list): Command list to run
dir (str): Directory
"""
p = subprocess.Popen(cmd, cwd=directory)
p.wait() | 5,290,272 |
def find_files(base_path: str, annotation_path: str or None = None) -> Generator[str, Annotation, None]:
"""Get each file and its proper annotation object.
Parameters
----------
base_path : srt
Base path of input files.
annotation_path : str or None
Path of annotation file.
Yie... | 5,290,273 |
def stanford2tt(sentence):
"""Given a Sentence object, return TreeTagger-style
tuples (word, tag, lemma).
"""
for idx in sorted(sentence.word):
word = sentence.word.get(idx, "")
if word.startswith("<"):
tag, lemma = "XML", word
else:
tag = sentence.tag.... | 5,290,274 |
def request_course_creator(request):
"""
User has requested course creation access.
"""
user_requested_access(request.user)
return render(request) | 5,290,275 |
def bazel_groovy_test(name=None, test_class=None, size="small", deps=[], srcs=[], **kwargs):
"""A wrapper around groovy test to use the Bazel test runner."""
test_class = "build.bazel.ci." + name if test_class == None else test_class
groovy_library(
name = name + "-lib",
deps = deps,
... | 5,290,276 |
def cleanup_sessions():
"""
This function which performs the task of periodically clearing expired sessions.
Sessions are cleared by running django's built-in command: ./manage.py clearsession.
The age of the session is set in the SESSION_COOKIE_AGE parameter of the project's settings.
This does not... | 5,290,277 |
def _generate_monthly_price_materialized_view_sql():
"""
Generate the SQL used to generate the materialized view used by the last point view
:return:
"""
return """
CREATE MATERIALIZED VIEW instancedata_monthly_price_mv
ENGINE = SummingMergeTree
PARTITION BY crawlMonth
... | 5,290,278 |
def number_constructors():
"""A decorator for parametrized tests that test particular number operations.
"""
return pytest.mark.parametrize(
"newobj",
[
lambda: weakget(0),
lambda: pep505(0),
lambda: _weakget__nothing, # a singleton
],
ids... | 5,290,279 |
def test_instance_mult():
""" Initial tests of instance-array-generation by multiplication """
Child = h.Module(name="Child")
Parent = h.Module(name="Parent")
# Create an array via multiplication
Parent.child = Child() * 5 # Lotta kids here
# Check that the array is created correctly
ass... | 5,290,280 |
def get_subnetwork_output(project: Optional[pulumi.Input[Optional[str]]] = None,
region: Optional[pulumi.Input[str]] = None,
subnetwork: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetSubn... | 5,290,281 |
def approve_paper(request):
"""API approve_paper"""
if not request.user.is_authenticated:
return JsonResponse({'status': 'false'}, status=401)
if request.method == 'POST':
id = request.POST['id']
comment = request.POST['comment']
paper = get_object_or_404(Paper, pk=id)
... | 5,290,282 |
def dopamine_eval(runner, patient0, seed=100):
"""Evaluate an agent."""
base_env = runner._environment.environment # pylint: disable=protected-access
initial_health_state = np.zeros_like(
base_env.initial_params.initial_health_state)
initial_health_state[patient0] = 1
base_env.set_initial_health_state... | 5,290,283 |
def _convert_dconstr(model: BDF, dconstr: DCONSTR, pressure_scale: float) -> None:
"""helper for ``_convert_optimization``"""
otype = dconstr.type
if otype == 'DCONSTR':
dresp = dconstr.dresp_id_ref
if dresp.type == 'DRESP1':
#property_type = dresp.ptype
response_type... | 5,290,284 |
def merge(
left: pandas.core.frame.DataFrame,
right: pandas.core.frame.DataFrame,
how: Literal["outer"],
left_index: bool,
right_index: bool,
suffixes: Tuple[Literal["1"], Literal["2"]],
):
"""
usage.dask: 1
"""
... | 5,290,285 |
def pad_data(data_list, fill=0):
"""
Pad tensors with fill-value such that list of variable shaped tensors can be stacked
"""
n_samples = len(data_list)
#first determine longest time series:
lengths = [x.shape[0] for x in data_list]
max_len = max(lengths)
output = fill*torch.ones((n... | 5,290,286 |
def market(request):
""" Consulta a API procurando por informações sobre o mercado """
conn.request("GET", "/market/v2/get-summary?region=BR", headers=headers)
res = conn.getresponse()
data = res.read()
summary = json.loads(data.decode("utf-8"))['marketSummaryAndSparkResponse']
return render(req... | 5,290,287 |
def setup_invalid_yaml(tmpdir):
"""Returns a list containing three Vector instances"""
test_config_data = """
test: 1
test2:
1
"""
default_dict = {'test': 'testing', 'test2': 'still testing'}
test_cfg = tmpdir.mkdir("sub").join('test_config.yml')
test_cfg.write(test_config_data)
... | 5,290,288 |
def fuse_features(features1, features2, frame_batch_size=64, device='cuda'):
"""feature fusion"""
video_length = features1.shape[0]
frame_start = 0
frame_end = frame_start + frame_batch_size
features = np.empty(shape=[0, 4096], dtype=np.float32)
if video_length <= frame_batch_size:
inde... | 5,290,289 |
def preorder(head):
"""Reads the file in a preorder format
precondition: the head of the file
postcondition: None"""
if head == None:
return
print(head.data) # if head is not empty then print out its data recursively
preorder(head.left) ... | 5,290,290 |
def raHMS2deg(angle):
"""
EXAMPLE: Angle("10:42:44",unit=u.hourangle).deg
"""
return astropy.coordinates.Angle(angle,unit=u.hourangle).deg | 5,290,291 |
def generate(images, captions=dict(), outputdir='.', no_cache=False,
stage_width=1080, stage_height=680,
width=1200, height=800, thumbheight=50,
disable_keyboard_nav=0, image_margin=0,
toggleinfo=True, thumbnails=True,
exif_class='isobar', ... | 5,290,292 |
def rel(*x):
""""Simple path helper"""
abspath = os.path.abspath(main_file_location)
BASE_DIR = os.path.dirname(abspath)
return os.path.join(BASE_DIR, *x) | 5,290,293 |
def same_padding_for_kernel(shape, corr, strides_up=None):
"""Determine correct amount of padding for `same` convolution.
To implement `'same'` convolutions, we first pad the image, and then perform a
`'valid'` convolution or correlation. Given the kernel shape, this function
determines the correct amount of p... | 5,290,294 |
def dedeidentify(text):
"""
MIMIC-specific
:param text: The text to de-de-identify
:return:
"""
return re.sub(r"\[\*\*.*\*\*\]", xxxx, text).lower() | 5,290,295 |
def export_project_to_zip(zip_name: Union[str, Path], pipeline: Pipeline, train_data: InputData, test_data: InputData,
opt_history: Optional[OptHistory] = None, log_file_name: str = 'log.txt'):
"""
Convert pipeline to JSON, data to csv, compress them to zip
archive and save to 'DEF... | 5,290,296 |
def embed_net_siam1():
"""
This is a siamese type network to compare two patches.
"""
data1 = mx.sym.Variable("data1")
data2 = mx.sym.Variable("data2")
conv_weight = []
conv_bias = []
for i in range(3):
conv_weight.append(mx.sym.Variable('conv' + str(i) + '_weight'))
... | 5,290,297 |
def visualize(cfg):
"""
Train a video model for many epochs on train set and evaluate it on val set.
Args:
cfg (CfgNode): configs. Details can be found in
slowfast/config/defaults.py
"""
# Setup logging format.
logging.setup_logging(cfg)
# Print config.
logger.info(... | 5,290,298 |
def traced_graphql_wrapped(
func,
args,
kwargs,
span_kwargs=None,
span_callback=None,
ignore_exceptions=(),
):
"""
Wrapper for graphql.graphql function.
"""
# allow schemas their own tracer with fall-back to the global
schema = args[0]
tracer = getattr(schema, 'datadog_tr... | 5,290,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.