content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def keep_active(useruid: str):
"""
試著保持著登入狀態
"""
# 取得使用者物件
user = User(useruid)
session = get_session(useruid)
# 確認登入狀態
if session.active:
return True
# 嘗試重新登入
try:
session.login(user.userid,
user.passwd,
session.cours... | 5,308,600 |
def random_string(length=16):
"""Generate a random string of the given length."""
result = ""
while len(result) < length:
result += random.choice(string.ascii_letters + string.digits)
return result | 5,308,601 |
def getIfacesInZone(zone_ifaces):
"""
Parse given interfaces for a zone for associating a zone with an interface
and set any properties listed to defined values upon fan control starting
on the zone.
"""
ifaces = []
for i in zone_ifaces:
iface = {}
# Interface name not neede... | 5,308,602 |
def calculate_confusion(config, predicted_indices, y_indices):
"""Helper method that calculates confusion matrix."""
confusion = np.zeros((config.label_size, config.label_size), dtype=np.int32)
for i in xrange(len(y_indices)):
correct_label = y_indices[i]
guessed_label = predicted_indices[i]... | 5,308,603 |
def make_surrogates(data, parcellation, scale, spatnull):
"""
Generates surrogates for `data` using `spatnull` method
Parameters
----------
data : (N,) pd.DataFrame
parcellation : {'atl-cammoun2012', 'atl-schaefer2018'}
scale : str
spatnull : {'burt2018', 'burt2020', 'moran'}
Retur... | 5,308,604 |
def grafica_cluster (cluster, centros):
"""
Grafica un cluster de puntos
Args:
cluster (List): Una lista con los clústers
centros (List): Una lista con los centros de los clústers
"""
cmap=plt.cm.rainbow
norm = matplotlib.colors.BoundaryNorm(np.arange(0,10,1), cmap.N)
plt.s... | 5,308,605 |
def CheckpointToSavedModel(ckpt_path, inputs, outputs, savedmodel_path, clear_devices=False):
"""
Read a Checkpoint and build a SavedModel
Args:
ckpt_path: path to the checkpoint file (without the ".meta" extension)
inputs: input list of placeholders names (e.g. ["x_cnn_1:0", "x_cnn_2:0"])
outputs:... | 5,308,606 |
def audit_superseder (db, cl, nodeid, new_values) :
"""
* ensure that we do not set superseder on a new item
* ensure that superseder gets not set to itself
* automatically set status to closed
"""
new_sup = new_values.get ("superseder", None)
if new_sup :
if not nodeid :
... | 5,308,607 |
def initdb_command():
"""Initializes the database."""
init_db()
print 'Initialized the database.' | 5,308,608 |
def basename(filename):
"""
Return basename of given filename.
Parameters
----------
filename : :class:`str`
Name of the file (may contain absolute path and extension) the
basename should be returned for.
Returns
-------
basename : :class:`str`
Basename correspo... | 5,308,609 |
def add_birth_rate_functions(_tb_model, _input_database, _country_iso3):
"""
Add crude birth rate function to existing epidemiological model
:param _tb_model: EpiModel or StratifiedModel class
SUMMER model object to be assigned bcg vaccination coverage functions
:param _input_database: sql data... | 5,308,610 |
def generate_kml_end_str():
""" Generates the footer for a KML file
"""
kml_str = '</Document>'
kml_str += '</kml>'
return kml_str | 5,308,611 |
def _GetUserTypeAndPassword(username, password=None, is_admin=False):
"""Returns the user-type and password for a user.
Args:
username: Username for the user.
password: Password for the user. If None, or not provided, we will prompt
for one via the terminal.
is_admin: Indicates whether the user s... | 5,308,612 |
def image_Rescale(image_Path):
"""
This will rescale all in user image into 3:2 Image ratio
Perform and save to the same image path
:param image_Path: string : Path to image
"""
size = IMAGE_HEIGHT, IMAGE_WIDTH
im = Image.open(image_Path)
im.thumbnail(size)
newimg = im.r... | 5,308,613 |
def top_ions(df1, df2):
""" function to compute the top species, top filename and top species/plant part for each ion
Args:
df1 = reduced_df, table of with index on sp/part column and features only.
df2 = quantitative.csv file, output from MZmine
Returns:
None
"""
#compu... | 5,308,614 |
def get_genome_group(src_loc: Path, config: Config) -> GenomeGroup:
"""Get the ``GenomeGroup`` based on ``src_loc`` and ``config``.
``Config`` is used to set global filter codes and exclude files on group creation.
Args:
src_loc: Path, can be directory or file
config: the running config ob... | 5,308,615 |
def rtl_dashboard(request):
"""RTL Dashboard page.
"""
return render(request, "django_sb_admin/sb_admin_rtl_dashboard.html",
{"nav_active":"rtl_dashboard"}) | 5,308,616 |
def relationship(flights, planes):
"""
Here we are having two columns common between flights and planes tables, which are
tailnum and year.
from above two common fields we consider tailnum column as keys in both the table.
In
"""
print(planes.shape) # (3322, 9)
print(planes.tailnum.nuni... | 5,308,617 |
def numpy_unpad(x, pad_width):
"""Unpad an array.
Args:
x (numpy.ndarray): array to unpad
pad_width (tuple): padding
Returns:
numpy.ndarray
"""
slices = []
for c in pad_width:
e = None if c[1] == 0 else -c[1]
slices.append(slice(c[0], e))
return x[tu... | 5,308,618 |
def linear(a, b, c):
"""exec a * b + c"""
print('exec linear')
ret = a * b + c
print('linear: %s * %s + %s = %s' % (a, b, c, ret))
return ret | 5,308,619 |
def test_round():
"""Tests round"""
_test_elementwise(
ops.round, [-0.9, 0.00001, 1.0, 3.14], [-1.0, 0.0, 1.0, 3.0]
) | 5,308,620 |
def start():
"""start goal"""
print("/start <- ")
print(request.get_json())
goal_id = request.get_json()['goal_id']
resDB = db.start(goal_id)
jsonResult = {
"result" : resDB
}
resJson = json.dumps(jsonResult)
print("/start -> ")
print(resJson)
return resJson | 5,308,621 |
def get_eer_values(fmr, fnmr):
"""Returns the value of the Equal Error Rate
Equal Error Rate (EER): is the point where FNMR(t) = FMR(t).
In practice the score distribution are not continuous so and interval
is returned instead. The EER value will be set as the midpoint of
this interval.
The in... | 5,308,622 |
def testDateTime():
"""
@tests:
DateTime.__init__
DateTime.getDate
DateTime.getTime
DateTime.now
"""
d = pyopenms.DateTime()
assert isinstance( d.getDate(), bytes)
assert isinstance( d.getTime(), bytes)
d = pyopenms.DateTime.now()
assert isinstance( d.getDate(), bytes... | 5,308,623 |
def test_window_size():
"""Determine window size for linear accelerometer, gyroscope measurements of motion gestures."""
recordings = read_recordings(os.path.dirname(accelerometer_gyroscope.__file__))
window_checked = check_windows(recordings, window_size=SAMPLES_PER_RECORDING)
os.makedirs(TEST_OUTPUT, ... | 5,308,624 |
def _update_token(token):
""" Fitbit module will take care of refreshing tokens and call this method when necessary """
print("Updating token")
# update the user dict
user = current.db(current.db.auth_user.username == token['user_id']).select().first()
if user:
user.update(
to... | 5,308,625 |
def validate_spec(index, spec):
""" Validate the value for a parameter specialization.
This validator ensures that the value is hashable and not None.
Parameters
----------
index : int
The integer index of the parameter being specialized.
spec : object
The parameter specializa... | 5,308,626 |
def ENgetflowunits():
"""Retrieves a code number indicating the units used to express all flow rates."""
j= ctypes.c_int()
ierr= _lib.ENgetflowunits(ctypes.byref(j))
if ierr!=0: raise ENtoolkitError(ierr)
return j.value | 5,308,627 |
def read_config(config_path, defaults):
"""Read config file from given location, and parse properties"""
if not os.path.isdir(config_path):
raise ValueError("{0} is not a directory".format(config_path))
try:
return yaml_load(config_path, defaults)
except yaml.YAMLError:
logging.... | 5,308,628 |
def _get_file_names():
"""Returns the file names expected to exist in the input_dir."""
file_names = {}
file_names['train'] = ['data_batch_%d' % i for i in xrange(1, 5)]
file_names['validation'] = ['data_batch_5']
file_names['eval'] = ['test_batch']
return file_names | 5,308,629 |
def index_of_best(list):
"""
low distance is better
:param list:
:return:
"""
a_list, error_count, error = remove_errors(list)
return list.index(min(a_list)) | 5,308,630 |
def mold(
content: VyList,
shape: VyList,
) -> VyList:
"""Mold one list to the shape of the other. Uses the mold function
that Jelly uses."""
# https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L578
if isinstance(content, str):
... | 5,308,631 |
def goal_optimization(model_exp_key, opt_exp_key=None, write_results=True):
"""
Optimize random goal states using a model-based estimator.
Note: tailored to HalfCheetah-v2 environment currently.
Args:
model_exp_key (str): model-based experiment key
opt_exp_key (str): optimizer experimen... | 5,308,632 |
def _read_datafile(path, expected_dims):
"""Utility function for reading mnist data files."""
base_magic_num = 2048
with gzip.GzipFile(path) as f:
magic_num = struct.unpack('>I', f.read(4))[0]
expected_magic_num = base_magic_num + expected_dims
if magic_num != expected_magic_num:
... | 5,308,633 |
def _vsos(da, pos, method_sos="median"):
"""
vSOS = Value at the start of season
Params
-----
da : xarray.DataArray
method_sos : str,
If 'first' then vSOS is estimated
as the first positive slope on the
greening side of the curve. If 'median',
then vSOS is estima... | 5,308,634 |
def setup_source_temp():
"""
Copy the source toctrees to new folder for assembling the sphinx-docs
"""
print("=== Copying Source toctrees ===")
if os.path.exists(SASVIEW_TOC_SOURCE):
print("Found docs folder at", SASVIEW_TOC_SOURCE)
shutil.copytree(SASVIEW_TOC_SOURCE, SPHINX_SOURCE) | 5,308,635 |
def list(ctx,
# Optional main parameter
startvolumeid = None,
# Optional main parameter
limit = None,
# Optional main parameter
volumestatus = None,
# Optional main parameter
accounts = None,
# Optional main parameter
... | 5,308,636 |
def parse_coordSys(config, coordSys=batoid.CoordSys()):
"""
@param config configuration dictionary
@param coordSys sys to which transformations in config are added
"""
shift = [0.0, 0.0, 0.0]
if any(x in config for x in ['x', 'y', 'z']):
if 'shift' in config:
raise ValueErr... | 5,308,637 |
def password_hasher(password):
"""
Just hashes the password
:param password:
:return: 32 byte hash
:rtype: bytes
"""
return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), b'salt', 100000) | 5,308,638 |
def index_alpha_beta(i, ij, ik, points):
"""
Finds for each input point the index of it's bounding triangle
and the alpha and beta value for that point in the triangle. Note
this means that the following statements will always be true:
alpha + beta <= 1
alpha >= 0
beta >= 0
f... | 5,308,639 |
def flac_read_file_f32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.... | 5,308,640 |
def test_adv_xml_search_abs():
"""Test advanced xml searching, to navigate from root of document (PR #9)"""
test_xml = """
<GBSeq_feature-table>
<GBFeature>
<GBFeature_key>source</GBFeature_key>
<GBFeature_quals>
<GBQualifier>
<GBQualifier_... | 5,308,641 |
def version() -> str:
"""
Version library
:return: version
"""
pfun = _lib.zmVersionLib
pfun.restype = None
pfun.argtypes = (ctypes.c_char_p,)
ver = ctypes.create_string_buffer(32)
pfun(ver)
return ver.value.decode("utf-8") | 5,308,642 |
def get_all_books(request):
"""
This view is to return all the books
"""
books = Book.objects.all()
context = {
'books': books
}
return render(request, 'books/books.html', context=context) | 5,308,643 |
def _GetSchemaPath(release_track, for_help=False):
"""Returns the resource schema path."""
return export_util.GetSchemaPath(
'compute',
_GetApiVersion(release_track),
'TargetHttpsProxy',
for_help=for_help) | 5,308,644 |
def login():
"""Login a user"""
if not request.is_json:
return jsonify(error="Missing JSON in request"), 400
username = request.json.get("username", None)
password = request.json.get("password", None)
remember = request.json.get("remember", False)
if not username:
return jsonify(... | 5,308,645 |
def patch_thread(threading=True, _threading_local=True, Event=False):
"""Replace the standard :mod:`thread` module to make it greenlet-based.
If *threading* is true (the default), also patch ``threading``.
If *_threading_local* is true (the default), also patch ``_threading_local.local``.
"""
patch_... | 5,308,646 |
def _load_state(path):
"""Load a GUI state from a JSON file."""
try:
logger.debug("Load %s for GUIState.", path)
data = load_json(str(path))
except json.decoder.JSONDecodeError as e: # pragma: no cover
logger.warning("Error decoding JSON: %s", e)
data = {}
return _bunchi... | 5,308,647 |
def plot_water_levels(station, dates, levels):
"""Returns a list of tuples with the station and relative water level"""
highs = []
lows = []
if (station.typical_range is None):
pass
else:
for i in range(len(levels)):
highs.append(station.typical_range[1])
... | 5,308,648 |
def client_host(server_host):
"""Return the host on which a client can connect to the given listener."""
if server_host == '0.0.0.0':
# 0.0.0.0 is INADDR_ANY, which should answer on localhost.
return '127.0.0.1'
if server_host in ('::', '::0', '::0.0.0.0'):
# :: is IN6ADDR_ANY, which should answer on localhost... | 5,308,649 |
def get_context(bot, update, session, user):
"""Create a context object for callback queries."""
context = CallbackContext(session, bot, update.callback_query, user)
add_breadcrumb(
crumb={
"query": update.callback_query,
"data": update.callback_query.data,
"user... | 5,308,650 |
def customer_all_detail(request, pk):
"""客户详情(不能更改信息)"""
customer = get_object_or_404(Customer, pk=pk, is_valid=True)
form = CustomerForm(instance=customer)
# 添加上地址信息
# 下面这里引入异常处理,如果数据库里没有该字段,那么表单渲染为空
try:
customer_shop = CustomerShop.objects.get(customer=pk)
shopform = C... | 5,308,651 |
def test_load_node_with_params(mock_component_container):
"""Test loading a node with parameters."""
context = _assert_launch_no_errors([
_load_composable_node(
package='foo_package',
plugin='bar_plugin',
name='test_node_name',
namespace='test_node_namespa... | 5,308,652 |
def logmethod(func):
""" Decorator to add logging information around calls for use with . """
def _wrapper(self, *args, **kwds):
logging.info("Start::%s.%s:%s",
func.__module__,
self.__class__.__name__,
func.__name__)
returnval = fu... | 5,308,653 |
def generate_project(source, language, outdir, uri):
"""For the given C struct source code, generate source code to read and
write that data in the given language. The resulting source code will be
written to disk at the location specified by outdir.
Args:
source: C source text that only contai... | 5,308,654 |
def robots():
""" "Just in case?" """
return send_from_directory(os.path.join(app.root_path, 'static'),
'robots.txt',
mimetype='text/plain') | 5,308,655 |
def createConstraint(obj_PhysicsID, root_PhysicsID, constraintType, pointPos_x, pointPos_y, pointPos_z, edgePos_x, edgePos_y, edgePos_z, edgeAngle_x, edgeAngle_y, edgeAngle_z):
"""
Create a point constraint between two objects, an edge constraint between two objects, or a vehicle constraint on an object.
You only... | 5,308,656 |
def to_isbn(ean):
"""Convert EAN to ISBN"""
clean = clean_isbn(ean)
isbn = clean[3:-1]
isbn.append(isbn_check_digit(isbn))
return ''.join(str(d) for d in isbn) | 5,308,657 |
def markdown_cell(content):
"""
Create a markdown cell with a given content.
"""
return nbformat.notebooknode.NotebookNode({"cell_type": "markdown", "source": content, "metadata": {}}) | 5,308,658 |
def _replace_suffix(string, old, new):
"""Returns a string with an old suffix replaced by a new suffix."""
return string.endswith(old) and string[:-len(old)] + new or string | 5,308,659 |
def calculate(loan_amount, interest_rate, years=1, payment_type=EP):
"""A mortgage payment calculator."""
print(
f"Loan Amount: {loan_amount}, Interest Rate: {interest_rate}, Years: {years}, Loan Type: {payment_type}"
)
print("*" * 80)
months = years * 12
mir = interest_rate / 12
if... | 5,308,660 |
def compute_fig(grid, col_x, col_y, col_z, value_coupe, n_points, xlim, ylim):
"""uses user input parameters to compute the values to plot
Parameters
----------
grid : pandas.DataFrame
full data grid
col_x : string
horizontal column in final plot
col_y : string
vertical ... | 5,308,661 |
def test_check_X_categorical_prediction_exceeds_training(wage_X_y, wage_gam):
"""
if our categorical variable is outside the training range
we should get an error
"""
X, y = wage_X_y # last feature is categorical
gam = wage_gam
# get edge knots for last feature
eks = gam.edge_knots_[-1]... | 5,308,662 |
def is_empty_json_response_from_s3(context):
"""Check if the JSON response from S3 is empty (but not None)."""
return context.s3_data == {} | 5,308,663 |
def CheckCustomCpuRamRatio(compute_client, project, zone, machine_type_name):
"""Checks that the CPU and memory ratio is a supported custom instance type.
Args:
compute_client: GCE API client,
project: a project,
zone: the zone of the instance(s) being created,
machine_type_name: The machine type o... | 5,308,664 |
def vault_value(key, default=None):
"""
Returns the secret referenced by the key supplied.
If the vault has not been initialized, returns the provided default instead
:param key:
:param default:
:return:
"""
if not vault_ready():
return default
try:
return _get_from_... | 5,308,665 |
def download(m3u8_path, mp4_path=None, ffmpeg_path=FFMPEG, ffmpeg_loglevel=FFMPEG_LOGLEVEL, force_down=False):
"""执行下载操作,需要依赖ffmpeg
:param m3u8_path: 要下载的m3u8文件的绝对路径
:param mp4_path: 输出文件路径,默认输出和m3u8同级目录同名文件
:param ffmpeg_path: ffmpeg可执行程序的路径
:param ffmpeg_loglevel: 日志级别
:param force_down: 当已将下... | 5,308,666 |
def show_expression_of_KO_genes(
sample_meta_file: str,
normalized_matrix: str,
ko_list: list,
ko_dict: dict = "",
percentile: bool = False,
heat: bool = False,
):
"""
Show expression of the genes that were actually knocked out.
Parameters
----------
sample_meta_file
... | 5,308,667 |
def preprocessEventData(eventData):
"""
Ensures that the event data dictionary is consistent before it reaches the template or event logic.
- dates should exist and be date objects if there is a value
- checkbaxes should be True or False
- if term is given, convert it to a model obj... | 5,308,668 |
def main(ctx, base):
"""A script to interact with the Anki database.
The base directory may be specified with the -b / --base option. For
convenience, it may also be specified in the config file
`~/.config/apy/apy.json` or with the environment variable APY_BASE or
ANKI_BASE.
A few sub commands... | 5,308,669 |
def get_data(self):
"""Generate the PWM matrix
Parameters
----------
self : ImportGenPWM
An ImportGenPWM object
Returns
-------
matrix: ndarray
The generated PWM matrix
"""
# Tpwmu=np.arange(fs*duration)/fs,
Tpwmu = np.linspace(0, self.duration, self.fs * self.... | 5,308,670 |
def set_code_by_activity_hash(db, overwrite=False):
"""Use ``activity_hash`` to set dataset code.
By default, won't overwrite existing codes, but will if ``overwrite`` is ``True``."""
for ds in db:
if 'code' not in ds or overwrite:
ds['code'] = activity_hash(ds)
return db | 5,308,671 |
def ca_time_sync(h_session, ultime):
"""
:param int h_session: Session handle
:param ultime:
"""
ret = CA_TimeSync(h_session, CK_ULONG(ultime))
return ret | 5,308,672 |
async def test_lock_operator_keypad(opp):
"""Test operation of a lock with doorsense and bridge."""
lock_one = await _mock_doorsense_enabled_august_lock_detail(opp)
activities = await _mock_activities_from_fixture(
opp, "get_activity.lock_from_keypad.json"
)
await _create_august_with_device... | 5,308,673 |
def add_subparser(parser):
"""Add the subparser that needs to be used for this command"""
plot_parser = parser.add_parser("plot", help=DESCRIPTION, description=DESCRIPTION)
cli.get_basic_args_group(plot_parser)
plot_parser.add_argument(
"kind",
type=str,
choices=SINGLE_EXPERIME... | 5,308,674 |
def Potential_bruteforce_parallel(x,m,softening,G=1.):
"""Returns the exact mutually-interacting gravitational potential for a set of particles with positions x and masses m, evaluated by brute force.
Arguments:
x -- shape (N,3) array of particle positions
m -- shape (N,) array of particle masses
s... | 5,308,675 |
def client():
"""init the autotradeweb flask app as a testing client"""
flask_app = APP
flask_app.config["DEBUG"] = True
flask_app.config["TESTING"] = True
with flask_app.test_client() as c:
yield c | 5,308,676 |
def _validate_plurals(mapping: Mapping[str, Any],
ref: str) -> List[SchemaError]:
"""
Check that no graph field conflicts with a instance registry field.
The instance registry field is identified with a plural of the class.
:param mapping: schema mapping to be validated
:par... | 5,308,677 |
def test_launch_benchmark_validate_bad_in_graph(
mock_system_platform, mock_os, mock_subprocess):
"""
Verifies that an invalid input graph path fails.
"""
setup_mock_values(mock_system_platform, mock_os, mock_subprocess)
launch_benchmark = LaunchBenchmark()
args, _ = launch_benchmark.par... | 5,308,678 |
def mock_validator_execute_validator(*args, **kwargs):
"""
Mock method to just return the builded command line without
executing it.
"""
cls = args[0]
command = args[1]
return command | 5,308,679 |
def load_seq(seq_path):
"""Load HPatches sequences."""
seq = cv2.imread(seq_path, 0)
n_patch = seq.shape[0] / 65
seq = np.reshape(seq, (n_patch, 65, 65, 1)).astype(np.float32)
resized_seq = np.zeros((n_patch, 32, 32), np.float32)
for i in range(n_patch):
tmp_patch = cv2.resize(seq[i], (... | 5,308,680 |
def mode_check_decorator(func):
"""Decorate load()/save() CookieJar methods."""
def wrapper(cls, **kwargs):
try:
filename = kwargs['filename']
except KeyError:
filename = cls.filename
res = func(cls, **kwargs)
file_mode_checker(filename, mode=0o600)
... | 5,308,681 |
def has_gap(k1, k2, min_gap=0.002):
"""判断 k1, k2 之间是否有缺口"""
assert k2['dt'] > k1['dt']
if k1['high'] < k2['low'] * (1-min_gap) \
or k2['high'] < k1['low'] * (1-min_gap):
return True
else:
return False | 5,308,682 |
def get_pronoun_lemmas(conll_document):
"""
Returns the list of lemmatized pronouns found in the given contents of a CONLL document (list of triples).
:param conll_document: the contents of a CONLL file, as a list of triples
:return:
"""
pronouns = []
for (form, lemma, pos) in conll_document... | 5,308,683 |
def isdisjoint(pth1, pth2):
""" returns 0 if disjoint
"""
edge1 = list(pairwise(pth1))
edge2 = list(pairwise(pth2))
for edge in edge1:
if edge in edge2:
return 1
return 0 | 5,308,684 |
def delete_post(post_id):
"""function for deleting a business by id"""
business = Business.query.get_or_404(post_id)
if business.business != current_user:
abort(403)
db.session.delete(business)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_fo... | 5,308,685 |
def retract(request):
"""retracts a cash invitations"""
params = request.get_params(schemas.RetractSchema())
device = get_device(request)
customer = device.customer
access_token = get_wc_token(request, customer)
postParams = {
'reason': 'other'
}
response = wc_contact(
re... | 5,308,686 |
def main(account, type, filter, verbose, git_options, existing_only):
"""Console script for clone_army"""
if account.startswith('-'):
raise click.BadArgumentUsage("Options for Git should come at end.")
if verbose:
logging.getLogger(__name__).setLevel(logging.INFO)
if existing_only:
... | 5,308,687 |
def generate_fileattr_metadata(local_path, metadata):
# type: (blobxfer.models.upload.LocalPath, dict) -> dict
"""Generate file attribute metadata dict
:param blobxfer.models.upload.LocalPath local_path: local path
:param dict metadata: existing metadata dict
:rtype: dict
:return: merged metadat... | 5,308,688 |
def merge_cfg_from_list(cfg_list):
"""Merge config keys, values in a list (e.g., from command line) into the
global config. For example, `cfg_list = ['TEST.NMS', 0.5]`.
"""
assert len(cfg_list) % 2 == 0
for full_key, v in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = full_key.split('.')
... | 5,308,689 |
def build_estimator(model_dir):
"""Build an estimator."""
m = tf.estimator.LinearClassifier(
model_dir=model_dir, feature_columns=base_columns,
optimizer=tf.train.FtrlOptimizer(
learning_rate=0.1,
l1_regularization_strength=1.0,
l2_regularization_strength=1.0)
)
return m | 5,308,690 |
def _set_logger(
logger_file_path: str,
logger_name: str = "default_logger",
write_to_console: bool = True,
) -> logging.Logger:
"""Set logger to log to the given path.
Modified from https://docs.python.org/3/howto/logging-cookbook.html
Args:
logger_file_path (str): Filepath to write t... | 5,308,691 |
def sort_and_print(body, num):
"""
Sorts the values of dictionaries and prints respective
top sentences
:param body: list of dictionaries of 'sentence': score
:param num: no of sentences to be printed
:return: prints
"""
result = []
rank = []
for sentdict in body:
for sen... | 5,308,692 |
def set_model_input_shape_attr(model, dataset=None, input_shape=None):
"""Sets an attribute named 'input_shape' within the model instance, specifying the expected input shape
Args:
model (nn.Module): Model instance
dataset (str): Name of dataset from which to infer input shape
inp... | 5,308,693 |
def get_trans_func(name):
"""
Retrieves the transformation module by name.
"""
trans_funcs = {
"bottleneck_transform": BottleneckTransform,
"basic_transform": BasicTransform,
}
assert (
name in trans_funcs.keys()
), "Transformation function '{}' not supported".format(... | 5,308,694 |
def game_instructions():
""" Display the game instructions """
print("INSTRUCTIONS")
print("Get two integers from user, check if 1st is a multiple of the 2nd.") | 5,308,695 |
def gen_answer_refine_file(std_dev_file, nbest_file, output_file, split):
"""
generate answer refine file, for choose refine answer
Args:
std_dev_file: official dev file
nbest_file: atrlp prediction nbest file
Returns: a file
"""
data = json.load(open(std_dev_file, 'r', encodin... | 5,308,696 |
def get_box_pair_info(box1, box2):
"""
input:
box1 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
box2 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
output:
32-digits: [box1, box2, unionbox, intersectionbox]
"""
# union box
unionbox = box1[:,:4].clone()
unionbox[:, 0] = torch.min(bo... | 5,308,697 |
def write(sesh):
"""Used to write the page in the app.py file"""
st.markdown(
"""## Add featurization
Some markdown goes here.
""",
unsafe_allow_html=True,
)
if len(sesh.fp) == 0:
write_fingerprints(sesh)
else:
st.write('Fingerprints already generat... | 5,308,698 |
def bintogrid(
x,
y,
unc=None,
newx=None,
dx=None,
weighting="inversevariance",
drop_nans=True,
):
"""
x = the independent variable (wavelength)
y = the measurement (transit depth)
unc = the uncertainty on the measurement (sigmas on the transit depths)
newx = a (linearly)... | 5,308,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.