content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def find_connected_pattern(variables: List[str], triples: List[Dict[str, str]]) -> Tuple[Dict[str, str],int, Set[str]]:
"""Find the first pattern in a set of triples pattern connected to a set of variables"""
pos = 0
#print("fcp:"+str(variables))
for triple in triples:
tripleVars = get_vars(trip... | 5,315,900 |
def make_secure_val(val):
"""
Creates secure value using secret.
"""
return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) | 5,315,901 |
def make_segm_from_catalog(catalog_star,
bounds, estimate_radius,
mag_name='rmag', mag_limit=22,
obj_name='', band='G',
ext_cat=None, draw=True,
save=False, dir_name='./Measure'):
"... | 5,315,902 |
def check(
work_dir: Path = WORK_DIR_ARG,
setup_dirs: bool = typer.Option(False, help="Create target directories."),
):
"""
Check training and validation targets and report to user.
"""
report_target_lists(work_dir=work_dir)
if setup_dirs:
crack_train.train_directory_setup(work_dir=w... | 5,315,903 |
def get_forced_photometry_mp(table, ra_col_name, dec_col_name, surveys,
bands, apertures, fovs, image_folder_path, n_jobs=5,
auto_download=True,
verbosity=0):
"""Calculate forced photometry in multiprocessing mode.
This function work... | 5,315,904 |
def eval_epoch(val_loader, model, val_meter, cur_epoch, cfg, writer=None):
"""
Evaluate the model on the val set.
Args:
val_loader (loader): data loader to provide validation data.
model (model): model to evaluate the performance.
val_meter (ValMeter): meter instance to record and ca... | 5,315,905 |
def Any(x):
"""The Any type; can also be used to cast a value to type Any."""
return x | 5,315,906 |
def resource_name_for_resource_type(resource_type, row):
"""Return the resource name for the resource type.
Each returned row contains all possible changed fields. This function
returns the resource name of the changed field based on the
resource type. The changed field's parent is also populated but is not us... | 5,315,907 |
def compute_performance_metrics_binary(model, x, y, metric_names):
"""
Given a model (TensorFlow) and (x, y).
Compute accuracy, loss, True Positive, False Negative, False Positive, True Negative, Recall, Precision,
f1 score, Average Precision Recall, ROC AUC, and classification re... | 5,315,908 |
def set_global_seed(seed: int):
"""
Set global seed for reproducibility.
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True | 5,315,909 |
def to_yw7(text):
"""Convert html tags to yWriter 6/7 raw markup.
Return a yw6/7 markup string.
"""
# Clean up polluted HTML code.
text = re.sub('</*font.*?>', '', text)
text = re.sub('</*span.*?>', '', text)
text = re.sub('</*FONT.*?>', '', text)
text = re.sub('</*SPAN.*?>'... | 5,315,910 |
def decode_labels(mask, num_images=1, num_classes=21):
"""Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
A batch with num_im... | 5,315,911 |
def test_total_precipitation(first_smhi_forecast):
"""test"""
assert first_smhi_forecast.total_precipitation == 2.0 | 5,315,912 |
def get_base_url(hostname):
"""
Constructs the GitHub API url with the given hostname.
:param str hostname: Hostname to construct the API endpoint url.
:returns: None
:raises: None
"""
if hostname and hostname.startswith('http'):
return hostname
else:
return "https://{ho... | 5,315,913 |
def gauss_sqrt_cov_ft(karr: array, width: float = 1.0) -> array:
"""sqrt of FFT of KD Gaussian covariance matrix
Square root of Fourier transform of a covariance matrix that is a Gaussian
function of difference in position
Returns
-------
karr : (L1,L2,...,LK/2+1,1,K)
Array of vectors ... | 5,315,914 |
def get_qt_lineedit_suffix(gb, suffix):
"""Gets the line edit associated with a tab and suffix.
Args:
gb (QtWidgets.QGroupBox): Group box for the tab.
suffix (str): Text appended to UI element search query.
Returns:
QtWidgets.QLineEdit: LineEdit matching val_{tag}_{suffix}.
"""... | 5,315,915 |
def generate_costing_table(pyscf_mf,name='molecule',thresh_range=[0.0001],dE=0.001,chi=10,beta=20, use_kernel=True,no_triples=False):
""" Print a table to file for testing how various DF thresholds impact cost, accuracy, etc.
Args:
pyscf_mf - PySCF mean field object
name (str) - file will be sa... | 5,315,916 |
def show_login_signup_screen():
"""
Function to display the screen to allow for the user to login and signup.
"""
# Global variable declarations.
global grid
global player_username
global player_is_authenticated
# Set the grid to be the frame of the screen.
grid = [[0, 0, 0, 0,... | 5,315,917 |
def capture_output_to_file():
"""Capture stdout, and stderr"""
orig_stdout = sys.stdout
orig_stderr = sys.stderr
try:
sys.stdout = tempfile.SpooledTemporaryFile(mode="w+", suffix=".out")
sys.stderr = tempfile.SpooledTemporaryFile(mode="w+", suffix=".err")
yield (sys.stdout, sys.s... | 5,315,918 |
def fit_statmech_pseudo_rotors(Tlist, Cvlist, n_vib, n_rot, molecule=None):
"""
Fit `n_vib` harmonic oscillator and `n_rot` hindered internal rotor modes to
the provided dimensionless heat capacities `Cvlist` at temperatures `Tlist`
in K. This method assumes that there are enough heat capacity points
... | 5,315,919 |
def response_to_invalid_request(diameter_request,
origin_host,
origin_realm):
"""
Method used to respond to invalid Diameter request.
We define an invalid Diameter request by comparing its command code
with the ones that we have support fo... | 5,315,920 |
def lsi_model(tmp_corpus, temp_dict):
""" creates an latent semantic indexing model from
a corpus of words and a dictionary using gensim
Args:
tmp_corpus (list): a list of words from dict
temp_dict (Dictionary): a gensim Dictionary
Returns:
a list of word vectors that comprise ... | 5,315,921 |
def kmeanssample(X, k, nsample=0, **kwargs):
""" 2-pass kmeans, fast for large N:
1) kmeans a random sample of nsample ~ sqrt(N) from X
2) full kmeans, starting from those centres
"""
# merge w kmeans ? mttiw
# v large N: sample N^1/2, N^1/2 of that
# seed like sklearn ?
N, dim =... | 5,315,922 |
def plot_forward_selection_results(
forward_selection_dict, plot_feature_names=False,
bar_face_colour=DEFAULT_BAR_FACE_COLOUR,
bar_edge_colour=DEFAULT_BAR_EDGE_COLOUR,
bar_edge_width=DEFAULT_BAR_EDGE_WIDTH):
"""Plots bar graph with results of any forward-selection algorithm.
:pa... | 5,315,923 |
def get_real_resolution():
"""获取真实的分辨率"""
hDC = win32gui.GetDC(0)
# 横向分辨率
w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
# 纵向分辨率
h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
return w, h | 5,315,924 |
def yaml_filename():
"""
This methods returns a random filename for the tests to use for generating
a config file. After the test runs, this file will be deleted
:return: None
"""
with tempfile.TemporaryDirectory() as tmpdir:
yaml_filename = os.path.join(tmpdir, 'model_def_' + uuid.uuid4... | 5,315,925 |
def op_acot(x):
"""Returns the inverse cotangent of this mathematical object."""
return op_inv(op_atan(x)) | 5,315,926 |
def terminal_size():
"""
Get terminal size
Will return width and height
"""
if os_windows:
w = 80
h = 25
else:
h, w, hp, wp = struct.unpack(
'HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
struct.pack('HHHH', 0, 0, 0, 0)))
return... | 5,315,927 |
def sdc_pandas_series_groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False, observed=False):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.groupby
... | 5,315,928 |
def get_most_popular():
"""
Helper which retrieves most popular urls based on `redirects`(desc) and
`created_at`(desc)
"""
return Url.objects.order_by('-redirects', '-created_at') | 5,315,929 |
def p_decl_8(t): # optional data
"""declaration : type_specifier STAR IDENT"""
t[0] = OptData (t[1],t[3]) | 5,315,930 |
def eval_genomes(genomes, substrate, vd_environment, generation):
"""
The function to evaluate fitness of the entire population against test
visual descriminator environment using the provided substrate
configuration of the descriminatorANN
Arguments:
genomes: The list of genomes in... | 5,315,931 |
def cosine_similarities(a, b, transform):
"""
returns list of cosine similarities between lists of vectors
a and b. The z_score transformation is applied if transform == True
"""
a = numpy.stack(a)
b = numpy.stack(b)
#transform if requested
if transform:
print "transforming"
... | 5,315,932 |
def element_damage_nohitbox(raw_element, sharpness):
"""
Calculate elemental damage to a monster part with the given elemental
attack, the given sharpness, and the given monster elemental weakness.
Note that this is independent of the motion value of the attack.
"""
return (raw_element * Sharpne... | 5,315,933 |
def transaction_handler(instance):
"""Handler to cycle through existing transactions and check timers or prompt sending of PDUs
"""
while True:
gevent.sleep(0)
try:
# Loop through once to prioritize sending file directives
# Check is inactivity timer expired. Later ad... | 5,315,934 |
def getTabData(header, index):
"""Get the table data at index from above tables generator.
Expects the header string and the index of the table."""
tabStart = header.index('{', index) + 1 #start of the table, first letter after {.
tabEnd = header.index('}', tabStart) #last of the array.
return header[tabStart:tabE... | 5,315,935 |
def get_default_input_id():
"""gets default input device number
pygame.midi.get_default_input_id(): return default_id
Return the default device ID or -1 if there are no devices.
The result can be passed to the Input()/Ouput() class.
On the PC, the user can specify a default device by
setting ... | 5,315,936 |
def notebook_system_output():
"""Capture system-level stdout/stderr within a Jupyter Notebook shell.
Get a context manager that attempts to use `wurlitzer
<https://github.com/minrk/wurlitzer>`__ to capture system-level
stdout/stderr within a Jupyter Notebook shell, without affecting
normal operatio... | 5,315,937 |
def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in kw.items():
if f(v):
d[k] = v
return d | 5,315,938 |
def check_latest_deploy(package, region, requirements_hash):
"""
Args:
package: Name of package to query
region: region to query for
requirements_hash: hash of requirements.txt file
returns:
Boolean: False if requirements hash matches latest deployhed version (doesn't need de... | 5,315,939 |
def writeTimeSeries(e, labels, tsFile):
""" Write activity timeseries file
:param pandas.DataFrame e: Pandas dataframe of epoch data. Must contain
activity classification columns with missing rows imputed.
:param list(str) labels: Activity state labels
:param dict tsFile: output CSV filename
... | 5,315,940 |
def docker_images(docker_url, query):
"""Looking for local images.
:param docker_url: Docker base url
:param query: image name lookup
:type docker_url: str
:type query: str
:returns: all matching images
:rtype: set
"""
cli = Client(base_url=docker_url)
results = set()
images... | 5,315,941 |
def start():
"""
node is responsible for all the I2C communication b/w Arduino and ROS
"""
# uncomment below line for debug
# rospy.init_node("motors_velocity_commander", log_level=rospy.DEBUG)
rospy.init_node("motors_velocity_commander")
rospy.loginfo("I2C bus is opened")
motorsObj = k... | 5,315,942 |
def test_dir_colors(file_name):
"""Test that dirs are brightly colored."""
assert (
color_file(File.from_path(file_name), isdir=True)
== colorama.Style.BRIGHT
+ colorama.Fore.BLUE
+ file_name
+ colorama.Style.RESET_ALL
) | 5,315,943 |
def _generate_pathfinding_environment(
object_bounds_list: List[List[Dict[str, float]]],
source: Dict[str, float] = None,
target: Dict[str, float] = None,
save_path_plot_with_name: str = None
) -> Optional[Environment]:
"""Generate and return the pathfinding environment using the given list of
o... | 5,315,944 |
def action_fs_cluster_status(
compute_client, network_client, config, storage_cluster_id,
detail, hosts):
# type: (azure.mgmt.compute.ComputeManagementClient,
# azure.mgmt.network.NetworkManagementClient, dict, str, bool,
# bool) -> None
"""Action: Fs Cluster Status
:pa... | 5,315,945 |
def keyword_confirm(request, name=None):
"""."""
q_objects = Q()
q_objects.add(Q(target_species__icontains=name), Q.OR)
confirm_proteins = Association.objects.filter(q_objects)
confirm_proteins = _sorted_nicely(confirm_proteins, sort_key="name")
return render(
request,
"associat... | 5,315,946 |
def day_dropdown_widget(
data: Union["LogData", pd.DataFrame], callback: Optional[Callable] = None
) -> "ipywidgets.Dropdown":
"""Create dropdown widget to filter log data by a specific day.
Parameters
----------
data : :class:`~biopsykit.carwatch_logs.log_data.LogData` or :class:`~pandas.DataFrame... | 5,315,947 |
def pull(
git_examples_handler: GitExamplesHandler,
example_name: str,
force: bool,
version: str,
path: str,
branch: Optional[str],
) -> None:
"""Pull examples straight into your current working directory.
Add the flag --force or -f to redownload all the examples afresh.
Use the flag... | 5,315,948 |
def Main(args):
"""Allow other scripts to call this script with fake command-line args.
@param The commandline argument list
"""
parser = optparse.OptionParser(USAGE_STRING % '%prog' + HELP_STRING)
parser.add_option('--render_dir', dest='render_dir',
help = ('specify the locat... | 5,315,949 |
def is_node_valid(node: dict) -> bool:
"""
Returns True if the provided node contains a directive and token.
"""
result = False
if node:
if DIR in node and TOK in node:
result = True
return result | 5,315,950 |
def cmd_add_partition(argv):
"""
Create a new Glue partition.
Example: add_partition datalake usage --year=2019 --month=09
"""
db, table, kargs = parse_args(argv, this_fn().usage)
add_partition(db, table, kargs)
print('Partition added') | 5,315,951 |
def is_crawler(client_ip):
"""
:return: crawler or not
"""
data_dir = os.path.join(os.path.dirname(__file__), 'data')
udger = Udger(data_dir)
return True if udger.parse_ip(client_ip)['ip_classification_code'] == 'crawler' else False | 5,315,952 |
def pytz_version():
"""Return the version of pytz as a tuple."""
year, month = pytz.__version__.split('.')
return int(year), int(month) | 5,315,953 |
def fixup_partition_table(partitions: List[Any], sector_size=512) -> Tuple[List[Any], int]:
"""
Return fixed partition table so it can be really written to disk.
Also return total size of partition.
"""
start_offset = 0
if _sect(partitions[0].start, sector_size) < 2048:
start_offset = 20... | 5,315,954 |
def topological_sort(self):
"""
Returns:
List(int): Topological sort of vertices of a graph.
"""
topo_order = self.depth_first_search()[1]
position = [-1] * len(self.v)
for i, v in enumerate(topo_order):
position[v] = i
for u, v in self.e:
if positi... | 5,315,955 |
def encrypt(cover_image, secret_text, encrypt_method, password, destination):
"""Prepare and encrypt the secret in the cover image and save it
Keyword arguments:
cover_image -- PIL Image where the secret is to be embedded
secret_text -- ascii string of text
encrypt_method -- either LSB or EMD
password -- a passw... | 5,315,956 |
def cleanup_ntfs(
cluster: str,
headers_inc: str):
""" Module to cleanup NTFS policy"""
print("\n===================================================================")
print("\n Module to Cleanup the polices that were created\n")
vserver = input("Enter the svm name: ")
policy_n... | 5,315,957 |
def construct_start_stop_intervals(intron_intervals, d):
"""Splits a iterable of intervals into two parallel tuples of 2d bp intervals representing their start and stop"""
left_intervals = []
right_intervals = []
for i in intron_intervals:
left_intervals.append(ChromosomeInterval(i.chromosome, i... | 5,315,958 |
def region_growing(image,coordinate,number):
"""Give coordinate and size,return a region."""
# tmp_image store marks and rg_image store new image after region grow
nt = number
tmp_image = np.zeros_like(image)
rg_image = np.zeros_like(image)
image_shape = image.shape
x = coordinate[0]
y ... | 5,315,959 |
def mock_subprocess(case_tuple):
"""We perform several subprocess.check_output calls, but we want to only mock
one of them at a time. This function helps us do that.
:type case_tuple: tuple of SubprocessMock
:param case_tuple: See docstring for SubprocessMock
"""
def fn(inputs, **kwargs):
... | 5,315,960 |
async def test_field_from_unicode_with_empty_str(dummy_guillotina):
""" """
fhir_field = FhirField(
title="Organization resource",
resource_class="fhir.resources.organization.Organization",
required=False,
)
value = fhir_field.from_unicode("")
assert value is None | 5,315,961 |
def wait_for_job(res, ping_time=0.5):
"""
Blocks execution and waits for an async Forest Job to complete.
:param JobResult res: The JobResult object to wait for.
:param ping_time: The interval (in seconds) at which to ping the server.
:return: The completed JobResult
"""
while not res.is_do... | 5,315,962 |
def _retr():
"""retrieves a list of all connected spectrometers for all backends"""
params, ids = [], []
if not _running_on_ci():
csb_serials, psb_serials = set(), set()
for serials, backend in [(csb_serials, csb), (psb_serials, psb)]:
if backend is None:
continue... | 5,315,963 |
def get_individual_annotations(self, all=False, imported=True):
"""Returns a dict with non-empty individual annotations.
If `all` is true, also annotations with no value are included.
If `imported` is true, also include annotations defined in
imported ontologies.
"""
onto = self.namespace.onto... | 5,315,964 |
def test_simple_flow(
app, service, identity, name_full_data, example_affiliation
):
"""Test a simple vocabulary service flow."""
# Create it
item = service.create(identity, name_full_data)
id_ = item.id
# add dereferenced values
expected_data = deepcopy(name_full_data)
expected_data["a... | 5,315,965 |
def ninja_check(args, build_folder):
"""
Invoke ninja with check targets if they are present
:param args: The args variable generated by parse_parameters
:param build_folder: The build folder that ninja should be run in
:return:
"""
if args.check_targets:
ninja_check = ['ninja'] + ['... | 5,315,966 |
def numeric_type(param):
"""
Checks parameter type
True for float; int or null data; false otherwise
:param param: input param to check
"""
if ((type(param) == float or type(param) == int or param == None)):
return True
return False | 5,315,967 |
def _pre_aggregate_df(df,
dims,
aggregate_dimensions,
show_control,
ctrl_id,
sort_by=None,
auto_decide_control_vals=False,
auto_add_description=True):
"""Process a ... | 5,315,968 |
def RunDsymUtil(dsym_path_prefix, full_args):
"""Linker driver action for -Wcrl,dsym,<dsym-path-prefix>. Invokes dsymutil
on the linker's output and produces a dsym file at |dsym_file| path.
Args:
dsym_path_prefix: string, The path at which the dsymutil output should be
located.
full_args: list o... | 5,315,969 |
def search_data_start(file, identifier, encoding):
"""
Returns the line of an identifier for the start of the data in a file.
"""
if identifier is None:
return 0
search = open(file, encoding=encoding)
i = 1
for line in search:
if identifier in line:
search.close()... | 5,315,970 |
def save_article(article: Dict[str, any]) -> None:
"""글을 CSV 형태로 저장한다"""
cols = [
'article_id', 'start', 'end', 'answered', 'votes', 'category', 'title',
'content'
]
# 파일이 없으면 새로 만들고 칼럼 이름 저장
if not os.path.isfile(CSV_WHOLE):
with open(CSV_WHOLE, 'w', newline='', encoding='u... | 5,315,971 |
def test_id_k015_id_k015_v(mode, save_output, output_format):
"""
TEST :Identity-constraint Definition Schema Component : constraint
locating an element that is of simpleType/union
"""
assert_bindings(
schema="msData/identityConstraint/idK015.xsd",
instance="msData/identityConstraint... | 5,315,972 |
def p_sha1(secret, seed, sizes=()):
"""
Derive one or more keys from secret and seed.
(See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0)
Lengths of keys will match sizes argument
"""
full_size = 0
for size in sizes:
full_size += size
result = b''
accum = seed
while len(re... | 5,315,973 |
def skip_check():
""" Check if has environment variable to skip this actor checks """
if os.getenv('LEAPP_SKIP_CHECK_SIGNED_PACKAGES'):
reporting.report_generic(title='Skipped signed packages check',
severity='low',
summary='Signed packag... | 5,315,974 |
def get_workload(batch_size, num_classes=1000, image_shape=(3, 224, 224), dtype="float32"):
"""Get benchmark workload for mobilenet
Parameters
----------
batch_size : int
The batch size used in the model
num_classes : int, optional
Number of classes
image_shape : tuple, option... | 5,315,975 |
def delete_review(review_id):
"""
It allows the user to delete the review from the page
and automatically from the database as well.
Checks that the user deleting the review is the
creator of the review, as only the that user is allowed
to delete it's own content.
"""
review = mongo.db.... | 5,315,976 |
def quotient_mealy(mealy, node_relation=None, relabel=False, outputs={'loc'}):
"""Returns the quotient graph of ``G`` under the specified equivalence
relation on nodes.
Parameters
----------
mealy : NetworkX graph
The graph for which to return the quotient graph with the specified node
... | 5,315,977 |
def test_bad_categories():
"""
Test OHE checks
"""
hidden_layers = [{'units': 64, 'activation': 'relu', 'name': 'relu1'},
{'units': 64, 'activation': 'relu', 'name': 'relu2'}]
one_hot_categories = {'categorical': list('abc')}
feature_names = FEATURES.columns.tolist() + ['ca... | 5,315,978 |
def find_package_data(where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data`... | 5,315,979 |
def test_charge_history_month(
mocked_responses: aioresponses, cli_runner: CliRunner
) -> None:
"""It exits with a status code of zero."""
initialise_credential_store(include_account_id=True, include_vin=True)
fixtures.inject_get_charge_history(
mocked_responses, start="202011", end="202011", pe... | 5,315,980 |
def generate_log_probabilities() -> None:
"""
Converts the ngram frequency files into files which have an array of each ngram's log probability
Each ngram is converted into a number using base 26
Frequency files are from http://practicalcryptography.com/cryptanalysis/text-characterisation/quadgrams/
... | 5,315,981 |
def delete_function_concurrency(FunctionName=None):
"""
Removes a concurrent execution limit from a function.
See also: AWS API Documentation
Exceptions
Examples
The following example deletes the reserved concurrent execution limit from a function named my-function.
Expected Output:
... | 5,315,982 |
def test_get_character(next_character: Character, expected_character: Character) -> None:
"""Test illud.terminal.Terminal.get_character."""
standard_input_mock = MagicMock(StandardInput, __next__=lambda self: next_character)
with patch('illud.terminal.StandardInput', return_value=standard_input_mock):
... | 5,315,983 |
def perform_v1_search(khoros_object, endpoint, filter_field, filter_value, return_json=False, fail_on_no_results=False,
proxy_user_object=None):
"""This function performs a search for a particular field value using a Community API v1 call.
.. versionchanged:: 4.0.0
Introduced the `... | 5,315,984 |
def get_page_generator(s,max_items=0):
"""Get the generator that returns the Page objects
that we're interested in, from Site s.
"""
page_generator = s.allpages()
if(max_items>0):
page_generator.set_maximum_items(max_items)
return page_generator | 5,315,985 |
def get_num_in(profile, key_path):
"""Return the value pointed by the key path in the JSON profile."""
job = __get_job_obj(profile)
obj = job
for key in key_path:
obj = obj[key]
return obj | 5,315,986 |
def replace_lost_images(member):
"""
If the specified member has images (such as from dcimg.awalker) that have expired, attempts to locate other copies of them online.
Possible methods:
search logsoku member threads (probably requires special rules for each member though :/)
ask google ... | 5,315,987 |
def file_basename_no_extension(filename):
""" Returns filename without extension
>>> file_basename_no_extension('/home/me/file.txt')
'file'
>>> file_basename_no_extension('file')
'file'
"""
base = os.path.basename(filename)
name, extension = os.path.splitext(base)
return name | 5,315,988 |
def rl_modelrl_medium():
"""Small set for larger testing."""
hparams = rl_modelrl_base()
hparams.true_env_generator_num_steps //= 2
return hparams | 5,315,989 |
def test_wait_time_low():
"""
The wait time has an offset of 5 minutes from the 30 minute markers (5, 35) to
provide a buffer for information to be uploaded.
Test the number just above the lower indicator
"""
assert find_wait_time(6) == 29 | 5,315,990 |
def check_flow_information(flow, search_name, pos):
""" Try to find out the type of a variable just with the information that
is given by the flows: e.g. It is also responsible for assert checks.::
if isinstance(k, str):
k. # <- completion here
ensures that `k` is a string.
"""
... | 5,315,991 |
def _xauth():
"""Make sure processes in the container can connect to the x server
"Necessary so gazebo can create a context for OpenGL rendering (even headless)"""
if not XAUTH.exists():
DISPLAY = os.getenv("DISPLAY")
xauth_list = _cmd("xauth", "nlist", DISPLAY)
xauth_list = re.sub(b... | 5,315,992 |
def accuracy_measures(predictions, trues):
"""Accuracy measures for the predictions of the method vs the groundtruth.
Prints a confusion matrix, accuracy, misclassifcation rate, true positieve rate, false positive rate, specificity, precision, prevalence.
Returns the accuracy score, precision score, and rec... | 5,315,993 |
def startGC():
"""Start Globus Connect on working node
"""
print "-----Running Globus Connect------"
arg = ['sh', 'globusconnect', '-start']
print arg
subprocess.Popen(arg) | 5,315,994 |
def list_drivers():
"""
"""
ecode = 0
try:
drivers = archive.get_driver_list()
logger.info("Supported convertable drivers: " + str(drivers))
except Exception as err:
logger.error(utils.format_error_output(config, 'dbupgrade', {}, err))
if not ecode:
ecode... | 5,315,995 |
def infinite_infer_run():
""" Entry point of the lambda function"""
try:
# This cat-dog model is implemented as binary classifier, since the number
# of labels is small, create a dictionary that converts the machine
# labels to human readable labels.
model_type = 'classific... | 5,315,996 |
def segment_text_to_sentences(text_file, sentence_splitter):
""" Segment text into sentences. Text is provided by BRAT in .txt
file.
Args:
text_file (str): the full path to the BRAT .txt file.
sentence_splitter (spacy LM): SpaCy EN language model.
Returns:
... | 5,315,997 |
def get_folder_offset(folder_list, folder_name):
"""
Check whether there is already a folder named 'folder_name' and if so, increment a counter.
"""
isExists = False
# Check whether a folder with the same name already exists
for folder in folder_list:
if folder['title'] == fold... | 5,315,998 |
def get_coords_for_radius(radius):
""" Given a radius, will return x,y coordinates with x=y.
This is useful for plotting the relation between the undistorted and distorted radius.
"""
sq = radius**2;
coord = np.sqrt(sq / 2);
return coord, coord; | 5,315,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.