content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def preresnet164bn_svhn(classes=10, **kwargs):
"""
PreResNet-164(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default Fal... | 49,300 |
def compute_hash_info(fd, unit_size=None):
"""Get MediaFireHashInfo structure from the fd, unit_size
fd -- file descriptor - expects exclusive access because of seeking
unit_size -- size of a single unit
Returns MediaFireHashInfo:
hi.file -- sha256 of the whole file
hi.units -- list of sha256 ... | 49,301 |
def deploy_signed_application_that_should_fail(request_handler, runtimes, name, application_path, retries=20):
"""
Deploys app associated w/ deployer and then tries to verify its
presence in registry (for all runtimes).
"""
from calvin.utilities.security import Security
delay = 0.1
retry = 0... | 49,302 |
def main():
"""Sample encryption decryption."""
in_str = 'This is only a test.'
in_str = b64encode(in_str.encode()).decode()
in_str = convert_string(in_str, 'e')
print(f'>> [{in_str}] <<')
out_str = r"Cm^WL6,WL6,:NdkJFm1yKmC\KH+ "
out_str = convert_string(out_str, 'd')
out_str = b64decod... | 49,303 |
def value_map_distribution(value_map: dict, bounds: List[float] = None):
"""Percent of values that fall in ranges.
Args:
value_map: dict, value map
bound: list of float, boundaries to count values within
Returns:
dist: dict, distribution values
"""
i... | 49,304 |
def expand_basic(state):
"""
Simple function which returns child states by appending an available move to
current state.
"""
assert(len(state) < 9)
# Calculte set difference to get remaining moves.
n = tuple(set(range(9)) - set(state))
# Create tuple of available new states and return... | 49,305 |
def schedule_conv2d_winograd_nnpack_weight_transform(attrs, outs, target):
"""Schedule conv2d_winograd_nnpack_weight_transform"""
with target:
return topi.generic.schedule_conv2d_winograd_nnpack_weight_transform(outs) | 49,306 |
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
... | 49,307 |
def cli(qeq_code):
"""Run qeq calculation on HKUST-1
"""
run_qeq_hkust1(qeq_code=qeq_code) | 49,308 |
def get_best_files(folder, filters):
"""
Compare all files in a folder that differ only by tags (and extension) and return only the best one according to their tags.
If filters is None, return all files.
folder: folder containing the files to check
filters: list of filters in order of import... | 49,309 |
def query_normalised_list(x: str or None,
ref: List[NormalisedName]) -> str:
"""
Internal method for querying a channel/marker against a reference list of
NormalisedName's
Parameters
----------
x: str or None
channel/marker to query
ref: list
list o... | 49,310 |
def help_me():
"""Opens a help, using systems default text viewer."""
web.open('dismal_help.txt')
entry_box.focus() | 49,311 |
def test_write_run(tmpdir):
""" write a TREC searcher file """
fn = tmpdir / "searcher"
run_dict = {"q1": {"d1": 1.1, "d2": 1.0}, "q2": {"d5": 9.0}}
Searcher.write_trec_run(run_dict, fn)
run = Searcher.load_trec_run(fn)
assert sorted(run.items()) == sorted(run_dict.items()) | 49,312 |
def get_reachable_observed_variables_for_inferred_variables(model, observed=set()):
"""
After performing inference on a BayesianModel, get the labels of observed variables
("reachable observed variables") that influenced the beliefs of variables inferred
to be in a definite state.
Args
mode... | 49,313 |
def main():
"""
This program will use highlight_fire() function to find out
the fire areas and make remaining areas turn into grey to
highlight those fires
"""
original_fire = SimpleImage('images/greenland-fire.png')
original_fire.show()
highlighted_fire = highlight_fires('images/greenla... | 49,314 |
def load_bias(dataset_name, filtered=False) -> Dict[str, np.ndarray]:
"""Loads the output of our bias-only model
Note that since this produces per-token output, it is only valid on data with the
same tokenization as our annotated data.
"""
if filtered:
bias_ids = SQUAD_FILTERED_BIAS_FILE_IDS
output_d... | 49,315 |
def isbuildin(name: str) -> bool:
"""[summary]
Checks if name is a keyword or build-in function
[description]
Arguments:
name {str} -- name to be checked
Returns:
bool -- true if it is a build-in
"""
blacklist = ["abs", "delattr", "hash", "memoryview", "set", "all", "dict"... | 49,316 |
def find_dip(pulls):
"""Find the longest sequence of significant observations in the data"""
significant = pulls > 3.
if np.sum(significant) == 0:
return 0, 0
# Find indices of start and end of each significant sequence
changes = np.diff(np.hstack(([False], significant, [False])))
sign... | 49,317 |
def clip_weights(model, weight_constraint):
"""
Clip weights of a keras model to be bounded by given constraints.
Parameters
----------
model: keras model object
model for which weights need to be clipped
weight_constraint:
Returns
-------
model: keras model object
... | 49,318 |
async def test_adam_climate_entity_climate_changes(
hass: HomeAssistant, mock_smile_adam: MagicMock, init_integration: MockConfigEntry
) -> None:
"""Test handling of user requests in adam climate device environment."""
await hass.services.async_call(
"climate",
"set_temperature",
{"e... | 49,319 |
def scatter_wrapper(
self, func, *args,
s=None, size=None, markersize=None,
c=None, color=None, markercolor=None,
smin=None, smax=None,
cmap=None, cmap_kw=None, vmin=None, vmax=None, norm=None, norm_kw=None,
lw=None, linewidth=None, linewidths=None,
markeredgewidth=None, markeredgewidths=Non... | 49,320 |
def its_nexus_target_is_faulted():
"""its nexus target is faulted."""
# Stop remote io-engine instance, which should fault the volume nexus child
# By Stopping instead of killing, the control plane should see the node is down due to the
# DeRegister event.
Docker.stop_container(IO_ENGINE_2)
chec... | 49,321 |
def _coerce_loc_index(divisions, o):
"""Transform values to be comparable against divisions
This is particularly valuable to use with pandas datetimes
"""
if divisions and isinstance(divisions[0], datetime):
return pd.Timestamp(o)
if divisions and isinstance(divisions[0], np.datetime64):
... | 49,322 |
def triplet_loss(anchor_vector, positive_vector, negative_vector, metric='cosine_dist', margin=0.009):
"""Computes the triplet loss with semi-hard negative mining.
The loss encourages the positive distances (between a pair of embeddings with
the same labels) to be smaller than the minimum negative distance ... | 49,323 |
def python_environment(
base_dir=os.path.expanduser("~/.virtualenvs"), overwrite=False, dir_name=None
):
"""Build Python virtualenv for the application"""
path_to_requirements = os.path.join(BASE_DIR, "requirements.txt")
if dir_name is None:
# This is memory inefficient. Don't put in a 5G requ... | 49,324 |
def cleanup(items2delete):
"""
Cleans directories of all files in the input list
Args:
items2delete (str list): A list of files to remove.
"""
if isinstance(items2delete, list):
for del_item in items2delete:
if os.path.isfile(del_item):
os.remove(del_... | 49,325 |
def parse_resource(resource):
"""解析资源地址和下载资源"""
post_data = {'callCount': '1', 'scriptSessionId': '${scriptSessionId}190',
'httpSessionId': '5531d06316b34b9486a6891710115ebc', 'c0-scriptName': 'CourseBean',
'c0-methodName': 'getLessonUnitLearnVo', 'c0-id': '0', 'c0-param0': 'n... | 49,326 |
def test_jupyter_notebooks(path):
""" run the jupyter notebooks """
if os.path.basename(path).startswith('_'):
pytest.skip('skip examples starting with an underscore')
# adjust python environment
my_env = os.environ.copy()
my_env["PYTHONPATH"] = str(PACKAGE_PATH) + ":" + my_env["PAT... | 49,327 |
def get_file_hash(filepath: str, blocksize: int = 2**20) -> str:
"""Return the hash of the given file, with a default blocksize of 1MiB."""
_hash = hashlib.md5()
if not isfile(filepath):
return _hash
with open(filepath, "rb") as f:
while True:
buffer = f.read(blocksize)
... | 49,328 |
async def test_form_reauth_websocket_cannot_connect(hass, remotews: Mock):
"""Test reauthenticate websocket when we cannot connect on the first attempt."""
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_WS_ENTRY)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAI... | 49,329 |
def version():
"""
Print the version number(s) and exit.
"""
print(VERS)
exit(0) | 49,330 |
def AddUdpRelatedArgs(parser, request_and_response_required=True):
"""Adds parser arguments related to UDP."""
_AddPortRelatedCreationArgs(
parser, use_serving_port=False, port_type='UDP', default_port=None)
parser.add_argument(
'--request',
required=request_and_response_required,
help="... | 49,331 |
def get_files_for_instrument(instrument, multitrack_list=None):
"""Get all (stem) files for a particular instrument from the dataset.
Parameters
----------
instrument : str
Instrument files to extract.
multitrack_list : list of MultiTrack objects or None, default=None
List of MultiT... | 49,332 |
def _load_cmonary_lib():
"""Loads the cmonary CDLL library (from the directory containing this module)."""
global cmonary
thismodule = __file__
abspath = os.path.abspath(thismodule)
moduledir = list(os.path.split(abspath))[:-1]
if platform.system() == 'Windows':
cmonary_fname = "cmonary.... | 49,333 |
def test__atom_inchi_numbers():
""" test graph.atom_inchi_numbers
"""
cgr = C8H13O_CGR
natms = len(graph.atoms(cgr))
for _ in range(10):
pmt_dct = dict(enumerate(numpy.random.permutation(natms)))
cgr_pmt = graph.relabel(cgr, pmt_dct)
inv_pmt_dct = dict(map(reversed, pmt_dct.i... | 49,334 |
def get_stopwords():
"""common stopwords to skip when checking for article names (derived from nltk)
"""
return [
"i",
"me",
"my",
"myself",
"we",
"our",
"out",
"ours",
"ourselves",
"you",
"your",
"he",
"... | 49,335 |
def setPolarBearattr(attrs):
"""
Sets a Polar Bear's attributes based on input dict:
{user_id: num, username: string, happiness: int, oldHappiness: int, size: int}
"""
polarBearCollection = db.get_polarbear_db()
userDict = polarBearCollection.find_one({'user_id' : attrs['user_id']})
if userDict == None:
polar... | 49,336 |
def test_io_dataset_to_in_dataset(fixture_lookup, io_dataset_fixture):
"""test_io_dataset_to_in_dataset"""
args, func, data_func = fixture_lookup(io_dataset_fixture)
def f(v):
dataset = tf.data.Dataset.range(1000)
dataset = dataset.batch(15)
dataset = dataset.map(tf.strings.as_string)
dataset = d... | 49,337 |
def convert_operation_to_task(operation):
"""Converts an Operation to a legacy Task."""
result = _convert_dict(
operation['metadata'], {
'createTime': ('creation_timestamp_ms', _convert_timestamp_to_msec),
'updateTime': ('update_timestamp_ms', _convert_timestamp_to_msec),
'startT... | 49,338 |
def execute_learning(X, G, algo, constrained, outcome):
"""
Wrapper to run bayesian learning
X - evidence (dataframe)
G - domain expert graph (DiGraph)
algo - one of ('greedy', 'exact', 'no-struct')
outcome - binary or bins
constrained (bool) - use G to constrain search if true
returns ... | 49,339 |
def augment_with_derivatives(V=None, theta=None, M=None, tol=1E-8, symm=True, deflate=True):
"""
Make a linear basis containing the subspace spanned by V and a third order tensor theta
e.g. from modal derivatives by deflation.
Parameters
----------
V : ndarray
linear basis
theta : n... | 49,340 |
def fomc_statement(
dates: Union[str, list[str], None] = None,
asDict: bool = False,
) -> Union[pd.DataFrame, dict]:
"""
Get FOMC statements for given date or dates.
`dates`: YYYY-MM-DD, or 'current', or 'previous'.
`asDict`: True or False, will return as dictionary if True.
"""
url = m... | 49,341 |
def lambda_handler(event, context):
""" This is the entry point for the lambda. It will call the main handler, which is within a
try/catch so that we can efficiently log any unhandled exceptions to Cloudwatch/Splunk.
Args:
event (dictionary): contains event data passed in by AWS Lambda ... | 49,342 |
def get_device_number(connection_str):
"""Return the integer device number from the connection string or raise ValueError
if the connection string is not in the format "device <n>" with positive n."""
try:
prefix, num = connection_str.split(' ')
num = int(num)
if prefix != 'device' o... | 49,343 |
def make_pre_copy(path_from, path_to, scale=None):
"""
Function that copies images with modification meta data.
Parameters:
------------------------------
path_from = str, image input path
path_to = str, image output path
scale = float, resizing scale factor
... | 49,344 |
def _test_perceptual_entropy(filename):
"""_test_perceptual_entropy."""
fs = 16000
win_len = 320
signal, sr = librosa.load(filename, None)
signal = librosa.core.stft(
signal,
n_fft=win_len,
window="hann",
win_length=win_len,
hop_length=win_len // 2,
)
... | 49,345 |
def runner():
"""Returns a ```click.testing.CliRunner()`` instance."""
return CliRunner() | 49,346 |
def execute_db_query(connection, query: str) -> None:
"""Executes a SQL query on the Sqlite3 database
Args:
connection: A database connection object
query: The SQL query as a string
Returns:
Nothing.
"""
cursor = connection.cursor()
try:
cursor.execute(query)
... | 49,347 |
def test_width_of_interval_slicer_reference_left_left_open(test_data):
"""
Function to compare characterisics of reference interval generated by
NumberOfIntervalSlicer and manually generated interval. Specific test
case: the reference of the interval is the lower boundary (left) and the
lower inter... | 49,348 |
def generate_ascii(image_path):
""" Generate New Config
Parameters
----------
image_path : str
Path to image file
"""
if not os.path.isfile(image_path):
print("Invalid image path!")
sys.exit(1)
#
art = ascii_magic.from_image_file(
img_path=image_path,
... | 49,349 |
def hung(idea, ans):
"""
Message for user who guess wrong and have no more chance to play
:param idea: str, the user's guess
:param ans: str, the initiated random word
:return: message to user
"""
print('There is no ' + idea + '\'s in the word.')
print('You are completely hung : (')
... | 49,350 |
def realtime_comment_classifier(sender, instance, created, **kwargs):
"""
Classifies a comment after it has been created.
This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,
default behaviour is to classify(True).
"""
# Only classify if newly created.
if created:
... | 49,351 |
def bent_plume_ic(profile, particles, Qj, A, D, X, phi_0, theta_0, Tj, Sj,
Pj, rho_j, cj, chem_names, tracers, p):
"""
Build the Lagragian plume state space given the initial conditions
Constructs the initial state space for a Lagrangian plume element from
the initial values for... | 49,352 |
def mkdir(*path):
"""
Quick helper to check if a directory exists (starting from
RESULTS_DIR_ROOT) and create it if not.
path should be a list of path fragments (they will be joined together
along with RESULTS_DIR_ROOT).
"""
full_path = normpath(*path)
if not os.path.exists(full_path):... | 49,353 |
def GetMatrixBase(dim, val = 0):
"""Return matrix base, with a single sand grain in the middle"""
m = np.ones(dim) * val
SandFalling(m, 1)
return m | 49,354 |
def are_resize_confirm_logs_created(logs, instance, guest_hb=False):
"""
Check if resize-confirm logs have been created
"""
expected_logs = [{'event_log_id': fm_constants.FM_LOG_ID_VM_RESIZE_CONFIRM,
'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL},
{'event... | 49,355 |
def find_second_largest2(root_node):
"""
Time: O(h)
Space: O(h)
h: height of the tree (O(lg n)); n: # of nodes
"""
def find_largest(node):
if node is None:
raise ValueError('Tree must have at least 1 node')
if node.right is not None:
return find_largest(... | 49,356 |
def parse_team_totals(page):
"""
gets only the totals for a team from the box score of a game
(i.e. the last row)
"""
soup = BeautifulSoup(page, features='lxml')
scorebox = soup.find('div', {'class':'scorebox'})
teams = [TEAM_NAME_TO_TEAM(item.text) for item in
scorebox.find_all('a'... | 49,357 |
def ball(p, radius, mass=-1):
"""Creates a ball that reacts to gravity.
:param p: The center point of the ball
:type p: (int, int)
:param radius: The radius of the ball
:type radius: int
:param mass: The mass of the shape (defaults to 1)
:type mass: int
:rtype: shape
"""
return... | 49,358 |
def test_specs_spec_name_versions_version_put_invalid_version(client):
"""
GIVEN spec id, data, invalid version and token
WHEN PUT /v1/specs/{spec_name}/versions/{version} is called with the Authorization
header
THEN 400 is returned.
"""
version = "a"
data = "data 1"
spec_name = ... | 49,359 |
def antya_nalopa(p: Prakriya, index):
"""Rules that delete the final n of a term.
(6.4.37 - )
"""
c = p.terms[index]
n = TermView.make(p, index)
if not n:
return
n.u = n.terms[0].u
anudatta_tanadi_van = c.all(T.ANUDATTA) or c.u in TAN_ADI or c.text == "van"
jhali = n.adi ... | 49,360 |
def cas_proxyCallback(request):
"""
This is a placeholder for a proxyCallback service
needed for CAS authentication
"""
logger.debug("Incoming request to CASPROXY (Proxy Callback):")
return HttpResponse("I am at a RSA-2 or VeriSigned SSL Cert. website.") | 49,361 |
def get_secret_id(source="~/.vault-id"):
""" Reads a vault user-id (UUID) from a file."""
source = os.path.abspath(os.path.expanduser(source))
user_id = None
# pylint: disable=invalid-name
if os.path.isfile(source):
fd = open(source, "r")
user_id = fd.read().strip()
fd.close... | 49,362 |
def decode_actions(
node_logits: torch.Tensor,
parent_label_logits: torch.Tensor,
new_label_logits: torch.Tensor,
label_vocab: List[Label],
) -> List[Any]:
"""
Decode the most likely actions from action logits for the attach-juxtapose transition system
"""
batch_size = node_logits.size(0... | 49,363 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up device tracker for OpenMediaVault component."""
inst = config_entry.data[CONF_NAME]
omv_controller = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]
sensors = {}
@callback
def update_controller():
"""Up... | 49,364 |
def timetz_pack(timetup_tz, dl_pack = dl_pack, mktime = mktime):
"""
Pack a time; offset from beginning of the day and timezone offset.
Given a pair, ((seconds, microseconds), timezone_offset), pack it into its
serialized form: "!dl".
"""
(timetup, tz_offset) = timetup_tz
return dl_pack((mktime(timetup), tz_off... | 49,365 |
def authentication_exempt(handler):
"""Mark the endpoint handler as not requiring authentication.
Note:
This only applies when the authentication_required_middleware is
being used.
"""
# Can't set attributes directly on a bound method so we need to
# wrap it in a function that we ca... | 49,366 |
def main() -> None:
"""
Calculate and output the solutions based on the real puzzle input.
"""
data = aocd.get_data(year=2020, day=6)
groups = [[set(form) for form in group.split("\n")] for group in data.split("\n\n")]
part1 = sum(len(reduce(union, group)) for group in groups)
print(f"Part ... | 49,367 |
def make_scan(headers, light_ROI=[0, np.inf, 0, np.inf],
curvature=np.array([0., 0., 0.]), bins=1,
ADU_per_photon=1, detector='rixscam_centroids',
min_threshold=-np.inf, max_threshold=np.inf,
background=None):
"""
Make 4D array of RIXS spectra with structu... | 49,368 |
def print_args(function):
"""Decorate the given function to print out it's arguments and return val if not None
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
bound_arguments = bind_args(function, *args, **kwargs)
print("{name}({call})".format(
name=function.__... | 49,369 |
def load_data(cutoff: float) -> DataFrame:
"""
Loads descriptors and binding data for given cutoff.
"""
# Load ECIF
ecif = pd.read_csv(f'Descriptors/ECIF_{cutoff}.csv')
# Load ligand descriptors
ligand_descriptors = pd.read_csv("Descriptors/RDKit_Descriptors.csv")
# Load binding affinity... | 49,370 |
def phys2digital(mvolts):
"""
Obtains the digital difference value in the signal that corresponds to
a certain physical magnitude variation.
"""
return mvolts * ADCGain | 49,371 |
def reverse_log_reader(filename, block_size=8192, start_pos=None):
""" read log file in reverse order
:param filename: filename or stream to parse
:param block_size: max block size to examine per loop
:param start_pos: start at position in file (None is end of file)
:return: generator
"""
if... | 49,372 |
def data_kg(self,one):
"""
添加数据
"""
kg=Kg()
kg.one(one,one[2]) | 49,373 |
def test_run_update(api):
""" Verify the ``run_update`` method call """
RUN_ID = 1234
PARAMS = {'param_key': 'param_value'}
api._session.request.return_value = RUN1
run = api.run_update(RUN_ID, PARAMS)
exp_call = mock.call(method=POST,
path=AP['update_run'].format(run_i... | 49,374 |
def resolve_mock_target(target: Any) -> str:
"""
`mock.patch` uses a str-representation of an object to find it, but this doesn't play well with
refactors and renames. This method extracts the str-representation of an object.
This method will not handle _all_ kinds of objects, in which case an Att... | 49,375 |
def a_star_dist(start_state: frozenset, end_state: frozenset):
"""A* algorithm to calculate minimum energy needed to traverse the given states."""
start_node = Node(0, start_state)
open_pq = [start_node]
g_scores = defaultdict(lambda: math.inf)
g_scores[start_state] = 0
while open_pq:
cu... | 49,376 |
def get_calc_data(stock_code, s, e, fq='qfq',
drop_columns=['code', 'preclose', 'adj'],
scaler=['amount', 'volume'],
scaler_func=sklearn.preprocessing.MinMaxScaler):
"""获取计算用数据源
Args:
fq: 是否采用复权数据。默认使用前复权。如果不需要复权则传''即可。
stock_code:
s... | 49,377 |
def test_checkfile(qtbot):
"""Check that CheckFile is actually a CheckFile"""
check = CheckFile()
qtbot.addWidget(check)
assert isinstance(check, CheckFile) | 49,378 |
def encode_add_validator_and_reconfigure_script(
sliding_nonce: st.uint64, validator_name: bytes, validator_address: AccountAddress
) -> Script:
"""# Summary
Adds a validator account to the validator set, and triggers a
reconfiguration of the system to admit the account to the validator set for the syst... | 49,379 |
def get_microphone():
"""Return raw data from microphone as Numpy array
Default format will be 16-bit signed mono. Format will match
audio playback. You must call tick() every frame to update the
results from this function.
"""
glock.acquire()
d = gmicdata
glock.release()
return ... | 49,380 |
def _expand_arrays(raw_variables, old_variables={}, compat='identical'):
"""Expand a dictionary of variables.
Returns a dictionary of Variable objects suitable for inserting into a
Dataset._arrays dictionary.
This includes converting tuples (dims, data) into Variable objects,
converting coordinate... | 49,381 |
def build_and_push_docker_image(args):
"""docker-py doesn't seem to work, so use subprocess to call Docker"""
# This could be configurable, but there isn't much point.
HTTP_PORT = 8081
image_name = f"{args.dockerhub_repo}/scpca_portal_api"
# Change dir so docker can see the code.
os.chdir("../... | 49,382 |
def redundant_peaks(usrdata):
"""Remove redundant, often ambiguous peaks by keeping the peak
with the highest ion score"""
peaks = usrdata.sort_values(by="IonScore", ascending=False).drop_duplicates(
subset=["SpectrumFile", "SequenceModi", "Charge", "PrecursorArea"]
)
peaks["Peak_UseFLAG"] =... | 49,383 |
def getattr_in_module(module_name: str, func_name: str):
""" 在某个模块中获取属性
Args:
module_name: 模块名
func_name: 属性名
Returns:
属性
"""
m = importlib.import_module(module_name)
return getattr(m, func_name) | 49,384 |
def file_upload(remote, local):
"""Uploads the local file to the remote location only if the remote location does not
exists or the content are different."""
# FIXME: Big files are never transferred properly!
f = file(local, 'rb')
content = f.read()
f.close()
sig = hashlib.sha256(c... | 49,385 |
def codeblock(request):
"""Parametrized fixture of each convention codeblock."""
return request.param | 49,386 |
def setup(bot: KoalaBot) -> None:
"""
Loads this cog into the selected bot
:param bot: The client of the KoalaBot
"""
bot.add_cog(IntroCog(bot))
print("IntroCog is ready.") | 49,387 |
def mapreduce(config):
""" Submit a new job in the jobstracker using a config class """
# connect to master and submit a config class to
# log a new job in the scheduler
host = get_host_ip()
#try get master_ip from network
master_ip = do_broadcast(host, 6666)
if not master_ip:
r... | 49,388 |
def cp_ls_cholesky_factor_objective(beta_gamma, norb, nthc, cholesky_factor, calcgrad=False):
"""cholesky_factor is reshaped into (norb, norb, num_cholesky)
Cholesky factor B_{ab,x}
Least squares fit objective ||B_{ab,x} - \sum_{r}beta_{a,x}beta_{b,x}gamma_{ab,x}||
This function provides the objectiv... | 49,389 |
def get_domains_output(admin_managed: Optional[pulumi.Input[Optional[bool]]] = None,
include_unverified: Optional[pulumi.Input[Optional[bool]]] = None,
only_default: Optional[pulumi.Input[Optional[bool]]] = None,
only_initial: Optional[pulumi.Input[Op... | 49,390 |
def volumes(jukebox_name, slot_id=[], as_object=False, p5_connection=None):
"""
Syntax: Jukebox <name> volumes
Description: Returns a list of all volumes currently loaded in the <name>
jukebox. To update the list of the volumes in the jukebox, use the
inventory method.
Return Values:
-On Suc... | 49,391 |
def calculate_psi(cube, cfg):
"""Calculate temperature variability metric psi for a given cube."""
window_length = cfg.get('window_length', 55)
lag = cfg.get('lag', 1)
psi_years = []
psis = []
# Moving average
for yr_idx in range(cube.shape[0] - window_length):
slc = slice(yr_idx, y... | 49,392 |
def _get_product_features(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Get outer product of 2 tensors along the last dimension.
All dimensions except last are preserved. The last dimension is replaced
with flattened outer products of last-dimension-vectors from input tensors
This is a... | 49,393 |
def test_x2sys_cross_region_interpolation_numpoints(mock_x2sys_home):
"""
Test that x2sys_cross's region (R), interpolation (l) and numpoints (W)
arguments work.
"""
with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir:
tag = os.path.basename(tmpdir)
x2sys_init(tag=tag,... | 49,394 |
def test_find_nth_double_positive():
"""
Make sure that...
"""
# Arrange
search_in = "abc def abc"
search_for = "abc"
nth = 2
expected_output = 8
# Act
actual_output = ParserHelper.find_nth_occurrence(search_in, search_for, nth)
# Assert
assert expected_output == actua... | 49,395 |
def resume_job(args, wording):
"""
used by fg and bg to resume a job either in the foreground or in the background.
"""
_clear_dead_jobs()
if len(tasks) == 0:
return "", "There are currently no suspended jobs"
if len(args) == 0:
tid = tasks[0] # take the last manipulated task b... | 49,396 |
def drop_me(message):
"""This function removes user/chat id into a database.
Parameters
----------
message : telebot.types.Message
The message object.
Returns
-------
msg : str
User/Chat alert list addition/removal.
"""
helpers.start_connection().query("""
DELETE FROM
`mooncake-304003.misc.ps5-broa... | 49,397 |
def summaries_with_matching_keyword(keyword, summary_dir):
"""Yields summary protos matching given keyword from event file."""
event_paths = tf.io.gfile.glob(os.path.join(summary_dir, 'events*'))
for event in tf.compat.v1.train.summary_iterator(event_paths[-1]):
if event.summary is not None:
for va... | 49,398 |
def cmpd_to_pt(cmpd, els):
"""
Args:
cmpd (str) - chemical formula
els (list) - ordered list of elements (str) in triangle (right, top, left)
Returns:
(x, y) for compound
"""
tri = [CompAnalyzer(cmpd).fractional_amt_of_el(el) for el in els]
return triangle_to_square(... | 49,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.