content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_train_valid(filename):
"""
读取训练或者验证文件
:param filename: 训练集/验证集的文件名字
:return:
返回训练集的文本和标签
其中文本是一个list, 标签是一个list(每个元素为int)
返回示例:['我很开心', '你不是真正的快乐', '一切都是假的], [1, 0, 0]
"""
fp = pd.read_table(filename, sep='\t', error_bad_lines=False)
return fp['review'].tolist(), list(... | 28,800 |
def check_for_recommendation_result_report(context):
"""Check for result if recommedation or not."""
json_data = context.response.json()
if "recommendation" in json_data:
check_recommendation_in_result(context)
else:
look_for_other_attributes(context)
check_vulnerability_in_resul... | 28,801 |
def handle_skinnyski_pdf(race_info):
"""
:param race_info: race metadata (RaceInfo)
:return: void
"""
pdf_content = get_skinnyski_content(race_info)
if pdf_content:
results = UnstructuredPDFRaceResults(race_info, pdf_content)
results.serialize()
else:
print("Warning: ... | 28,802 |
def test_stateless_token_authentication_no_header(rf):
"""Tests that StatelessTokenAuthentication returns nothing if no auth header is present"""
request = rf.get("api/v0/notification_settings")
authentication = StatelessTokenAuthentication()
assert authentication.authenticate(request) is None | 28,803 |
def weighted_regularization_matrix_from(
regularization_weights: np.ndarray,
pixel_neighbors: np.ndarray,
pixel_neighbors_sizes: np.ndarray,
) -> np.ndarray:
"""
From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.
Parameters
---------... | 28,804 |
def generateConstantNoneReferenceCode(to_name, expression, emit, context):
""" Assign 'None' to to_name."""
# No context or other knowledge needed, pylint: disable=unused-argument
emit("%s = Py_None;" % to_name) | 28,805 |
def test_mo_ei_watanabe():
"""based on Watanabe value on H-like Molybdenum
check if deviation by Lotz formula from experiemntal
value exceeds error bars specified by Lotz
"""
elem = csd.get_element_data('Mo')
e_e = 64400
watanabe__ei = csd.ei_lotz_cs(elem, 41, e_e)
print('Error ... | 28,806 |
def _send_email(self, to, subject, html_body):
# We intentionally commented out this code - we used it to prevent emails in development from going to non-Staffjoy emails.
"""
if current_app.config.get("ENV") != "prod":
allowed_domains = ["@staffjoy.com", "@7bridg.es"]
ok = False
for... | 28,807 |
def child_at_time(
self,
search_time,
shallow_search=False,
):
"""Return the child that overlaps with time search_time.
search_time is in the space of self.
If shallow_search is false, will recurse into compositions.
"""
range_map = self.range_of_all_children()
# find... | 28,808 |
def weight_variable_truncated_normal(input_dim, output_dim, name=""):
"""Create a weight variable with truncated normal distribution, values
that are more than 2 stddev away from the mean are redrawn."""
initial = tf.truncated_normal([input_dim, output_dim], stddev=0.5)
return tf.Variable(initial, name... | 28,809 |
def download_image(id_, url, icon_size=200, dst_path="./movie/"):
"""URLから画像をダウンロードする
Parameters
----------
id_ : int
受付ID
url : str
画像のURL
icon_size : int
画像サイズ(24, 48, 73, 200, 400, 512のいずれか), by default 200
dst_path : str, optional
画像の保存場所, by default "ico... | 28,810 |
def get_dummy_vm_create_spec(client_factory, name, data_store_name):
"""Builds the dummy VM create spec."""
config_spec = client_factory.create('ns0:VirtualMachineConfigSpec')
config_spec.name = name
config_spec.guestId = "otherGuest"
vm_file_info = client_factory.create('ns0:VirtualMachineFileInf... | 28,811 |
def _kill_jupyter_processes():
"""Ensure all Jupyter processes are killed."""
global _all_jupyter_processes
while _all_jupyter_processes:
proc = _all_jupyter_processes[0]
if proc.poll() is not None:
_all_jupyter_processes = _all_jupyter_processes[1:]
continue
... | 28,812 |
def test_comparison_ops_eq_t():
"""Check the equal-to operator for a truthy result."""
return """
fn main() {
{dest} = 1 == 1;
}
""" | 28,813 |
def binary_accuracy(*, logits, labels):
"""Accuracy of binary classifier, from logits."""
p = jax.nn.sigmoid(logits)
return jnp.mean(labels == (p > 0.5)) | 28,814 |
def create_app(app_name=None, blueprints=None, config=None):
"""
Diffy application factory
:param config:
:param app_name:
:param blueprints:
:return:
"""
if not blueprints:
blueprints = DEFAULT_BLUEPRINTS
else:
blueprints = blueprints + DEFAULT_BLUEPRINTS
if no... | 28,815 |
def extract_tag(inventory, url):
"""
extract data from sphinx inventory.
The extracted datas come from a C++ project
documented using Breathe. The structure of the inventory
is a dictionary with the following keys
- cpp:class (class names)
- cpp:function (functions or class methods)... | 28,816 |
def strip_parens(s):
"""Strip parentheses around string"""
if not s:
return s
if s[0] == "(" and s[-1] == ")":
return strip_parens(s[1:-1])
else:
return s | 28,817 |
def custom_eval(node, value_map=None):
"""
for safely using `eval`
"""
if isinstance(node, ast.Call):
values = [custom_eval(v) for v in node.args]
func_name = node.func.id
if func_name in {"AVG", "IF"}:
return FUNCTIONS_MAP[func_name](*values)
elif func_name i... | 28,818 |
def validate_dict(input,validate):
"""
This function returns true or false if the dictionaries pass regexp
validation.
Validate format:
{
keyname: {
substrname: "^\w{5,10}$",
subintname: "^[0-9]+$"
}
}
Validates that keyname exists, and that it contains a substrname
that is 5-10 word characters, an... | 28,819 |
def run(app=None, host='0.0.0.0', port=8080, cam=None):
""" サーバー起動用関数
app: アプリケーション機能拡張用オブジェクト exec()メソッドが必要
host: 待機するIPアドレス
port: 待機するポート
cam: mjpeg_server用カメラオブジェクト start(), stop(), capture() メソッドが必要
"""
global _application
global _server
_application = app
_server = HTTPServe... | 28,820 |
def build_windows_and_pods_from_events(backpressure_events, window_width_in_hours=1) -> (list, list):
"""
Generate barchart-friendly time windows with counts of backpressuring durations within each window.
:param backpressure_events: a list of BackpressureEvents to be broken up into time windows
:param... | 28,821 |
def package_search(api_url, org_id=None, params=None, start_index=0, rows=100, logger=None, out=None):
"""
package_search: run the package_search CKAN API query, filtering by org_id, iterating by 100, starting with 'start_index'
perform package_search by owner_org:
https://data.ioos.us/api/3/action/pack... | 28,822 |
def get_reduction(n_components=None, seed=4242) -> Iterable[
Tuple[str, "sklearn.base.TransformerMixin", int]]:
"""
Get benchmark reduction algorithms
"""
# Note: FA rotation requires sklearn version > 0.24
import sklearn
assert tuple(map(int, sklearn.__version__.split('.'))) >= (0, 24)
... | 28,823 |
def write_inline_statistics(inline_file_path, inline_statistics, compilation):
"""write inline statistic into file"""
csv_writer = csv.writer(open(inline_file_path, "w", newline=""))
for i in range(len(compilation)):
line = [compilation[i]] + inline_statistics[i]
csv_writer.writerow(line) | 28,824 |
def voigt_fit(prefix,x,slice,c,vary):
"""
This function fits a voigt to a spectral slice. Center value can be set to constant or floated, everything else is floated.
Parameters:
prefix: prefix for lmfit to distinguish variables during multiple fits
x: x values to use in fit
slice: slice ... | 28,825 |
def add_tags(obj, tags):
"""
:param obj: Maya object to add string attributes to.
:param tags: dict{'Region': 'Arm', 'Side': 'R', 'Type': 'IK'}
"""
for key in tags.keys():
if not obj.hasAttr(key):
obj.addAttr(key, type='string', keyable=False)
obj.setAttr(key, tags[ke... | 28,826 |
def turn_coordinates_into_list_of_distances(list_of_coordinates: List[tuple]):
"""
Function to calculate the distance between coordinates in a list. Using the
'great_circle' for measuring here, since it is much faster (but less precise
than 'geodesic').
Parameters
----------
list_of_coordin... | 28,827 |
def getPileupDatasetSizes(datasets, phedexUrl):
"""
Given a list of datasets, find all their blocks with replicas
available, i.e., blocks that have valid files to be processed,
and calculate the total dataset size
:param datasets: list of dataset names
:param phedexUrl: a string with the PhEDEx ... | 28,828 |
def convertpo(inputpofile, outputpotfile, template, reverse=False):
"""reads in inputpofile, removes the header, writes to outputpotfile."""
inputpo = po.pofile(inputpofile)
templatepo = po.pofile(template)
if reverse:
swapdir(inputpo)
templatepo.makeindex()
header = inputpo.header()
... | 28,829 |
def _test_get_atoms(atom_factory, atoms):
"""
Test :meth:`.AtomFactory.get_atoms`.
Parameters
----------
atom_factory : :class:`.AtomFactory`
The atom factory to test.
atoms : :class:`tuple` of :class:`.Atom`
The atoms which should be created.
Returns
-------
None ... | 28,830 |
def do_fk5(l, b, jde):
"""[summary]
Parameters
----------
l : float
longitude
b : float
latitude
jde : float
Julian Day of the ephemeris
Returns
-------
tuple
tuple(l,b)
"""
T = (jde - JD_J2000) / CENTURY
lda = l - deg2rad(1.397)*T - deg2... | 28,831 |
def test_construct_many_to_one_kwargs():
"""
GIVEN artifacts for a many to one relationship with kwargs
WHEN construct is called with the artifacts
THEN a many to one relationship with kwargs is returned.
"""
artifacts = artifacts_types.ManyToOneRelationshipPropertyArtifacts(
type=types.... | 28,832 |
def command_norm_yaml(ns):
"""Run the norm_yaml command."""
parent_dir = common.YAML_DIR
paths = ns_to_paths(ns, parent_dir=parent_dir, ext='.yaml')
for path in paths:
common.normalize_yaml(path) | 28,833 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.8 ** (epoch // 1))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | 28,834 |
def get_defaults(module, *args):
"""
Find an internal defaults data file, load it using YAML, and return the resulting
dictionary.
Takes the dot-separated module path (e.g. "abscal.wfc3.reduce_grism_extract"), splits
off the last item (e.g. ["abscal.wfc3", "reduce_grism_extract"]), adds ".yam... | 28,835 |
def register_rnaseq(rna_seq_files, transaction):
"""Registers RNAseq experiment raw data in openBIS.
The list must contain two elements, following the naming convention ``r'.*tumor_rna[1,2]{1}.fastq.gz'``.
Both files must additionally contain the same QBiC sample code in order to get registered.
Args:... | 28,836 |
def publish(dry_run=False):
""" POST /repos/:owner/:repo/releases
https://developer.github.com/v3/repos/releases/#create-a-release
"""
# dynamic import to allow the other commands to run without requests
import requests
# get gihub config. If not set -> POST will fail, developer wi... | 28,837 |
def get(using=None):
"""Return a browser launcher instance appropriate for the environment."""
if _tryorder is None:
with _lock:
if _tryorder is None:
register_standard_browsers()
if using is not None:
alternatives = [using]
else:
alternatives = _tryor... | 28,838 |
def _bin_to_long(x):
"""
Convert a binary string into a long integer
This is a clever optimization for fast xor vector math
"""
return int(binascii.hexlify(x), 16) | 28,839 |
def update_book(username, book_id, data):
"""Update book data"""
cursor, conn = db_sql.connect('books.db')
keys = list(data.keys())
sql = ("UPDATE " + username + " SET " + " = ?, ".join(keys) +
" = ? WHERE _id = ?")
temp_list = []
for key in keys:
temp_list.append(data[key])
... | 28,840 |
def test_that_peek_returns_the_next_value(q_20):
"""Will test that the peek method returns the next value, the next to be dequeued."""
for num in range(20):
peek = q_20.peek()
dequeued = q_20.dequeue()
assert peek == dequeued | 28,841 |
def score_retrievals(label, retrievals):
"""
Evaluating the current retrieval experiment
Args:
-----
label: string
label corresponding to the query
retrivals: list
list of strings containing the ranked labels corresponding to the retrievals
tot_labels: integer
number ... | 28,842 |
def default_add_one_res_2_all_res(one_res: list, all_res: list) -> list:
"""
默认函数1: one_res 增加到all_res
:param one_res:
:param all_res:
:return:
"""
for i in one_res:
for j in i:
all_res.append(j)
return all_res | 28,843 |
def search_gene(search_string: str, **kwargs) -> Iterable[Gene]:
""" Symbols have been separated into search_gene_symbol - this returns Gene objects """
CONSORTIUM_REGEX = {
r"(ENSG\d+)": AnnotationConsortium.ENSEMBL,
r"Gene:(\d+)": AnnotationConsortium.REFSEQ,
r"GeneID:(\d+)": Annotati... | 28,844 |
def get_steam_libraries():
"""Returns list of found Steam library folders."""
found_libraries = []
if os.path.isdir(STEAM_INSTALL_DIR + '/steamapps/common'):
found_libraries.append(STEAM_INSTALL_DIR)
libraries_config = {}
if LIBRARY_FOLDERS_FILE:
libraries_config = vdf.load(open(LIB... | 28,845 |
def detect_wings_simple(img, pixel_size=1,
ds=2, layers=2, thresh_window=1.8e3,
minarea=0.5e6, maxarea=2e6, minsolidity=.6,
minaspect=.3, plot=False, threshold_fun=None):
"""
simple wing detection via adaptive thresholding and some filterin... | 28,846 |
def check_logged(request):
"""Check if user is logged and have the permission."""
permission = request.GET.get('permission', '')
if permission:
has_perm = request.user.has_perm(permission)
if not has_perm:
msg = (
"User does not have permission to exectute this ac... | 28,847 |
def _deprecated_configs(agentConfig):
""" Warn about deprecated configs
"""
deprecated_checks = {}
deprecated_configs_enabled = [v for k, v in OLD_STYLE_PARAMETERS if len([l for l in agentConfig if l.startswith(k)]) > 0]
for deprecated_config in deprecated_configs_enabled:
msg = "Configuring... | 28,848 |
def os_link(source, link_name):
"""Add support for os.link() on Windows."""
if sys.platform == 'win32':
if not ctypes.windll.kernel32.CreateHardLinkW(
unicode(link_name), unicode(source), 0):
raise OSError()
else:
os.link(source, link_name) | 28,849 |
def check_number_of_calls(object_with_method, method_name, maximum_calls, minimum_calls=1, stack_depth=2):
"""
Instruments the given method on the given object to verify the number of calls to the method is
less than or equal to the expected maximum_calls and greater than or equal to the expected minimum_ca... | 28,850 |
def strict_transport_security(reqs: dict, expectation='hsts-implemented-max-age-at-least-six-months') -> dict:
"""
:param reqs: dictionary containing all the request and response objects
:param expectation: test expectation
hsts-implemented-max-age-at-least-six-months: HSTS implemented with a max ag... | 28,851 |
def _get_span(succ, name, resultidx=0, matchidx=0, silent_fail=False):
"""
Helper method to return the span for the given result index and name, or None.
Args:
succ: success instance
name: name of the match info, if None, uses the entire span of the result
resultidx: index of the re... | 28,852 |
def plot_ft(fns=None, s=False, o=None, xd=False, yd=False, o_fmt='png',
dpi=300, in_fmt='mat', **kwargs):
"""
Plot the fourier spectrum of the data.
Can be useful if you have mystery data of unknown frequency.
"""
plot.plot(fns, xd=xd, yd=yd, s=s, o=o, ftype=o_fmt, dpi=dpi,
... | 28,853 |
def gen_k_arr(K, n):
"""
Arguments:
K {int} -- [apa numbers]
n {int} -- [trial numbers]
"""
def random_sel(K, trial=200):
count_index = 0
pool = np.arange(K)
last = None
while count_index < trial:
count_index += 1
random.shuffle(po... | 28,854 |
def tau_data(spc_dct_i,
spc_mod_dct_i,
run_prefix, save_prefix, saddle=False):
""" Read the filesystem to get information for TAU
"""
# Set up all the filesystem objects using models and levels
pf_filesystems = filesys.models.pf_filesys(
spc_dct_i, spc_mod_dct_i, run_p... | 28,855 |
def list_container_registries() -> None:
"""List all available container registries from service."""
service = Repository().get_service()
cli_utils.title("Container registries:")
cli_utils.print_table(
cli_utils.format_component_list(service.container_registries)
) | 28,856 |
def get_atten(log, atten_obj):
"""Get attenuator current attenuation value.
Args:
log: log object.
atten_obj: attenuator object.
Returns:
Current attenuation value.
"""
return atten_obj.get_atten() | 28,857 |
def lfs_hsm_remove(log, fpath, host=None):
"""
HSM remove
"""
command = ("lfs hsm_remove %s" % (fpath))
extra_string = ""
if host is None:
retval = utils.run(command)
else:
retval = host.sh_run(log, command)
extra_string = ("on host [%s]" % host.sh_hostname)
if re... | 28,858 |
def area_under_curve_score(table,scoring_function):
"""Takes a run and produces the total area under the curve until the end of the run.
mean_area_under_curve_score is probably more informative."""
assert_run(table)
scores = get_scores(table,scoring_function)
return np.trapz(scores) | 28,859 |
def read_key_value(file):
"""支持注释,支持中文"""
return_dict = {}
lines = readlines(file)
for line in lines:
line = line.strip().split(':')
if line[0][0] == '#':
continue
key = line[0].strip()
value = line[1].strip()
return_dict[key] = value
return return... | 28,860 |
def binarize_image(image):
"""Binarize image pixel values to 0 and 255."""
unique_values = np.unique(image)
if len(unique_values) == 2:
if (unique_values == np.array([0., 255.])).all():
return image
mean = image.mean()
image[image > mean] = 255
image[image <= mean] = ... | 28,861 |
def LineMatcher_fixture(request: FixtureRequest) -> Type["LineMatcher"]:
"""A reference to the :class: `LineMatcher`.
This is instantiable with a list of lines (without their trailing newlines).
This is useful for testing large texts, such as the output of commands.
"""
return LineMatcher | 28,862 |
def Delay(opts, args):
"""Sleeps for a while
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the duration
the sleep
@rtype: int
@return: the desired exit code
"""
delay = float(args[0])
op = opcodes.OpTestDelay(duration=... | 28,863 |
def generatorObjectIds():
""" for multiple generator_object, each have a different id """
print("\nfor multiple generator_object, each have a different id ")
g1 = generate123()
g2 = generate123()
if g1 is not g2:
print("g1 is not g2")
print(f"g1: {g1}")
print(f"g1: {g2}") | 28,864 |
def ffs(x):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ffs.html
:param x: Argument.
:type x: int32
:rtype: int32
""" | 28,865 |
def logout():
""" Simply loading the logout page while logged in will log the user out """
logout_user()
return render_template(f"{app_name}/logout.html") | 28,866 |
def test_LeafConstructionError_upon_update():
"""Tests that a `LeafConstructionError` is raised if both `record` and `digest`
are provided as arguments to the `MerkleTree.update()` method
"""
t = MerkleTree()
with pytest.raises(LeafConstructionError):
t.update(
record='some rec... | 28,867 |
def deletebucket(bucket_choices):
"""
This function is used to delete the bucket/s in S3
"""
progressbar("Deleting Bucket")
bucketnames=bucket_choices['bucket']
try:
for bucketname in bucketnames:
s3.delete_bucket( Bucket=str(bucketname))
print("\n \n Bucke... | 28,868 |
def identify_larger_definition(
one: ObjectDefinition,
two: ObjectDefinition
) -> Dict[str, Any]:
"""Return the larger (in dimensions) of the two given definitions."""
if not one:
return two
if not two:
return one
# TODO Handle if one has a larger X but other has a larger Z
r... | 28,869 |
def duration_to_timedelta(obj):
"""Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600)
"""
matches = DURATION_PATTERN.search(obj)
matches = matches.groupdict(default="0")
matches = {k: int(v) for k, v in matches.items()}
return timedelta(**matc... | 28,870 |
async def create_mock_hlk_sw16_connection(fail):
"""Create a mock HLK-SW16 client."""
client = MockSW16Client(fail)
await client.setup()
return client | 28,871 |
def gc_collect():
"""Force jako many objects jako possible to be collected.
In non-CPython implementations of Python, this jest needed because timely
deallocation jest nie guaranteed by the garbage collector. (Even w CPython
this can be the case w case of reference cycles.) This means that __del__
... | 28,872 |
def inv_dist_weight(distances, b):
"""Inverse distance weight
Parameters
----------
distances : numpy.array of floats
Distances to point of interest
b : float
The parameter of the inverse distance weight. The higher, the
higher the influence of closeby stations... | 28,873 |
def _uniformly_named_arguments(captured_arguments):
"""Iterate the captured arguments as uniform name/value pairs."""
args, kwargs = captured_arguments
# For positional arguments, the name is 1-based index padded with
# leading zeroes to the length of the last index.
width = len(str(len(args)))
... | 28,874 |
def load_inferred_fishing(table, id_list, project_id, threshold=True):
"""Load inferred data and generate comparison data
"""
query_template = """
SELECT vessel_id, start_time, end_time, nnet_score FROM
TABLE_DATE_RANGE([{table}],
TIMESTAMP('{year}-01-01'), TIMESTAMP('{year}-12-31'... | 28,875 |
def is_optional(value: Any) -> CheckerReturn:
"""
It is a rather special validator because it never returns False and emits an exception
signal when the value is correct instead of returning True.
Its user should catch the signal to short-circuit the validation chain.
"""
if value is None:
... | 28,876 |
def cli(env):
"""List health check types."""
mgr = SoftLayer.LoadBalancerManager(env.client)
hc_types = mgr.get_hc_types()
table = formatting.KeyValueTable(['ID', 'Name'])
table.align['ID'] = 'l'
table.align['Name'] = 'l'
table.sortby = 'ID'
for hc_type in hc_types:
table.add_r... | 28,877 |
def test_tag_format(tmp_image):
"""test --tag-format"""
from exif2findertags.cli import cli
runner = CliRunner()
result = runner.invoke(
cli,
[
"--tag",
"Keywords",
"--tag-format",
"{TAG}={VALUE}",
"--verbose",
str(... | 28,878 |
def approximate_bounding_box_dyn_obstacles(obj: list, time_step=0) -> Union[
Tuple[list], None]:
"""
Compute bounding box of dynamic obstacles at time step
:param obj: All possible objects. DynamicObstacles are filtered.
:return:
"""
def update_bounds(new_point: np.ndarray, bounds: List[lis... | 28,879 |
def sky_spectrum_from_fibres_using_file(
rss_file,
fibre_list=[],
win_sky=151,
n_sky=0,
skyflat="",
apply_throughput=True,
correct_ccd_defects=False,
fix_wavelengths=False,
sol=[0, 0, 0],
xmin=0,
xmax=0,
ymin=0,
ymax=0,
verbose=True,
plot=True,
):
"""
... | 28,880 |
def binary_class_accuracy_score(y_pred, data):
"""LightGBM binary class accuracy-score function.
Parameters
----------
y_pred
LightGBM predictions.
data
LightGBM ``'Dataset'``.
Returns
-------
(eval_name, eval_result, is_higher_better)
``'eval_name'`` : string
... | 28,881 |
def win32_clipboard_get():
""" Get the current clipboard's text on Windows.
Requires Mark Hammond's pywin32 extensions.
"""
try:
import win32clipboard
except ImportError:
message = ("Getting text from the clipboard requires the pywin32 "
"extensions: http://source... | 28,882 |
def open_add_folder_dialog(*args):
"""
Set folder name entry with clipboard contents,
Start dialog,
when done hide it.
"""
folder_name = __.Builder.get_object('folder_name')
clipboard_content = __.Jimmy.receive()
folder_name.set_text(clipboard_content)
__.folder_dialog = __.Builde... | 28,883 |
def is_prime(n):
"""Given an integer n, return True if n is prime and False if not.
"""
return True | 28,884 |
def path_to_newname(path, name_level=1):
"""
Takes one path and returns a new name, combining the directory structure
with the filename.
Parameters
----------
path : String
name_level : Integer
Form the name using items this far back in the path. E.g. if
path = mydata/1234/... | 28,885 |
def run_command(state, config_file: str, tool: str, report: str = "console", scan_type: str = None) -> None:
"""
manually run a scan using given tool
aka
eze tools run safety --debug
"""
log_debug(
f"""Running scan:
=========================
tool: {tool}
report: {report}
sc... | 28,886 |
def mount_if_unmounted(drive_path):
""" Mount given drive path, if not mounted. """
filesystem_mount_cli = [
'sudo',
'mount', '-a'
]
if path.ismount(drive_path) == False:
print "Mounting filesystem .."
try:
check_output(filesystem_mount_cli)... | 28,887 |
def load_model_from_json(model_path=None, weights_path=None):
"""
load dataset and weights from file
input:
model_path path to the model file, should be json format
weights_path path to the weights file, should be HDF5 format
output:
Keras model
"""
# default model path
home_p... | 28,888 |
def update_parameters(parameters,grads,learning_rate,optimizer,beta1=0.9,beta2=0.999, epsilon=1e-8):
"""
Description:
Updates the neural networks parameters (weights, biases) based on the optomizer selected
Arguments:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | 28,889 |
def test_create_boot_session():
"""Test creating new boot session
"""
template_uuid = str(uuid.uuid4())
session_request = {"operation": "boot",
"templateUuid": template_uuid}
response = requests.post(BOOT_SESSION_URI, headers=HEADERS, verify=HTTPS_VERIFY,
... | 28,890 |
def get_request_file():
"""
Method to implement REST API call of GET on address /file
"""
try:
content_file = open("html/file_get.html", "r")
content = content_file.read()
except:
logging.info("Could not load source HTML file '%s'")
raise
return content | 28,891 |
def pytest_configure(config):
""" Create a log file if log_file is not mentioned in *.ini file"""
timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')
if not config.option.log_file:
log_file_name = "log_" + timestamp + ".log"
config.option.log_file = os.path.join(Config... | 28,892 |
def sock_merchant(arr: Iterable[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5])
6
"""
from collections import Counter
count = Counter(arr).values()
ret = sum(n // 2 for n in count)
return... | 28,893 |
def new_user_registration(email: str) -> dict:
"""Alert the CIDC admin mailing list to a new user registration."""
subject = "New User Registration"
html_content = (
f"A new user, {email}, has registered for the CIMAC-CIDC Data Portal ({ENV}). If you are a CIDC Admin, "
"please visit the a... | 28,894 |
def article_detail():
"""文章详情"""
id = request.form.get('id')
if id is None:
raise Exception('ARTICLE_NOT_EXIST')
article = Article.find(id)
if article is None:
raise Exception('ARTICLE_NOT_EXIST')
# 获取标签
if article.tags is None:
article.tags = []
else:
al... | 28,895 |
def add_state_names_column(my_df):
"""
Add a column of corresponding state names to a dataframe
Params (my_df) a DataFrame with a column called "abbrev" that has state abbreviations.
Return a copy of the original dataframe, but with an extra column.
"""
new_df = my_df.copy()
n... | 28,896 |
def list_subdir_paths(directory):
"""
Generates a list of subdirectory paths
:param directory: str pathname of target parent directory
:return: list of paths for each subdirectory in the target parent
directory
"""
subdir_paths = glob("{}/*/".format(directory))
return subdir_paths | 28,897 |
def random_replacement_(batch: torch.LongTensor, index: int, selection: slice, size: int, max_index: int) -> None:
"""
Replace a column of a batch of indices by random indices.
:param batch: shape: `(*batch_dims, d)`
the batch of indices
:param index:
the index (of the last axis) which ... | 28,898 |
def logic_method_with_bkg(plots_per_cycle, cycle_time, sigma_s=160, m=3, n=4):
"""
:param plots_per_cycle:
:param cycle_time:
:param sigma_s:
:param m:
:param n:
:return:
"""
N = plots_per_cycle.shape[0] # number of cycles
tracks = [] # ret
track_cnt = 0
# 取滑动窗口
s... | 28,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.