uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f99be62f1df520c6d4137e0f | train | function | def CheckLLVMVersion(llvm_mc):
version = subprocess.check_output([llvm_mc, '-version'])
m = re.search("^ LLVM version (\d)\.(\d)\.\d$", version.decode(), re.M)
major, minor = m.groups()
if int(major) < 3 or (int(major) == 3 and int(minor) < 8):
raise Exception("This script requires LLVM version 3.8 or high... | def CheckLLVMVersion(llvm_mc):
| version = subprocess.check_output([llvm_mc, '-version'])
m = re.search("^ LLVM version (\d)\.(\d)\.\d$", version.decode(), re.M)
major, minor = m.groups()
if int(major) < 3 or (int(major) == 3 and int(minor) < 8):
raise Exception("This script requires LLVM version 3.8 or higher.")
| correct.',
formatter_class = argparse.ArgumentDefaultsHelpFormatter)
result.add_argument('--llvm-mc', default='llvm-mc', help='Path to llvm-mc')
result.add_argument('--verbose', '-v', action='store_true')
return result.parse_args()
def CheckLLVMVersion(llvm_mc):
| 64 | 64 | 97 | 8 | 56 | Componolit/android_external_vixl | tools/verify_assembler_traces.py | Python | CheckLLVMVersion | CheckLLVMVersion | 127 | 132 | 127 | 127 | 358d95bd911bc56659ca530b340328e95fdc2172 | bigcode/the-stack | train |
e7fbbfab265ec8a06c09b8e6 | train | function | def BuildOptions():
result = argparse.ArgumentParser(
description = 'Use `llvm-mc` to check the assembler traces are correct.',
formatter_class = argparse.ArgumentDefaultsHelpFormatter)
result.add_argument('--llvm-mc', default='llvm-mc', help='Path to llvm-mc')
result.add_argument('--verbose', '-v', a... | def BuildOptions():
| result = argparse.ArgumentParser(
description = 'Use `llvm-mc` to check the assembler traces are correct.',
formatter_class = argparse.ArgumentDefaultsHelpFormatter)
result.add_argument('--llvm-mc', default='llvm-mc', help='Path to llvm-mc')
result.add_argument('--verbose', '-v', action='store_true')
... | @ encoding: [0x12,0x0f,0x6f,0x01]
The script will finally extract the encoding and compare it to what VIXL
generated.
"""
import argparse
import subprocess
import os
import re
import itertools
import types
def BuildOptions():
| 64 | 64 | 83 | 4 | 59 | Componolit/android_external_vixl | tools/verify_assembler_traces.py | Python | BuildOptions | BuildOptions | 118 | 124 | 118 | 118 | bbe60fb4f8cc3a4aed95a1829a2bfe19ab8199fa | bigcode/the-stack | train |
64b4b7c41da0e2e221da1ef2 | train | function | def VerifyInstructionsWithLLVMMC(llvm_mc, f, triple):
"""
Extract all instructions from `f`, feed them to `llvm-mc` and make sure it's
encoded them the same way as VIXL. `triple` allows us to specify either
"thumbv8" or "armv8".
"""
vixl_reference = ReadTrace(f.read())
vixl_instructions, vixl_encodings =... | def VerifyInstructionsWithLLVMMC(llvm_mc, f, triple):
| """
Extract all instructions from `f`, feed them to `llvm-mc` and make sure it's
encoded them the same way as VIXL. `triple` allows us to specify either
"thumbv8" or "armv8".
"""
vixl_reference = ReadTrace(f.read())
vixl_instructions, vixl_encodings = zip(*vixl_reference)
instructions = [
Convert... | the encoding.
For example:
[
("Clz eq r0 r0", ["0x10", "0x0f", "0x6f", "0x01"]),
("Clz eq r0 r1", ["0x11", "0x0f", "0x6f", "0x01"]),
("Clz eq r0 r2", ["0x12", "0x0f", "0x6f", "0x01"])
]
"""
pattern = re.compile(
"^ (?P<encoding>(:?0x[0-9a-f]{2}, )+0x[0-9a-f]{2}) // ... | 212 | 213 | 713 | 15 | 197 | Componolit/android_external_vixl | tools/verify_assembler_traces.py | Python | VerifyInstructionsWithLLVMMC | VerifyInstructionsWithLLVMMC | 346 | 405 | 346 | 346 | 43cc8913c4736d8d744dd27dd3b5da9cdb65b434 | bigcode/the-stack | train |
eee1b938a0de60aa84aeb607 | train | function | def replace_remote_file_func():
def copy_file_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(user_home, row[8], row[1])), (
os.path.join(simple_remote_path, row[1]))]
)
if (row[5] == "L" or
... | def replace_remote_file_func():
| def copy_file_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(user_home, row[8], row[1])), (
os.path.join(simple_remote_path, row[1]))]
)
if (row[5] == "L" or
row[6] == "F"):
simple_... | copy_dir_to_remote_func()
else:
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
copy_dir_to_remote_func()
# Replace remote file contents from local
def replace_remote_file_func():
| 64 | 64 | 170 | 7 | 56 | afhpayne/birdy | birdy.py | Python | replace_remote_file_func | replace_remote_file_func | 580 | 605 | 580 | 582 | 00d8b2b1be325d45756aec53a4239b53abf5c8cc | bigcode/the-stack | train |
132368787c490ff61de1eda8 | train | function | def replace_local_file_enc_func():
subprocess.run(
['rsync', '-p', '-t', '-E', '--progress', (
os.path.join(birdy_work, row[1])), (
os.path.join(user_home, row[8]))]
)
| def replace_local_file_enc_func():
| subprocess.run(
['rsync', '-p', '-t', '-E', '--progress', (
os.path.join(birdy_work, row[1])), (
os.path.join(user_home, row[8]))]
)
| ', '-u', '--delete', '--progress', (
os.path.join(birdy_work, row[1], '')), (
os.path.join(user_home, row[8], row[1], ''))]
)
# Replace local file from ENCRYPTED backup
def replace_local_file_enc_func():
| 64 | 64 | 57 | 7 | 56 | afhpayne/birdy | birdy.py | Python | replace_local_file_enc_func | replace_local_file_enc_func | 726 | 731 | 726 | 726 | 150394f02558e5ba9ad4194665b1020fa16b6150 | bigcode/the-stack | train |
0d7d61781c94127e87f0442c | train | function | def print_dolly_list_func():
print('{:<}'.format(
"Dolly Files\n"))
for c1,c2 in itertools.zip_longest(
key_dolly_pretty,
dolly_list,
fillvalue=""):
print('{:<6}{}'.format(
c1, c2))
| def print_dolly_list_func():
| print('{:<}'.format(
"Dolly Files\n"))
for c1,c2 in itertools.zip_longest(
key_dolly_pretty,
dolly_list,
fillvalue=""):
print('{:<6}{}'.format(
c1, c2))
| ('{:<35}'.format(
"\nSystem\n"))
for c1,c2 in itertools.zip_longest(
key_root_pretty,
root_list,
fillvalue=""):
print('{:<6}{:<30}'.format(
c1, c2))
def print_dolly_list_func():
| 64 | 64 | 66 | 7 | 57 | afhpayne/birdy | birdy.py | Python | print_dolly_list_func | print_dolly_list_func | 324 | 332 | 324 | 324 | 4ec1585a6fb61f95587c39195e9e34a5f7b207d5 | bigcode/the-stack | train |
c9cbcc63ebba57bafb0d9c43 | train | function | def make_local_safe_func():
simple_local_path = os.path.join(
user_home,
row[8])
subprocess.run(
['mkdir', '-p', simple_local_path]
)
simple_localsafe_path = os.path.join(
local_safe,
row[8],
row[10])
subprocess.run(
['mkdir', '-p', simple_loca... | def make_local_safe_func():
| simple_local_path = os.path.join(
user_home,
row[8])
subprocess.run(
['mkdir', '-p', simple_local_path]
)
simple_localsafe_path = os.path.join(
local_safe,
row[8],
row[10])
subprocess.run(
['mkdir', '-p', simple_localsafe_path]
)
if os.... | ("\nCopying... ", row[1])
replace_remote_dir_func()
def runseq_file_backup_func():
print("\nCopying... ", row[1])
replace_remote_file_func()
# RESTORE FUNCTIONS ----------------------------------------------------------|
# Copy the LOCAL target files to the local_safety folder in /tmp
def make_local_saf... | 70 | 70 | 236 | 6 | 63 | afhpayne/birdy | birdy.py | Python | make_local_safe_func | make_local_safe_func | 629 | 666 | 629 | 629 | 081aeb70da2259d369ed3167677edba9a251d8f1 | bigcode/the-stack | train |
06b157fa5c526de73fbade2b | train | function | def make_sorted_lists_keys_func():
key_enc = list(range(1, (1 + len(enc_list))))
for i in key_enc:
key_enc_pretty.append("[" + str(i) + "]")
key_unenc = list(range(50, (50 + len(unenc_list))))
for i in key_unenc:
key_unenc_pretty.append("[" + str(i) + "]")
key_dolly = list(range(10... | def make_sorted_lists_keys_func():
| key_enc = list(range(1, (1 + len(enc_list))))
for i in key_enc:
key_enc_pretty.append("[" + str(i) + "]")
key_unenc = list(range(50, (50 + len(unenc_list))))
for i in key_unenc:
key_unenc_pretty.append("[" + str(i) + "]")
key_dolly = list(range(100, (100 + len(dolly_list))))
fo... | .path.join(
row[8], row[1]))
fork_list.sort()
if 300 <= int(row[0]) < 400:
root_list.append(os.path.join(
row[7], row[8], row[1]))
root_list.sort()
def make_sorted_lists_keys_func():
| 64 | 64 | 209 | 7 | 57 | afhpayne/birdy | birdy.py | Python | make_sorted_lists_keys_func | make_sorted_lists_keys_func | 248 | 267 | 248 | 248 | 577cb0775209f850d98ddc0947f3465c71533677 | bigcode/the-stack | train |
7c6cce9f6a6bd45e31dd7b1f | train | function | def make_dicts_for_input_func():
key_1 = 1
key_50 = 50
key_100 = 100
key_200 = 200
key_300 = 300
for i in enc_list:
i = i.split("/")
try:
syslist_dict.update({key_1: i[1]})
except(IndexError):
syslist_dict.update({key_1: i[0]})
key_1 += 1
... | def make_dicts_for_input_func():
| key_1 = 1
key_50 = 50
key_100 = 100
key_200 = 200
key_300 = 300
for i in enc_list:
i = i.split("/")
try:
syslist_dict.update({key_1: i[1]})
except(IndexError):
syslist_dict.update({key_1: i[0]})
key_1 += 1
for i in unenc_list:
i... | ,
# key_fork_pretty,
# fork_list,
# fillvalue=""):
# print('{:<5}{:<30}{:<5}{:<30}{:<6}{:<30}{:<6}{}'.format(
# c1, c2, c3, c4, c5, c6, c7, c8))
# Make dictionaries to reference user input to backup items
def make_dicts_for_input_func():
| 93 | 93 | 313 | 8 | 84 | afhpayne/birdy | birdy.py | Python | make_dicts_for_input_func | make_dicts_for_input_func | 354 | 390 | 354 | 354 | 4f1c6ab8c966721b6b225c32211c9e5a061b24c5 | bigcode/the-stack | train |
f7cd64bc0cc773f1755220bf | train | function | def make_sorted_lists_func():
for row in system_list_pruned:
if int(row[0]) <= 99 and row[4] == "E":
enc_list.append(os.path.join(
row[8], row[1]))
enc_list.sort()
if int(row[0]) <= 99 and row[4] == "n":
unenc_list.append(os.path.join(
... | def make_sorted_lists_func():
| for row in system_list_pruned:
if int(row[0]) <= 99 and row[4] == "E":
enc_list.append(os.path.join(
row[8], row[1]))
enc_list.sort()
if int(row[0]) <= 99 and row[4] == "n":
unenc_list.append(os.path.join(
row[8], row[1]))
... | 100 <= int(row[0]) < 200:
system_list_dolly.append(row)
if 200 <= int(row[0]) < 300:
system_list_fork.append(row)
if 300 <= int(row[0]) < 400:
system_list_basic.append(row)
def make_sorted_lists_func():
| 68 | 68 | 229 | 6 | 62 | afhpayne/birdy | birdy.py | Python | make_sorted_lists_func | make_sorted_lists_func | 220 | 245 | 220 | 220 | cc1d96cd69452ab41fa21da41f8414d43839b1b5 | bigcode/the-stack | train |
d437928d264ee8b56cea539b | train | function | def prune_system_list_4backup_func():
def commit_to_list_func():
if os.path.isfile(item_path) or os.path.isdir(item_path):
if item_path not in system_list_pruned:
system_list_pruned.append(row)
for row in system_list_full:
if row[7] == "user_home":
ite... | def prune_system_list_4backup_func():
| def commit_to_list_func():
if os.path.isfile(item_path) or os.path.isdir(item_path):
if item_path not in system_list_pruned:
system_list_pruned.append(row)
for row in system_list_full:
if row[7] == "user_home":
item_path = os.path.join(
u... | with open(systemlist_src) as system_list:
reader = csv.reader(system_list, delimiter=',')
for row in itertools.islice(reader, 1, None, None):
system_list_full.append(row)
# Filters files not present on the system
def prune_system_list_4backup_func():
| 64 | 64 | 133 | 10 | 53 | afhpayne/birdy | birdy.py | Python | prune_system_list_4backup_func | prune_system_list_4backup_func | 135 | 157 | 135 | 137 | fff3d4e880b8ba84a150799e2b400ac18023bed4 | bigcode/the-stack | train |
b5fc0e5503f23b003eb8a1a0 | train | function | def replace_local_file_func():
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--progress', (
os.path.join(simple_remote_path, row[1])), (
os.pa... | def replace_local_file_func():
| simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--progress', (
os.path.join(simple_remote_path, row[1])), (
os.path.join(user_home, row[8], row[... | '-t', '-E', '-u', '--delete', '--progress', (
os.path.join(simple_remote_path, row[1], '')), (
os.path.join(user_home, row[8], row[1], ''))]
)
# Replace local file from backup
def replace_local_file_func():
| 64 | 64 | 97 | 6 | 57 | afhpayne/birdy | birdy.py | Python | replace_local_file_func | replace_local_file_func | 750 | 761 | 750 | 750 | 218d6e1a1e1b644193f042b704deea4eba978e22 | bigcode/the-stack | train |
aafb11c6851a02b714149b97 | train | function | def replace_local_dir_enc_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--delete', '--progress', (
os.path.join(birdy_work, row[1], '')), (
os.path.join(user_home, row[8], row[1], ''))]
)
| def replace_local_dir_enc_func():
| subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--delete', '--progress', (
os.path.join(birdy_work, row[1], '')), (
os.path.join(user_home, row[8], row[1], ''))]
)
| file.open(os.path.join(birdy_work, (row[1] + '.tar.bz2')), 'r:bz2')
tar.extractall(path=(os.path.join(birdy_work)))
tar.close()
# Replace local dir contents from ENCRYPTED backup
def replace_local_dir_enc_func():
| 64 | 64 | 74 | 7 | 56 | afhpayne/birdy | birdy.py | Python | replace_local_dir_enc_func | replace_local_dir_enc_func | 717 | 722 | 717 | 717 | 1619c0d37b8fd024f468088b5484dcb0331d351a | bigcode/the-stack | train |
946c91dc4825dc89a01820de | train | function | def create_tar_func():
tar = tarfile.open(os.path.join(birdy_work, (row[1] + '.tar.bz2')), 'w:bz2')
tar.add(os.path.join(user_home, row[8], row[1]), arcname=row[1])
tar.close()
| def create_tar_func():
| tar = tarfile.open(os.path.join(birdy_work, (row[1] + '.tar.bz2')), 'w:bz2')
tar.add(os.path.join(user_home, row[8], row[1]), arcname=row[1])
tar.close()
| remote_cloud,
row[9],
sysname,
row[8],
row[10])
subprocess.run(
['mkdir', '-p', simple_remote_path]
)
copy_items_to_safety_func()
# Create tar.bz2 archive of local file
def create_tar_func():
| 64 | 64 | 64 | 5 | 58 | afhpayne/birdy | birdy.py | Python | create_tar_func | create_tar_func | 497 | 500 | 497 | 497 | e5cbe8b5ed3b6c4a2e7f722e7083fb5e5571e97c | bigcode/the-stack | train |
32ff373959914e88df52df7c | train | function | def make_safety_dirs_func():
if os.path.isdir(back_safe):
shutil.rmtree(back_safe)
subprocess.run(['mkdir', '-p', back_safe])
if os.path.isdir(local_safe):
shutil.rmtree(local_safe)
subprocess.run(['mkdir', '-p', local_safe])
if os.path.isdir(birdy_work):
shutil.rmtree(birdy_... | def make_safety_dirs_func():
| if os.path.isdir(back_safe):
shutil.rmtree(back_safe)
subprocess.run(['mkdir', '-p', back_safe])
if os.path.isdir(local_safe):
shutil.rmtree(local_safe)
subprocess.run(['mkdir', '-p', local_safe])
if os.path.isdir(birdy_work):
shutil.rmtree(birdy_work)
subprocess.run(['mk... | ("/")
try:
syslist_dict.update({key_300: i[2]})
except(IndexError):
syslist_dict.update({key_300: i[1]})
key_300 += 1
# Create safety directories for local and remote files
def make_safety_dirs_func():
| 64 | 64 | 93 | 7 | 56 | afhpayne/birdy | birdy.py | Python | make_safety_dirs_func | make_safety_dirs_func | 394 | 403 | 394 | 394 | 424f6bc511d06e6801fad202a8d7f1b0126d7b70 | bigcode/the-stack | train |
4b8db73d5ed12d403880ae4c | train | function | def print_pruned_sorted_system_list_func():
os.system("clear")
print("\nChoose (i)ndividual files:\n")
print('{:<30}{:<}'.format(
"Encrypted", "Unencrypted\n"))
for c1, c2, c3, c4 in itertools.zip_longest(
key_enc_pretty,
enc_list,
key_unenc_pretty,
... | def print_pruned_sorted_system_list_func():
| os.system("clear")
print("\nChoose (i)ndividual files:\n")
print('{:<30}{:<}'.format(
"Encrypted", "Unencrypted\n"))
for c1, c2, c3, c4 in itertools.zip_longest(
key_enc_pretty,
enc_list,
key_unenc_pretty,
unenc_list,
fillvalue=""):
... | , c4))
print('{:<35}'.format(
"\nSystem\n"))
for c1,c2 in itertools.zip_longest(
key_root_pretty,
root_list,
fillvalue=""):
print('{:<6}{:<30}'.format(
c1, c2))
def print_pruned_sorted_system_list_func():
| 72 | 72 | 243 | 9 | 63 | afhpayne/birdy | birdy.py | Python | print_pruned_sorted_system_list_func | print_pruned_sorted_system_list_func | 293 | 321 | 293 | 293 | fd7de0a8fac0d82845e11cb2f3164553d56729fb | bigcode/the-stack | train |
a6bfbda718552cb21075d71f | train | function | def make_group_lists_func():
for row in system_list_pruned:
if int(row[0]) < 99:
system_list_basic.append(row)
if 100 <= int(row[0]) < 200:
system_list_dolly.append(row)
if 200 <= int(row[0]) < 300:
system_list_fork.append(row)
if 300 <= int(row[0]... | def make_group_lists_func():
| for row in system_list_pruned:
if int(row[0]) < 99:
system_list_basic.append(row)
if 100 <= int(row[0]) < 200:
system_list_dolly.append(row)
if 200 <= int(row[0]) < 300:
system_list_fork.append(row)
if 300 <= int(row[0]) < 400:
system_l... | row[8], (row[1] + ".tar.bz2.gpg"))
commit_to_list_func()
else:
item_path = os.path.join(
remote_sysname, row[7], row[8], row[1])
commit_to_list_func()
def make_group_lists_func():
| 64 | 64 | 98 | 6 | 58 | afhpayne/birdy | birdy.py | Python | make_group_lists_func | make_group_lists_func | 208 | 217 | 208 | 208 | 62e1d58a1c1a9f7d377a231ffd2bf8fb2969452c | bigcode/the-stack | train |
b73f4260d7cfa98de316cf28 | train | function | def prune_system_list_4restore_func():
def commit_to_list_func():
if os.path.isfile(item_path) or os.path.isdir(item_path):
if item_path not in system_list_pruned:
system_list_pruned.append(row)
for row in system_list_full:
if (row[7] == "user_home" and
... | def prune_system_list_4restore_func():
| def commit_to_list_func():
if os.path.isfile(item_path) or os.path.isdir(item_path):
if item_path not in system_list_pruned:
system_list_pruned.append(row)
for row in system_list_full:
if (row[7] == "user_home" and
row[4] == "n" and
row[5] == ... | _to_list_func():
if os.path.isfile(item_path) or os.path.isdir(item_path):
if item_path not in system_list_pruned:
system_list_pruned.append(row)
for row in system_list_full:
if row[7] == "user_home":
item_path = os.path.join(
user_home,
... | 139 | 139 | 464 | 10 | 128 | afhpayne/birdy | birdy.py | Python | prune_system_list_4restore_func | prune_system_list_4restore_func | 161 | 205 | 161 | 163 | 6fbffce9a16793bb09926f580cb777bd1dbf2eae | bigcode/the-stack | train |
1424d465a64bdcc6695eb69d | train | function | def replace_remote_dir_func():
def copy_dir_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(user_home, row[8], row[1], '')), (
os.path.join(simple_remote_path, row[1], ''))]
)
if row[5] == "L" or ... | def replace_remote_dir_func():
| def copy_dir_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(user_home, row[8], row[1], '')), (
os.path.join(simple_remote_path, row[1], ''))]
)
if row[5] == "L" or row[6] == "F":
simple_rem... | _gpg_to_remote_func()
else:
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
copy_gpg_to_remote_func()
# Replace remote dir contents from local
def replace_remote_dir_func():
| 64 | 64 | 171 | 7 | 56 | afhpayne/birdy | birdy.py | Python | replace_remote_dir_func | replace_remote_dir_func | 552 | 576 | 552 | 554 | 62f925f506ffe6da3553b6dfa590c16d2f45af1b | bigcode/the-stack | train |
89c4cb7452f477b2eaf39d14 | train | function | def runseq_file_backup_func():
print("\nCopying... ", row[1])
replace_remote_file_func()
| def runseq_file_backup_func():
| print("\nCopying... ", row[1])
replace_remote_file_func()
| create_tar_func()
print("Encrypting...")
enc_gpg_func()
print("Copying...\n")
replace_remote_gpg_func()
def runseq_dir_backup_func():
print("\nCopying... ", row[1])
replace_remote_dir_func()
def runseq_file_backup_func():
| 64 | 64 | 25 | 7 | 57 | afhpayne/birdy | birdy.py | Python | runseq_file_backup_func | runseq_file_backup_func | 622 | 624 | 622 | 622 | 013a42750d6290a8abcfb351a2d8cf1dcef9bdbb | bigcode/the-stack | train |
ad4138133c8f310ae60977ce | train | function | def runseq_enc_file_restore_func():
print("\nDecrypting... ", row[1])
dec_gpg_func()
print("\nExpanding...")
extract_tar_func()
print("\nCopying... ", row[1])
replace_local_file_enc_func()
| def runseq_enc_file_restore_func():
| print("\nDecrypting... ", row[1])
dec_gpg_func()
print("\nExpanding...")
extract_tar_func()
print("\nCopying... ", row[1])
replace_local_file_enc_func()
| 0)
def runseq_enc_dir_restore_func():
print("\nDecrypting... ", row[1])
dec_gpg_func()
print("\nExpanding...")
extract_tar_func()
print("\nCopying...\n")
replace_local_dir_enc_func()
def runseq_enc_file_restore_func():
| 64 | 64 | 57 | 8 | 56 | afhpayne/birdy | birdy.py | Python | runseq_enc_file_restore_func | runseq_enc_file_restore_func | 789 | 795 | 789 | 789 | ff65963997312be46f8a983a47386578fd45394a | bigcode/the-stack | train |
63984a3a69b7348316d8d54c | train | function | def get_alternate_sytems_func():
alt_list = os.listdir(remote_backup)
alt_list.sort()
print("Here's what's available...\n")
for item in alt_list:
print("\t" + item)
| def get_alternate_sytems_func():
| alt_list = os.listdir(remote_backup)
alt_list.sort()
print("Here's what's available...\n")
for item in alt_list:
print("\t" + item)
| (
['rsync', '-r', '-p', '-t', '-E', '-u', '--progress', (
os.path.join(simple_remote_path, row[1])), (
os.path.join(user_home, row[8], row[1]))]
)
def get_alternate_sytems_func():
| 64 | 64 | 46 | 8 | 56 | afhpayne/birdy | birdy.py | Python | get_alternate_sytems_func | get_alternate_sytems_func | 764 | 769 | 764 | 764 | 26897e9d9f462b1e767e24cf2da3781b5195bd27 | bigcode/the-stack | train |
67644bb53cca36817575861b | train | function | def replace_remote_gpg_func():
def copy_gpg_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(birdy_work, (row[1] + '.tar.bz2.gpg'))), (
os.path.join(simple_remote_path, (row[1] + '.tar.bz2.gpg')))]
... | def replace_remote_gpg_func():
| def copy_gpg_to_remote_func():
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '--progress', (
os.path.join(birdy_work, (row[1] + '.tar.bz2.gpg'))), (
os.path.join(simple_remote_path, (row[1] + '.tar.bz2.gpg')))]
)
if (row[5] == "L" or
... | os.path.join(birdy_work, (
row[1] + '.tar.bz2.gpg'))), '-r', pgp_recip, '--encrypt', (
os.path.join(birdy_work, (row[1] + '.tar.bz2')))])
# Move archive to remote directory
def replace_remote_gpg_func():
| 74 | 74 | 249 | 8 | 65 | afhpayne/birdy | birdy.py | Python | replace_remote_gpg_func | replace_remote_gpg_func | 513 | 548 | 513 | 515 | f0f0542efd47177e8e2d2a3d00cf071dd6df7eb5 | bigcode/the-stack | train |
dd2f6d1e00531ce763255209 | train | function | def enc_gpg_func():
subprocess.run(
['gpg', '--yes', '-o', (
os.path.join(birdy_work, (
row[1] + '.tar.bz2.gpg'))), '-r', pgp_recip, '--encrypt', (
os.path.join(birdy_work, (row[1] + '.tar.bz2')))])
| def enc_gpg_func():
| subprocess.run(
['gpg', '--yes', '-o', (
os.path.join(birdy_work, (
row[1] + '.tar.bz2.gpg'))), '-r', pgp_recip, '--encrypt', (
os.path.join(birdy_work, (row[1] + '.tar.bz2')))])
| , (row[1] + '.tar.bz2')), 'w:bz2')
tar.add(os.path.join(user_home, row[8], row[1]), arcname=row[1])
tar.close()
## Encrypt gpg file from tar.bz2 archive
def enc_gpg_func():
| 64 | 64 | 81 | 6 | 57 | afhpayne/birdy | birdy.py | Python | enc_gpg_func | enc_gpg_func | 504 | 509 | 504 | 504 | 6ab4f5fd502782ed53e66c89878ec8317749969f | bigcode/the-stack | train |
4fff585e7744f47b25f01f81 | train | function | def print_basic_list_func():
# os.system("clear")
print("\nList of (b)ackup candidates on this system:\n")
print('{:<35}{:<30}'.format(
"Encrypted", "Unencrypted\n"))
for c1,c2,c3,c4 in itertools.zip_longest(
key_enc_pretty,
enc_list,
key_unenc_pretty,
... | def print_basic_list_func():
# os.system("clear")
| print("\nList of (b)ackup candidates on this system:\n")
print('{:<35}{:<30}'.format(
"Encrypted", "Unencrypted\n"))
for c1,c2,c3,c4 in itertools.zip_longest(
key_enc_pretty,
enc_list,
key_unenc_pretty,
unenc_list,
fillvalue=""):
pr... | ork_pretty.append("[" + str(i) + "]")
key_root = list(range(300, (300 + len(root_list))))
for i in key_root:
key_root_pretty.append("[" + str(i) + "]")
def print_basic_list_func():
# os.system("clear")
| 64 | 64 | 183 | 13 | 51 | afhpayne/birdy | birdy.py | Python | print_basic_list_func | print_basic_list_func | 270 | 290 | 270 | 271 | 0e4f019a41e9d37e769a8f5f7d7ed9143ba6395a | bigcode/the-stack | train |
64c03e873cce8553317c9875 | train | function | def extract_tar_func():
tar = tarfile.open(os.path.join(birdy_work, (row[1] + '.tar.bz2')), 'r:bz2')
tar.extractall(path=(os.path.join(birdy_work)))
tar.close()
| def extract_tar_func():
| tar = tarfile.open(os.path.join(birdy_work, (row[1] + '.tar.bz2')), 'r:bz2')
tar.extractall(path=(os.path.join(birdy_work)))
tar.close()
| ])
run_decryption_func()
else:
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
run_decryption_func()
# Extract user file from tar.bz2 archive
def extract_tar_func():
| 64 | 64 | 55 | 5 | 58 | afhpayne/birdy | birdy.py | Python | extract_tar_func | extract_tar_func | 710 | 713 | 710 | 710 | 2aff7cb6408927b22d905b104db037405a660252 | bigcode/the-stack | train |
061c1bab0e5a8bbcccd56d0c | train | function | def runseq_enc_dir_restore_func():
print("\nDecrypting... ", row[1])
dec_gpg_func()
print("\nExpanding...")
extract_tar_func()
print("\nCopying...\n")
replace_local_dir_enc_func()
| def runseq_enc_dir_restore_func():
| print("\nDecrypting... ", row[1])
dec_gpg_func()
print("\nExpanding...")
extract_tar_func()
print("\nCopying...\n")
replace_local_dir_enc_func()
| n")
for item in alt_list:
print("\t" + item)
def more_choice_func():
more_choice = input("\nContinue? Y/n ")
if more_choice in ["Y", "y"]:
pass
else:
exit(0)
def runseq_enc_dir_restore_func():
| 64 | 64 | 54 | 8 | 56 | afhpayne/birdy | birdy.py | Python | runseq_enc_dir_restore_func | runseq_enc_dir_restore_func | 780 | 786 | 780 | 780 | a8991b090a5b69d9af5095a79bf21abb203e5438 | bigcode/the-stack | train |
8a00a2159db6547060878ebe | train | function | def more_choice_func():
more_choice = input("\nContinue? Y/n ")
if more_choice in ["Y", "y"]:
pass
else:
exit(0)
| def more_choice_func():
| more_choice = input("\nContinue? Y/n ")
if more_choice in ["Y", "y"]:
pass
else:
exit(0)
| _home, row[8], row[1]))]
)
def get_alternate_sytems_func():
alt_list = os.listdir(remote_backup)
alt_list.sort()
print("Here's what's available...\n")
for item in alt_list:
print("\t" + item)
def more_choice_func():
| 64 | 64 | 39 | 5 | 59 | afhpayne/birdy | birdy.py | Python | more_choice_func | more_choice_func | 772 | 777 | 772 | 772 | b473fdb8af507380f4964da20855de1e43c59c00 | bigcode/the-stack | train |
97d4356e75d9696e72c20bdf | train | function | def runseq_dir_backup_func():
print("\nCopying... ", row[1])
replace_remote_dir_func()
| def runseq_dir_backup_func():
| print("\nCopying... ", row[1])
replace_remote_dir_func()
| copy_file_to_remote_func()
def runseq_enc_backup_func():
print("\nCompressing... ", row[1])
create_tar_func()
print("Encrypting...")
enc_gpg_func()
print("Copying...\n")
replace_remote_gpg_func()
def runseq_dir_backup_func():
| 64 | 64 | 25 | 7 | 57 | afhpayne/birdy | birdy.py | Python | runseq_dir_backup_func | runseq_dir_backup_func | 617 | 619 | 617 | 617 | ec0d1daf89b5ddc25d20e5d1a7818c64a2e0dfc2 | bigcode/the-stack | train |
9cec79fa19a7ed37821b2f42 | train | function | def replace_local_dir_func():
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--delete', '--progress', (
os.path.join(simple_remote_path, row[1], '')), (
... | def replace_local_dir_func():
| simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
subprocess.run(
['rsync', '-r', '-p', '-t', '-E', '-u', '--delete', '--progress', (
os.path.join(simple_remote_path, row[1], '')), (
os.path.join(user_ho... | subprocess.run(
['rsync', '-p', '-t', '-E', '--progress', (
os.path.join(birdy_work, row[1])), (
os.path.join(user_home, row[8]))]
)
# Replace local dir contents from backup
def replace_local_dir_func():
| 64 | 64 | 104 | 6 | 57 | afhpayne/birdy | birdy.py | Python | replace_local_dir_func | replace_local_dir_func | 735 | 746 | 735 | 735 | 1c9509c27ee5e10b47a32d0007d28391a371d31c | bigcode/the-stack | train |
a3c9f225b1f8fca1c7151aff | train | function | def runseq_enc_backup_func():
print("\nCompressing... ", row[1])
create_tar_func()
print("Encrypting...")
enc_gpg_func()
print("Copying...\n")
replace_remote_gpg_func()
| def runseq_enc_backup_func():
| print("\nCompressing... ", row[1])
create_tar_func()
print("Encrypting...")
enc_gpg_func()
print("Copying...\n")
replace_remote_gpg_func()
| [8],
row[10])
copy_file_to_remote_func()
else:
simple_remote_path = os.path.join(
remote_cloud,
row[9],
sysname,
row[8],
row[10])
copy_file_to_remote_func()
def runseq_enc_backup_func():
| 64 | 64 | 51 | 7 | 57 | afhpayne/birdy | birdy.py | Python | runseq_enc_backup_func | runseq_enc_backup_func | 608 | 614 | 608 | 608 | d77d12ecedf912f4d774d4756205148c4db4733a | bigcode/the-stack | train |
5dbff611a95942b8d590c6c7 | train | function | def dec_gpg_func():
def run_decryption_func():
subprocess.run(
['gpg', '--yes', '-o', (
os.path.join(
birdy_work, (row[1] + '.tar.bz2'))), '--decrypt', (
os.path.join(
simple_remote_path, (row[1] + '.tar.bz... | def dec_gpg_func():
| def run_decryption_func():
subprocess.run(
['gpg', '--yes', '-o', (
os.path.join(
birdy_work, (row[1] + '.tar.bz2'))), '--decrypt', (
os.path.join(
simple_remote_path, (row[1] + '.tar.bz2.gpg')))]
)
... | ['rsync', '-p', '-t', '-E', (
os.path.join(
simple_local_path,
row[1])), (
os.path.join(
simple_localsafe_path,
row[1]))]
)
# Decrypt gpg and extract tar.bz2 file
def dec_gp... | 70 | 70 | 234 | 7 | 62 | afhpayne/birdy | birdy.py | Python | dec_gpg_func | dec_gpg_func | 670 | 706 | 670 | 672 | 3c3133a758e43c5c922a14c9667a5fc9a992dc7f | bigcode/the-stack | train |
21b0ebe355dde0eef9d4632f | train | function | def make_remote_safe_func():
def copy_items_to_safety_func():
if os.path.isfile(os.path.join(
simple_remote_path, (
row[1] +
".tar.bz2.gpg"))):
subprocess.run(
['rsync', '-p', '-t', '-E', (
os.path.join(
... | def make_remote_safe_func():
| def copy_items_to_safety_func():
if os.path.isfile(os.path.join(
simple_remote_path, (
row[1] +
".tar.bz2.gpg"))):
subprocess.run(
['rsync', '-p', '-t', '-E', (
os.path.join(
simple_remote_pat... | _dict.update({key_300: i[2]})
except(IndexError):
syslist_dict.update({key_300: i[1]})
key_300 += 1
# Create safety directories for local and remote files
def make_safety_dirs_func():
if os.path.isdir(back_safe):
shutil.rmtree(back_safe)
subprocess.run(['mkdir', '-p', back_... | 170 | 170 | 567 | 7 | 162 | afhpayne/birdy | birdy.py | Python | make_remote_safe_func | make_remote_safe_func | 408 | 493 | 408 | 410 | 51fe258599ef4cc01b6db541028e2ef59e5c8699 | bigcode/the-stack | train |
ba2d63a85e0e4605e91f6aa5 | train | function | def read_system_list_func():
with open(systemlist_src) as system_list:
reader = csv.reader(system_list, delimiter=',')
for row in itertools.islice(reader, 1, None, None):
system_list_full.append(row)
| def read_system_list_func():
| with open(systemlist_src) as system_list:
reader = csv.reader(system_list, delimiter=',')
for row in itertools.islice(reader, 1, None, None):
system_list_full.append(row)
| = row[5]
# fork = row[6]
# local_base = row[7]
# local_path = row[8]
# back_base = row[9]
# back_path = row[10]
# Make a python list from the CSV config
def read_system_list_func():
| 64 | 64 | 51 | 6 | 57 | afhpayne/birdy | birdy.py | Python | read_system_list_func | read_system_list_func | 127 | 131 | 127 | 127 | f543ce9fedee84240f45a02c26cb2e3b518c7dae | bigcode/the-stack | train |
d8af633fedb6d35eb3021d3e | train | class | class planetInfo():
def __init__(self,Radius, Orbit, Period, c):
SunRadius = 6955500.0*ScalingFactor
self.radius = Radius
self.orbit = Orbit
self.period = Period
self.planet = sphere(pos=vector((self.orbit + SunRadius), self.orbit ,0), radius=self.radius*ScalingFactor,color ... | class planetInfo():
| def __init__(self,Radius, Orbit, Period, c):
SunRadius = 6955500.0*ScalingFactor
self.radius = Radius
self.orbit = Orbit
self.period = Period
self.planet = sphere(pos=vector((self.orbit + SunRadius), self.orbit ,0), radius=self.radius*ScalingFactor,color = c)
return
... | from vpython import sphere, rate, vector, color
from scipy.constants import day
from math import pi, cos ,sin
from numpy import arange
ScalingFactor = 0.0025
class planetInfo():
| 46 | 64 | 116 | 4 | 41 | Vworri/Computational-Physics-Review | Planets.py | Python | planetInfo | planetInfo | 8 | 20 | 8 | 8 | be141d728a580b63f7331ec48f0fab05fa0bdb07 | bigcode/the-stack | train |
4da8a6dad43706341b7e3d38 | train | function | def pwd():
"""
Return the path to the current working directory.
"""
return os.getcwd()
| def pwd():
| """
Return the path to the current working directory.
"""
return os.getcwd()
| ():
"""
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd()
def pwd():
| 64 | 64 | 22 | 3 | 61 | ChrisCummins/format | labm8/py/fs.py | Python | pwd | pwd | 159 | 163 | 159 | 159 | 27956c447d7226c8d15dca84291fa5417998a405 | bigcode/the-stack | train |
b48b9a50e9726aec81c2af71 | train | function | def abspath(*components):
"""
Get an absolute file path.
Concatenate all components into an absolute path.
"""
return os.path.abspath(path(*components))
| def abspath(*components):
| """
Get an absolute file path.
Concatenate all components into an absolute path.
"""
return os.path.abspath(path(*components))
| components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
"""
_path = path(*components)
if not exists(_path):
raise File404(_path)
return _path
def abspath(*components):
| 64 | 64 | 36 | 6 | 57 | ChrisCummins/format | labm8/py/fs.py | Python | abspath | abspath | 87 | 93 | 87 | 87 | 614a0f16e4dca2f05dde2cb5bfc8de830343ee9b | bigcode/the-stack | train |
4e0ed37533138d840de37f6e | train | function | def AtomicWrite(
filename: typing.Union[str, pathlib.Path],
contents: bytes,
mode: int = 0o0666,
gid: int = None,
) -> None:
"""Create a file 'filename' with 'contents' atomically.
As in Write, 'mode' is modified by the umask. This creates and moves
a temporary file, and errors doing the above will be p... | def AtomicWrite(
filename: typing.Union[str, pathlib.Path],
contents: bytes,
mode: int = 0o0666,
gid: int = None,
) -> None:
| """Create a file 'filename' with 'contents' atomically.
As in Write, 'mode' is modified by the umask. This creates and moves
a temporary file, and errors doing the above will be propagated normally,
though it will try to clean up the temporary file in that case.
This is very similar to the prodlib function ... | for the specific language governing permissions and
# limitations under the License.
flags = os.O_WRONLY | os.O_TRUNC | os.O_CREAT
if not overwrite_existing:
flags |= os.O_EXCL
fd = os.open(filename, flags, mode)
try:
os.write(fd, contents)
finally:
os.close(fd)
if gid is not None:
os.cho... | 141 | 141 | 471 | 42 | 99 | ChrisCummins/format | labm8/py/fs.py | Python | AtomicWrite | AtomicWrite | 670 | 719 | 670 | 675 | ba0c71a90a20e0293bdcc8b8ed1f422ebd78a1a6 | bigcode/the-stack | train |
3455e00af559b8aec756ebbb | train | function | def cp(src, dst):
"""
Copy a file or directory.
If source is a directory, this recursively copies the directory
and its contents. If the destination is a directory, then this
creates a copy of the source in the destination directory with the
same basename.
If the destination already exists, this will at... | def cp(src, dst):
| """
Copy a file or directory.
If source is a directory, this recursively copies the directory
and its contents. If the destination is a directory, then this
creates a copy of the source in the destination directory with the
same basename.
If the destination already exists, this will attempt to overwrite... | ("foo", "bar")
>>> rmtrash("/home/labm8/file.txt")
Arguments:
*components (string[]): path to the file or directory.
"""
_path = path(*components)
if exists(_path):
send2trash(_path)
def cp(src, dst):
| 64 | 64 | 182 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | cp | cp | 370 | 399 | 370 | 370 | 4027e6fbd1d2dad24838a36687ce13d1a2e730fb | bigcode/the-stack | train |
8f7549a10734de0f4cd9abcb | train | function | @contextlib.contextmanager
def chdir(directory: typing.Union[str, pathlib.Path]) -> pathlib.Path:
"""A context manager which allows you to temporarily change working directory.
Args:
directory: The directory to change to.
Returns:
The directory which has been changed to.
Raises:
OSError: If the g... | @contextlib.contextmanager
def chdir(directory: typing.Union[str, pathlib.Path]) -> pathlib.Path:
| """A context manager which allows you to temporarily change working directory.
Args:
directory: The directory to change to.
Returns:
The directory which has been changed to.
Raises:
OSError: If the given directory does not exist.
NotADirectoryError: If the given path is a file.
"""
previo... | :
True if directory is empty, else False.
"""
for _, subdirs, files in os.walk(path(directory)):
if subdirs or files:
return False
return True
@contextlib.contextmanager
def chdir(directory: typing.Union[str, pathlib.Path]) -> pathlib.Path:
| 64 | 64 | 125 | 23 | 40 | ChrisCummins/format | labm8/py/fs.py | Python | chdir | chdir | 564 | 583 | 564 | 565 | c1c4cb585d8c45c042625b88edc411dbfa2f8d68 | bigcode/the-stack | train |
455b46c41fa13e2aec6048f7 | train | function | def lsdirs(root=".", **kwargs):
"""
Return only subdirectories from a directory listing.
Arguments:
root (str): Path to directory. Can be relative or absolute.
**kwargs: Any additional arguments to be passed to ls().
Returns:
list of str: A list of directory paths.
Raises:
OSErro... | def lsdirs(root=".", **kwargs):
| """
Return only subdirectories from a directory listing.
Arguments:
root (str): Path to directory. Can be relative or absolute.
**kwargs: Any additional arguments to be passed to ls().
Returns:
list of str: A list of directory paths.
Raises:
OSError: If root directory does not ex... | subdirectories.
paths = ls(root, abspaths=abspaths, recursive=False)
return labtypes.flatten([_expand_subdirs(file) for file in paths])
else:
# List directory contents.
return list(sorted(os.listdir(root)))
def lsdirs(root=".", **kwargs):
| 63 | 64 | 120 | 9 | 54 | ChrisCummins/format | labm8/py/fs.py | Python | lsdirs | lsdirs | 275 | 295 | 275 | 275 | 88d11e0942aa9064d18c4200dc9b91f68b6d1a92 | bigcode/the-stack | train |
7342b5fa24db2dfa043184cb | train | function | def files_from_list(*paths):
"""
Return a list of all file paths from a list of files or directories.
For each path in the input: if it is a file, return it; if it is a
directory, return a list of files in the directory.
Arguments:
paths (list of str): List of file and directory paths.
Returns:
... | def files_from_list(*paths):
| """
Return a list of all file paths from a list of files or directories.
For each path in the input: if it is a file, return it; if it is a
directory, return a list of files in the directory.
Arguments:
paths (list of str): List of file and directory paths.
Returns:
list of str: Absolute file... | components)
if not exists(_path):
raise Error("file '{}' not found".format(_path))
size = os.stat(_path).st_size
if human_readable:
return humanize.BinaryPrefix(size, "B")
else:
return size
def files_from_list(*paths):
| 64 | 64 | 172 | 7 | 56 | ChrisCummins/format | labm8/py/fs.py | Python | files_from_list | files_from_list | 518 | 542 | 518 | 518 | 178a34f9874f3b6976bc88e0e31e7cb8288c6983 | bigcode/the-stack | train |
728ec13ef145e8ac804ef4b6 | train | function | def cd(path):
"""
Change working directory.
Returns absolute path to new working directory.
"""
_cdhist.append(pwd()) # Push to history.
path = abspath(path)
os.chdir(path)
return path
| def cd(path):
| """
Change working directory.
Returns absolute path to new working directory.
"""
_cdhist.append(pwd()) # Push to history.
path = abspath(path)
os.chdir(path)
return path
| = os.path.realpath(parent)
if len(child_path) < len(parent_path):
return False
for i in range(len(parent_path)):
if parent_path[i] != child_path[i]:
return False
return True
# Directory history.
_cdhist = []
def cd(path):
| 63 | 64 | 52 | 4 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | cd | cd | 133 | 142 | 133 | 133 | 52c40e78703303c4726e1717871d5b12e15faaa4 | bigcode/the-stack | train |
6c17f45abe2ae9fa5e173277 | train | function | def du(*components, **kwargs):
"""
Get the size of a file in bytes or as a human-readable string.
Arguments:
*components (str[]): Path to file.
**kwargs: If "human_readable" is True, return a formatted string,
e.g. "976.6 KiB" (default True)
Returns:
int or str: If "human_readble" k... | def du(*components, **kwargs):
| """
Get the size of a file in bytes or as a human-readable string.
Arguments:
*components (str[]): Path to file.
**kwargs: If "human_readable" is True, return a formatted string,
e.g. "976.6 KiB" (default True)
Returns:
int or str: If "human_readble" kwarg is True, return str, else ... |
if not re.match(comment_line_re, line)
]
elif rstrip:
# No comments, and right strip results.
return [line.rstrip() for line in lines]
else:
# Just a good old-fashioned read!
return lines
def du(*components, **kwargs):
| 64 | 64 | 176 | 8 | 55 | ChrisCummins/format | labm8/py/fs.py | Python | du | du | 493 | 515 | 493 | 493 | 41a857d4fd8b94badfa0ff54ebd96c6544757002 | bigcode/the-stack | train |
ccce421038cd54ca99004766 | train | function | def exists(*components):
"""
Return whether a file exists.
"""
return os.path.exists(path(*components))
| def exists(*components):
| """
Return whether a file exists.
"""
return os.path.exists(path(*components))
| cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd()
def pwd():
"""
Return the path to the current working directory.
"""
return os.getcwd()
def exists(*components):
| 64 | 64 | 25 | 5 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | exists | exists | 166 | 170 | 166 | 166 | 76ef67188a2d49780fd71892f379734fd33346ba | bigcode/the-stack | train |
a9d379bdaf05d779114973c4 | train | function | def mkdir(*components, **kwargs):
"""
Make directory "path", including any required parents. If
directory already exists, do nothing.
"""
_path = path(*components)
if not isdir(_path):
os.makedirs(_path, **kwargs)
return _path
| def mkdir(*components, **kwargs):
| """
Make directory "path", including any required parents. If
directory already exists, do nothing.
"""
_path = path(*components)
if not isdir(_path):
os.makedirs(_path, **kwargs)
return _path
| Raises:
File404: if source does not exist.
IOError: in case of error.
"""
if not exists(src):
raise File404(src)
try:
shutil.move(src, dst)
except Exception as e:
raise IOError(str(e))
def mkdir(*components, **kwargs):
| 64 | 64 | 63 | 8 | 56 | ChrisCummins/format | labm8/py/fs.py | Python | mkdir | mkdir | 428 | 436 | 428 | 428 | 904c119f24cf30353b66df84ba05c17d8cc279ed | bigcode/the-stack | train |
3bfc0acfe7ff0b0931db4fdf | train | function | def basename(*components):
"""
Return the basename of a given file path.
"""
return os.path.basename(path(*components))
| def basename(*components):
| """
Return the basename of a given file path.
"""
return os.path.basename(path(*components))
| path(*components)
if not exists(_path):
raise File404(_path)
return _path
def abspath(*components):
"""
Get an absolute file path.
Concatenate all components into an absolute path.
"""
return os.path.abspath(path(*components))
def basename(*components):
| 64 | 64 | 28 | 5 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | basename | basename | 96 | 100 | 96 | 96 | e96cf25c3016014053a7e58a01fe44bb17ace3db | bigcode/the-stack | train |
f33fe7bf6482a177323e2c66 | train | function | def directory_is_empty(directory: pathlib.Path) -> bool:
"""Return if a directory is empty.
A directory which does not exist is considered empty (returns True). A
directory containing only subdirectories but no files is considered not empty
(returns False).
Args:
directory: The path of a directory.
R... | def directory_is_empty(directory: pathlib.Path) -> bool:
| """Return if a directory is empty.
A directory which does not exist is considered empty (returns True). A
directory containing only subdirectories but no files is considered not empty
(returns False).
Args:
directory: The path of a directory.
Returns:
True if directory is empty, else False.
"""... | (path):
ret.append(abspath(path))
elif isdir(path):
ret += [f for f in ls(path, abspaths=True, recursive=True) if isfile(f)]
else:
raise File404(path)
return ret
def directory_is_empty(directory: pathlib.Path) -> bool:
| 64 | 64 | 111 | 12 | 51 | ChrisCummins/format | labm8/py/fs.py | Python | directory_is_empty | directory_is_empty | 545 | 561 | 545 | 545 | 5f4e20f8fd8cf0317d80e6a96a2d92cb555372bf | bigcode/the-stack | train |
c507ecbd90703da5b329b7f8 | train | function | def rm(*components, **kwargs):
"""
Remove a file or directory.
If path is a directory, this recursively removes the directory and
any contents. Non-existent paths are silently ignored.
Supports Unix style globbing by default (disable using
glob=False). For details on globbing pattern expansion, see:
... | def rm(*components, **kwargs):
| """
Remove a file or directory.
If path is a directory, this recursively removes the directory and
any contents. Non-existent paths are silently ignored.
Supports Unix style globbing by default (disable using
glob=False). For details on globbing pattern expansion, see:
https://docs.python.org/2/lib... | .
Raises:
OSError: If root directory does not exist.
"""
paths = ls(root=root, **kwargs)
if isfile(root):
return paths
return [_path for _path in paths if isfile(path(root, _path))]
def rm(*components, **kwargs):
| 63 | 64 | 203 | 8 | 56 | ChrisCummins/format | labm8/py/fs.py | Python | rm | rm | 321 | 347 | 321 | 321 | 04590fbe75bb17104535b05b0609fbb6fbf9bbed | bigcode/the-stack | train |
8083e1bb4e7835b1ffc6d3c4 | train | function | def isdir(*components):
"""
Return whether a path exists, and is a directory.
"""
if components:
return os.path.isdir(path(*components))
else:
return False
| def isdir(*components):
| """
Return whether a path exists, and is a directory.
"""
if components:
return os.path.isdir(path(*components))
else:
return False
| False
>>> isexe("/not/a/real/path")
False
Returns:
bool: True if file is executable, else false.
"""
_path = path(*components)
return isfile(_path) and os.access(_path, os.X_OK)
def isdir(*components):
| 64 | 64 | 42 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | isdir | isdir | 204 | 211 | 204 | 204 | ca8aafc1103e05aa105e517787d39676dba6e7bb | bigcode/the-stack | train |
4ab8ccc0b7d77c45adb4673f | train | function | def ls(
root: typing.Union[str, pathlib.Path] = ".", abspaths=False, recursive=False,
):
"""
Return a list of files in directory.
Directory listings are sorted alphabetically. If the named
directory is a file, return it's path.
Examples:
>>> ls("foo")
["a", "b", "c"]
>>> ls("foo/a")
["foo... | def ls(
root: typing.Union[str, pathlib.Path] = ".", abspaths=False, recursive=False,
):
| """
Return a list of files in directory.
Directory listings are sorted alphabetically. If the named
directory is a file, return it's path.
Examples:
>>> ls("foo")
["a", "b", "c"]
>>> ls("foo/a")
["foo/a"]
>>> ls("foo", abspaths=True)
["/home/test/foo/a", "/home/test/foo/b", "/home/... | isexe("/home")
False
>>> isexe("/not/a/real/path")
False
Returns:
bool: True if file is executable, else false.
"""
_path = path(*components)
return isfile(_path) and os.access(_path, os.X_OK)
def isdir(*components):
"""
Return whether a path exists, and is a directory.
"""
if com... | 131 | 131 | 439 | 25 | 105 | ChrisCummins/format | labm8/py/fs.py | Python | ls | ls | 214 | 272 | 214 | 216 | 3ebba6991f1f354b56471cda6469f2003ab4d0e4 | bigcode/the-stack | train |
320c1ace7f061ceb4198f0b9 | train | function | def Read(filename: typing.Union[str, pathlib.Path]) -> str:
"""Read entire contents of file with name 'filename'."""
with open(filename) as fp:
return fp.read()
| def Read(filename: typing.Union[str, pathlib.Path]) -> str:
| """Read entire contents of file with name 'filename'."""
with open(filename) as fp:
return fp.read()
| .
with tempfile.TemporaryDirectory(prefix=prefix) as d:
os.chdir(d)
yield pathlib.Path(d)
# Return to previous working directory, if there was one.
if old_directory:
os.chdir(old_directory)
def Read(filename: typing.Union[str, pathlib.Path]) -> str:
| 64 | 64 | 41 | 15 | 49 | ChrisCummins/format | labm8/py/fs.py | Python | Read | Read | 616 | 619 | 616 | 616 | 3d5f4b2876044659169c6747d54f6fc887b4514d | bigcode/the-stack | train |
c7a7f611cf0f6aed60ebd7ae | train | function | @contextlib.contextmanager
def TemporaryWorkingDir(prefix: str = "phd_") -> pathlib.Path:
"""A context manager which provides a temporary working directory.
This creates an empty temporary directory, and changes the current working
directory to it. Once out of scope, the directory and all it's contents are
rem... | @contextlib.contextmanager
def TemporaryWorkingDir(prefix: str = "phd_") -> pathlib.Path:
| """A context manager which provides a temporary working directory.
This creates an empty temporary directory, and changes the current working
directory to it. Once out of scope, the directory and all it's contents are
removed.
Args:
prefix: A prefix for the temporary directory name.
Returns:
The ... | given path is a file.
"""
previous_directory = pathlib.Path.cwd()
os.chdir(str(directory))
try:
yield pathlib.Path(directory)
finally:
os.chdir(str(previous_directory))
@contextlib.contextmanager
def TemporaryWorkingDir(prefix: str = "phd_") -> pathlib.Path:
| 64 | 64 | 215 | 23 | 41 | ChrisCummins/format | labm8/py/fs.py | Python | TemporaryWorkingDir | TemporaryWorkingDir | 586 | 613 | 586 | 587 | 8ed42803ccc8732a55d4bebefdd6943a85dde9a1 | bigcode/the-stack | train |
bd448a1b0da86287e3d2aa8b | train | function | def Write(
filename: typing.Union[str, pathlib.Path],
contents: bytes,
overwrite_existing: bool = True,
mode: int = 0o0666,
gid: int = None,
) -> pathlib.Path:
"""Create a file 'filename' with 'contents', with the mode given in 'mode'.
The 'mode' is modified by the umask, as in open(2). If
'overwrite_... | def Write(
filename: typing.Union[str, pathlib.Path],
contents: bytes,
overwrite_existing: bool = True,
mode: int = 0o0666,
gid: int = None,
) -> pathlib.Path:
| """Create a file 'filename' with 'contents', with the mode given in 'mode'.
The 'mode' is modified by the umask, as in open(2). If
'overwrite_existing' is False, the file will be opened in O_EXCL mode.
An optional gid can be specified.
Args:
filename: the name of the file
contents: the data to writ... | prefix) as d:
os.chdir(d)
yield pathlib.Path(d)
# Return to previous working directory, if there was one.
if old_directory:
os.chdir(old_directory)
def Read(filename: typing.Union[str, pathlib.Path]) -> str:
"""Read entire contents of file with name 'filename'."""
with open(filename) as fp:
re... | 131 | 131 | 439 | 50 | 81 | ChrisCummins/format | labm8/py/fs.py | Python | Write | Write | 622 | 667 | 622 | 628 | 6cddf9506bed96f740ebe8aad5e3e3520b241339 | bigcode/the-stack | train |
a6d5901bcc409730720b23ae | train | function | def lsfiles(root: typing.Union[str, pathlib.Path] = ".", **kwargs):
"""
Return only files from a directory listing.
Arguments:
root (str): Path to directory. Can be relative or absolute.
**kwargs: Any additional arguments to be passed to ls().
Returns:
list of str: A list of file paths.
... | def lsfiles(root: typing.Union[str, pathlib.Path] = ".", **kwargs):
| """
Return only files from a directory listing.
Arguments:
root (str): Path to directory. Can be relative or absolute.
**kwargs: Any additional arguments to be passed to ls().
Returns:
list of str: A list of file paths.
Raises:
OSError: If root directory does not exist.
"""
p... | root directory does not exist.
"""
paths = ls(root=root, **kwargs)
if isfile(root):
return []
return [_path for _path in paths if isdir(path(root, _path))]
def lsfiles(root: typing.Union[str, pathlib.Path] = ".", **kwargs):
| 63 | 64 | 129 | 18 | 46 | ChrisCummins/format | labm8/py/fs.py | Python | lsfiles | lsfiles | 298 | 318 | 298 | 298 | a0e7a4d51622be3840ceabbafa957719a0134710 | bigcode/the-stack | train |
c8376358134955cf2fdacb67 | train | function | def path(*components):
"""
Get a file path.
Concatenate all components into a path.
"""
_path = os.path.join(*components)
_path = os.path.expanduser(_path)
return _path
| def path(*components):
| """
Get a file path.
Concatenate all components into a path.
"""
_path = os.path.join(*components)
_path = os.path.expanduser(_path)
return _path
| .timemachine.donotpresent",
".com.apple.timemachine.supported",
".DS_Store",
".sync.ffs_db",
".sync_timestamp.txt",
".VolumeIcon.icns",
".VolumeIcon.ico",
"autorun.inf",
]
)
def path(*components):
| 64 | 64 | 50 | 5 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | path | path | 56 | 65 | 56 | 56 | 1c65ab8ff384a265188e2fda5f696cf059d83463 | bigcode/the-stack | train |
43605077988021c8cafcbd3a | train | function | def mv(src, dst):
"""
Move a file or directory.
If the destination already exists, this will attempt to overwrite
it.
Arguments:
src (string): path to the source file or directory.
dst (string): path to the destination file or directory.
Raises:
File404: if source does not exist.
... | def mv(src, dst):
| """
Move a file or directory.
If the destination already exists, this will attempt to overwrite
it.
Arguments:
src (string): path to the source file or directory.
dst (string): path to the destination file or directory.
Raises:
File404: if source does not exist.
IOError: in case... | (src):
# Overwrite an existing directory.
if isdir(dst):
rm(dst)
shutil.copytree(src, dst)
elif isfile(src):
shutil.copy(src, dst)
else:
raise IOError("Source '{0}' not found".format(src))
def mv(src, dst):
| 64 | 64 | 117 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | mv | mv | 402 | 425 | 402 | 402 | dbb999cdf8fc480201a56e9f5b86916d60efa4da | bigcode/the-stack | train |
a09689dd220aa08683856214 | train | function | def must_exist(*components):
"""
Ensure path exists.
Arguments:
*components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
"""
_path = path(*components)
if not exists(_path):
raise File404(_path)
return _path
| def must_exist(*components):
| """
Ensure path exists.
Arguments:
*components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
"""
_path = path(*components)
if not exists(_path):
raise File404(_path)
return _path
| "autorun.inf",
]
)
def path(*components):
"""
Get a file path.
Concatenate all components into a path.
"""
_path = os.path.join(*components)
_path = os.path.expanduser(_path)
return _path
def must_exist(*components):
| 64 | 64 | 76 | 6 | 57 | ChrisCummins/format | labm8/py/fs.py | Python | must_exist | must_exist | 68 | 84 | 68 | 68 | 60171afba41321d5b84bb47400a85d02cd43d84c | bigcode/the-stack | train |
45fbd5c52aa696a437dd01fd | train | function | def rmtrash(*components):
"""
Move a file or directory to trash.
If file does not exist, nothing happens.
Examples:
>>> rmtrash("foo", "bar")
>>> rmtrash("/home/labm8/file.txt")
Arguments:
*components (string[]): path to the file or directory.
"""
_path = path(*components)
if exis... | def rmtrash(*components):
| """
Move a file or directory to trash.
If file does not exist, nothing happens.
Examples:
>>> rmtrash("foo", "bar")
>>> rmtrash("/home/labm8/file.txt")
Arguments:
*components (string[]): path to the file or directory.
"""
_path = path(*components)
if exists(_path):
send2trash(... | components)
glob = kwargs.get("glob", True)
paths = iglob(_path) if glob else [_path]
for file in paths:
if isfile(file):
os.remove(file)
elif exists(file):
shutil.rmtree(file, ignore_errors=False)
def rmtrash(*components):
| 64 | 64 | 92 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | rmtrash | rmtrash | 350 | 367 | 350 | 350 | b4dd5f21cf0c8ed10e373fb5e1e208bc8cd96dce | bigcode/the-stack | train |
577609191ca0b470120e8860 | train | function | def isfile(*components):
"""
Return whether a path exists, and is a file.
"""
return os.path.isfile(path(*components))
| def isfile(*components):
| """
Return whether a path exists, and is a file.
"""
return os.path.isfile(path(*components))
| return old
else:
return pwd()
def pwd():
"""
Return the path to the current working directory.
"""
return os.getcwd()
def exists(*components):
"""
Return whether a file exists.
"""
return os.path.exists(path(*components))
def isfile(*components):
| 64 | 64 | 31 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | isfile | isfile | 173 | 177 | 173 | 173 | 1be2ea861ccbada5ff8c7a969803262db45a0bfc | bigcode/the-stack | train |
f7d0ede8fd0f468fe03a18b5 | train | function | def cdpop():
"""
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd()
| def cdpop():
| """
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd()
| history.
_cdhist = []
def cd(path):
"""
Change working directory.
Returns absolute path to new working directory.
"""
_cdhist.append(pwd()) # Push to history.
path = abspath(path)
os.chdir(path)
return path
def cdpop():
| 64 | 64 | 64 | 4 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | cdpop | cdpop | 145 | 156 | 145 | 145 | e842a8383fae28e89520cbb51effbf1002afe017 | bigcode/the-stack | train |
bc71d1dd169613123974b618 | train | function | def mkopen(p, *args, **kwargs):
"""
A wrapper for the open() builtin which makes parent directories if needed.
"""
dir = os.path.dirname(p)
mkdir(dir)
return open(p, *args, **kwargs)
| def mkopen(p, *args, **kwargs):
| """
A wrapper for the open() builtin which makes parent directories if needed.
"""
dir = os.path.dirname(p)
mkdir(dir)
return open(p, *args, **kwargs)
| Make directory "path", including any required parents. If
directory already exists, do nothing.
"""
_path = path(*components)
if not isdir(_path):
os.makedirs(_path, **kwargs)
return _path
def mkopen(p, *args, **kwargs):
| 64 | 64 | 53 | 11 | 52 | ChrisCummins/format | labm8/py/fs.py | Python | mkopen | mkopen | 439 | 445 | 439 | 439 | 6b662a48f20a8e900190c38b6f48a4da085f486f | bigcode/the-stack | train |
c3d79d9a38fec6ed4f697755 | train | class | class Error(Exception):
pass
| class Error(Exception):
| pass
| filesystem interface.
"""
import contextlib
import os.path
import pathlib
import re
import shutil
import tempfile
import typing
from glob import iglob
from send2trash import send2trash
from labm8.py import humanize
from labm8.py import labtypes
class Error(Exception):
| 64 | 64 | 7 | 4 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | Error | Error | 31 | 32 | 31 | 31 | c8e1f8a5c317a0f0e168cf6f96d1b6bb4946a1a7 | bigcode/the-stack | train |
6cabf6160fe50384022e8027 | train | function | @contextlib.contextmanager
def TemporaryFileWithContents(contents: bytes, **kwargs):
"""A contextmanager that writes out a string to a file on disk.
This is useful whenever you need to call a function or command that expects a
file on disk with some contents that you have in memory. The context manager
abstrac... | @contextlib.contextmanager
def TemporaryFileWithContents(contents: bytes, **kwargs):
| """A contextmanager that writes out a string to a file on disk.
This is useful whenever you need to call a function or command that expects a
file on disk with some contents that you have in memory. The context manager
abstracts the writing, flushing, and deletion of the temporary file. This is a
common idio... | =os.path.dirname(filename))
try:
os.write(fd, contents)
finally:
os.close(fd)
try:
os.chmod(tmp_filename, mode)
if gid is not None:
os.chown(tmp_filename, -1, gid)
os.rename(tmp_filename, filename)
except OSError as exc:
try:
os.remove(tmp_filename)
except OSError as e:
... | 129 | 129 | 432 | 18 | 110 | ChrisCummins/format | labm8/py/fs.py | Python | TemporaryFileWithContents | TemporaryFileWithContents | 722 | 762 | 722 | 723 | 7f422401c77c11d2a510d5bd03f26b3c9909084d | bigcode/the-stack | train |
bcb4fefcbcf6be194431641e | train | function | def read(*components, **kwargs):
"""
Read file and return a list of lines. If comment_char is set, ignore the
contents of lines following the comment_char.
Raises:
IOError: if reading path fails
"""
rstrip = kwargs.get("rstrip", True)
comment_char = kwargs.get("comment_char", None)
ignore_comme... | def read(*components, **kwargs):
| """
Read file and return a list of lines. If comment_char is set, ignore the
contents of lines following the comment_char.
Raises:
IOError: if reading path fails
"""
rstrip = kwargs.get("rstrip", True)
comment_char = kwargs.get("comment_char", None)
ignore_comments = comment_char is not None
... | path = path(*components)
if not isdir(_path):
os.makedirs(_path, **kwargs)
return _path
def mkopen(p, *args, **kwargs):
"""
A wrapper for the open() builtin which makes parent directories if needed.
"""
dir = os.path.dirname(p)
mkdir(dir)
return open(p, *args, **kwargs)
def read(*components, **kwa... | 89 | 89 | 297 | 8 | 81 | ChrisCummins/format | labm8/py/fs.py | Python | read | read | 448 | 490 | 448 | 448 | 0fc49fdca4f24e0fa6afc8507134cfbe1eac1424 | bigcode/the-stack | train |
debb451fdfc775cfedda43e8 | train | function | def is_subdir(child, parent):
"""
Determine if "child" is a subdirectory of "parent".
If child == parent, returns True.
"""
child_path = os.path.realpath(child)
parent_path = os.path.realpath(parent)
if len(child_path) < len(parent_path):
return False
for i in range(len(parent_path)):
if pare... | def is_subdir(child, parent):
| """
Determine if "child" is a subdirectory of "parent".
If child == parent, returns True.
"""
child_path = os.path.realpath(child)
parent_path = os.path.realpath(parent)
if len(child_path) < len(parent_path):
return False
for i in range(len(parent_path)):
if parent_path[i] != child_path[i]:
... | basename(*components):
"""
Return the basename of a given file path.
"""
return os.path.basename(path(*components))
def dirname(*components):
"""
Return the directory name of a given file path.
"""
return os.path.dirname(path(*components))
def is_subdir(child, parent):
| 64 | 64 | 98 | 8 | 56 | ChrisCummins/format | labm8/py/fs.py | Python | is_subdir | is_subdir | 110 | 126 | 110 | 110 | e110c54ebde0287e915235b2f377ea2e8250e992 | bigcode/the-stack | train |
f0ff0d236b15c010c3d341c2 | train | function | def dirname(*components):
"""
Return the directory name of a given file path.
"""
return os.path.dirname(path(*components))
| def dirname(*components):
| """
Return the directory name of a given file path.
"""
return os.path.dirname(path(*components))
| ):
"""
Get an absolute file path.
Concatenate all components into an absolute path.
"""
return os.path.abspath(path(*components))
def basename(*components):
"""
Return the basename of a given file path.
"""
return os.path.basename(path(*components))
def dirname(*components):
| 64 | 64 | 29 | 5 | 59 | ChrisCummins/format | labm8/py/fs.py | Python | dirname | dirname | 103 | 107 | 103 | 103 | dfd7a4ad6008caa24e759d13670a50e7d44fdca7 | bigcode/the-stack | train |
5b5b3c635220294384299c5b | train | function | def isexe(*components):
"""
Return whether a path is an executable file.
Arguments:
path (str): Path of the file to check.
Examples:
>>> isexe("/bin/ls")
True
>>> isexe("/home")
False
>>> isexe("/not/a/real/path")
False
Returns:
bool: True if file is executable, else fal... | def isexe(*components):
| """
Return whether a path is an executable file.
Arguments:
path (str): Path of the file to check.
Examples:
>>> isexe("/bin/ls")
True
>>> isexe("/home")
False
>>> isexe("/not/a/real/path")
False
Returns:
bool: True if file is executable, else false.
"""
_path = path... | .getcwd()
def exists(*components):
"""
Return whether a file exists.
"""
return os.path.exists(path(*components))
def isfile(*components):
"""
Return whether a path exists, and is a file.
"""
return os.path.isfile(path(*components))
def isexe(*components):
| 64 | 64 | 114 | 6 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | isexe | isexe | 180 | 201 | 180 | 180 | 62203fd1c491bebc0ab990fea346bd65c1541289 | bigcode/the-stack | train |
891d813688bec97803491f90 | train | class | class File404(Error):
pass
| class File404(Error):
| pass
| import os.path
import pathlib
import re
import shutil
import tempfile
import typing
from glob import iglob
from send2trash import send2trash
from labm8.py import humanize
from labm8.py import labtypes
class Error(Exception):
pass
class File404(Error):
| 64 | 64 | 8 | 5 | 58 | ChrisCummins/format | labm8/py/fs.py | Python | File404 | File404 | 35 | 36 | 35 | 35 | fd831b9174287a69bf2a46110d885e96577a7820 | bigcode/the-stack | train |
f5c1915cf3ca648a0542534e | train | class | class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/dashboard.html'
def get_balance_context(self):
"""Get the high level balances"""
bank_account = Account.objects.get(name='Bank')
return dict(
bank=bank_account,
retained_earnings_a... | class DashboardView(LoginRequiredMixin, TemplateView):
| template_name = 'dashboard/dashboard.html'
def get_balance_context(self):
"""Get the high level balances"""
bank_account = Account.objects.get(name='Bank')
return dict(
bank=bank_account,
retained_earnings_accounts=Account.objects.filter(parent__name='Retained E... | from datetime import date
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.views.generic import TemplateView
from django.conf import settings
from hordak.models import Account
from hordak.utilities.currency import Balance
from swiftwind.billing_cycle.models import Bi... | 72 | 87 | 292 | 10 | 61 | m-den-i/swiftwind | swiftwind/dashboard/views.py | Python | DashboardView | DashboardView | 12 | 46 | 12 | 12 | 862b3bfdd519bbb91b399a5ee85cba7d66d05e91 | bigcode/the-stack | train |
568ccd648cbc6375ef65482c | train | class | class Uniform(ContinuousDistribution):
"""Uniform distribution with `a` and `b` parameters.
The PDF of this distribution is constant between [`a`, `b`], and 0 elsewhere.
"""
def __init__(self, a=0.0, b=1.0, name="Uniform"):
"""Construct Uniform distributions with `a` and `b`.
The parameters `a` and `... | class Uniform(ContinuousDistribution):
| """Uniform distribution with `a` and `b` parameters.
The PDF of this distribution is constant between [`a`, `b`], and 0 elsewhere.
"""
def __init__(self, a=0.0, b=1.0, name="Uniform"):
"""Construct Uniform distributions with `a` and `b`.
The parameters `a` and `b` must be shaped in a way that support... | Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS I... | 256 | 256 | 1,736 | 6 | 249 | prafullasd/tensorflow | tensorflow/contrib/distributions/python/ops/uniform.py | Python | Uniform | Uniform | 33 | 244 | 33 | 33 | 2a662f963d4c0c7974796701f47e04fd8d8d0699 | bigcode/the-stack | train |
80474c3be2e2f8e586063e12 | train | class | class ScheduledReport(models.Model):
""" A scheduled report that runs and emails itself to various users on
a recurring basis. Requires celery. """
is_active = models.BooleanField(default=True)
report = models.ForeignKey(
'report_builder.Report', on_delete=models.CASCADE
)
users = models... | class ScheduledReport(models.Model):
| """ A scheduled report that runs and emails itself to various users on
a recurring basis. Requires celery. """
is_active = models.BooleanField(default=True)
report = models.ForeignKey(
'report_builder.Report', on_delete=models.CASCADE
)
users = models.ManyToManyField(
AUTH_US... | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
import report_builder_scheduled.tasks
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class ScheduledReport(models.Model):
| 57 | 154 | 516 | 6 | 51 | nazmizorlu/django-report-builder | report_builder_scheduled/models.py | Python | ScheduledReport | ScheduledReport | 11 | 66 | 11 | 11 | 52deec04e7c4b5df675d72fb9dd201efc6f21252 | bigcode/the-stack | train |
2d00759b1520a6bfaa44c94f | train | function | def spotify_dl():
"""Main entry point of the script."""
parser = argparse.ArgumentParser(prog='spotify_dl')
parser.add_argument('-l', '--url', action="store",
help="Spotify Playlist link URL", type=str, nargs='+', required=True)
parser.add_argument('-o', '--output', type=str, act... | def spotify_dl():
| """Main entry point of the script."""
parser = argparse.ArgumentParser(prog='spotify_dl')
parser.add_argument('-l', '--url', action="store",
help="Spotify Playlist link URL", type=str, nargs='+', required=True)
parser.add_argument('-o', '--output', type=str, action='store',
... | #!/usr/bin/env python3
import argparse
import json
import os
import sys
from logging import DEBUG
from pathlib import Path, PurePath
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotify_dl.constants import VERSION
from spotify_dl.scaffold import log, check_for_tokens, console
from spotify_dl... | 109 | 224 | 749 | 4 | 104 | Aayush2492/spotify-dl | spotify_dl/spotify_dl.py | Python | spotify_dl | spotify_dl | 17 | 94 | 17 | 17 | cfb6015c5ab4fbcb7d0c4dc02b537ac16653dd45 | bigcode/the-stack | train |
ce69f734d46b19a3c9e52412 | train | function | def test_delete_service_account_field_headers():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.DeleteServiceAccountRequest()
request... | def test_delete_service_account_field_headers():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.DeleteServiceAccountRequest()
request.name = 'name/value'
# Mock the actual call ... | assert args[0] == iam.DeleteServiceAccountRequest()
# Establish that the response is the type that we expect.
assert response is None
@pytest.mark.asyncio
async def test_delete_service_account_async_from_dict():
await test_delete_service_account_async(request_type=dict)
def test_delete_service_ac... | 66 | 66 | 220 | 8 | 58 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_delete_service_account_field_headers | test_delete_service_account_field_headers | 1,800 | 1,828 | 1,800 | 1,800 | 901f0ab3a4b9befc6f648e9cc77f3c0d83b8e87d | bigcode/the-stack | train |
8490c7e6a2a953e2b96e0c97 | train | function | @pytest.mark.asyncio
async def test_create_service_account_key_async(transport: str = 'grpc_asyncio', request_type=iam.CreateServiceAccountKeyRequest):
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as fa... | @pytest.mark.asyncio
async def test_create_service_account_key_async(transport: str = 'grpc_asyncio', request_type=iam.CreateServiceAccountKeyRequest):
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the ... | work.
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_service_account_key),
'__call__') as call:
... | 135 | 135 | 450 | 33 | 102 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_create_service_account_key_async | test_create_service_account_key_async | 2,938 | 2,978 | 2,938 | 2,939 | 6bfb30aea5070c73702d7066f8a8b459a870fe1f | bigcode/the-stack | train |
eaf76f088e0dcb9a3e650f77 | train | function | @pytest.mark.asyncio
async def test_get_service_account_flattened_error_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
... | @pytest.mark.asyncio
async def test_get_service_account_flattened_error_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.get_service_account(
iam.GetServiceAccountRequest(),
... | that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == 'name_value'
@pytest.mark.asyncio
async def test_get_service_account_flattened_error_async():
| 64 | 64 | 87 | 17 | 47 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_service_account_flattened_error_async | test_get_service_account_flattened_error_async | 1,062 | 1,074 | 1,062 | 1,063 | 3e30a809530f81accad752d2b20653925c75448a | bigcode/the-stack | train |
b2a0171235bca397c901dc29 | train | function | def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
assert isinstance(
client.transport,
transports.IAMGrpcTransport,
)
| def test_transport_grpc_default():
# A client should use the gRPC transport by default.
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
assert isinstance(
client.transport,
transports.IAMGrpcTransport,
)
| used if not provided.
with mock.patch.object(google.auth, 'default') as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
| 64 | 64 | 54 | 20 | 44 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_transport_grpc_default | test_transport_grpc_default | 6,776 | 6,784 | 6,776 | 6,777 | d6b42aac9092b3ea1e7d660e0ab701ff22eea5d3 | bigcode/the-stack | train |
fad99123aef7aa94dc8ee9ed | train | function | @pytest.mark.asyncio
async def test_delete_service_account_key_flattened_error_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
... | @pytest.mark.asyncio
async def test_delete_service_account_key_flattened_error_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.delete_service_account_key(
iam.DeleteServiceAccountKey... | the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == 'name_value'
@pytest.mark.asyncio
async def test_delete_service_account_key_flattened_error_async():
| 64 | 64 | 90 | 18 | 46 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_delete_service_account_key_flattened_error_async | test_delete_service_account_key_flattened_error_async | 3,526 | 3,538 | 3,526 | 3,527 | c7b19b4b94697fed0e5c5f75d878649c364b34a4 | bigcode/the-stack | train |
8d8548252b105dcb123bae4f | train | function | @pytest.mark.asyncio
async def test_list_roles_async_pages():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.list_roles),
'__call... | @pytest.mark.asyncio
async def test_list_roles_async_pages():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.list_roles),
'__call__', new_callable=mock.AsyncMock) as call:
# Set the r... | client.list_roles(request={},)
assert async_pager.next_page_token == 'abc'
responses = []
async for response in async_pager:
responses.append(response)
assert len(responses) == 6
assert all(isinstance(i, iam.Role)
for i in responses)
@pytest.mark.... | 75 | 75 | 251 | 13 | 62 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_list_roles_async_pages | test_list_roles_async_pages | 5,355 | 5,397 | 5,355 | 5,356 | 6cdb9921117e5d056f5758251cbb60288cb62f93 | bigcode/the-stack | train |
35e5b5750b6feed461f63fa9 | train | function | @pytest.mark.asyncio
async def test_sign_blob_field_headers_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.SignBlobRequest()... | @pytest.mark.asyncio
async def test_sign_blob_field_headers_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.SignBlobRequest()
request.name = 'name/value'
# Mock the actual call within ... | assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
@pytest.mark.asyncio
async def test_sign_blob_field_headers_async():
| 69 | 69 | 233 | 14 | 55 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_sign_blob_field_headers_async | test_sign_blob_field_headers_async | 3,664 | 3,693 | 3,664 | 3,665 | 3ad238170945acc58dcd0783238761fc385a56ec | bigcode/the-stack | train |
77623486baf5fb8ad9214c8a | train | function | def test_create_role_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call... | def test_create_role_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_role),
'__call__') as call:
client.create_ro... | _blob'
assert response.deleted is True
def test_create_role_from_dict():
test_create_role(request_type=dict)
def test_create_role_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| 64 | 64 | 134 | 40 | 24 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_create_role_empty_call | test_create_role_empty_call | 5,620 | 5,635 | 5,620 | 5,622 | 4df370c41f059cfef1f913684395f17ce355de5a | bigcode/the-stack | train |
eb17fdba021de967cd9b1c3e | train | function | @pytest.mark.asyncio
async def test_get_iam_policy_field_headers_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam_policy_pb2.G... | @pytest.mark.asyncio
async def test_get_iam_policy_field_headers_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam_policy_pb2.GetIamPolicyRequest()
request.resource = 'resource/value'
# Mock ... | assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'resource=resource/value',
) in kw['metadata']
@pytest.mark.asyncio
async def test_get_iam_policy_field_headers_async():
| 72 | 72 | 243 | 16 | 56 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_iam_policy_field_headers_async | test_get_iam_policy_field_headers_async | 4,146 | 4,175 | 4,146 | 4,147 | 1a672b4bafbefb2687889f4331f23aaf271e4a64 | bigcode/the-stack | train |
222457c843d7fe2838ebef80 | train | function | def test_get_role_from_dict():
test_get_role(request_type=dict)
| def test_get_role_from_dict():
| test_get_role(request_type=dict)
| == 'title_value'
assert response.description == 'description_value'
assert response.included_permissions == ['included_permissions_value']
assert response.stage == iam.Role.RoleLaunchStage.BETA
assert response.etag == b'etag_blob'
assert response.deleted is True
def test_get_role_from_dict():
| 64 | 64 | 15 | 7 | 56 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_role_from_dict | test_get_role_from_dict | 5,441 | 5,442 | 5,441 | 5,441 | baa7a3e2219ff5a51d3dca74ac3108afaceb606e | bigcode/the-stack | train |
227dfddefdc3f53927301bec | train | function | def test_create_service_account_key_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock ... | def test_create_service_account_key_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_service_account_key),
'__call__') as call:
c... | _MANAGED
def test_create_service_account_key_from_dict():
test_create_service_account_key(request_type=dict)
def test_create_service_account_key_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| 64 | 64 | 142 | 42 | 22 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_create_service_account_key_empty_call | test_create_service_account_key_empty_call | 2,920 | 2,935 | 2,920 | 2,922 | 56ab7b08f9b7e29de1336293b35d46d9441814fb | bigcode/the-stack | train |
a7139558c0f56bf2602e7233 | train | function | @pytest.mark.asyncio
async def test_delete_service_account_key_flattened_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_ser... | @pytest.mark.asyncio
async def test_delete_service_account_key_flattened_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_service_account_key),
'__call__') as call:
# Designate an appropr... | a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete_service_account_key(
iam.DeleteServiceAccountKeyRequest(),
name='name_value',
)
@pytest.mark.asyncio
async def test_delete_service_account_key_flattened_... | 64 | 64 | 202 | 17 | 47 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_delete_service_account_key_flattened_async | test_delete_service_account_key_flattened_async | 3,499 | 3,523 | 3,499 | 3,500 | 921e683a227551448820ee3fdec2e000944cf6c4 | bigcode/the-stack | train |
9cd51aa680cffeb3618d7181 | train | function | def test_get_service_account_field_headers():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.GetServiceAccountRequest()
request.name ... | def test_get_service_account_field_headers():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.GetServiceAccountRequest()
request.name = 'name/value'
# Mock the actual call wit... | '
assert response.description == 'description_value'
assert response.oauth2_client_id == 'oauth2_client_id_value'
assert response.disabled is True
@pytest.mark.asyncio
async def test_get_service_account_async_from_dict():
await test_get_service_account_async(request_type=dict)
def test_get_service_acc... | 66 | 66 | 222 | 8 | 58 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_service_account_field_headers | test_get_service_account_field_headers | 934 | 962 | 934 | 934 | 5750b7db6a2c8d5a24c56488779a9dec2705c9b4 | bigcode/the-stack | train |
8fd357aa75a0260859df1d3f | train | function | def test_test_iam_permissions_from_dict():
test_test_iam_permissions(request_type=dict)
| def test_test_iam_permissions_from_dict():
| test_test_iam_permissions(request_type=dict)
| [0]
assert args[0] == iam_policy_pb2.TestIamPermissionsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse)
assert response.permissions == ['permissions_value']
def test_test_iam_permissions_from_dict():
| 64 | 64 | 19 | 9 | 55 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_test_iam_permissions_from_dict | test_test_iam_permissions_from_dict | 4,557 | 4,558 | 4,557 | 4,557 | fd12b66ec14db92379a2bffb55f1bdbd35b84b1f | bigcode/the-stack | train |
f74a67af195d46675a343084 | train | function | @pytest.mark.asyncio
async def test_sign_blob_async_from_dict():
await test_sign_blob_async(request_type=dict)
| @pytest.mark.asyncio
async def test_sign_blob_async_from_dict():
| await test_sign_blob_async(request_type=dict)
| iam.SignBlobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, iam.SignBlobResponse)
assert response.key_id == 'key_id_value'
assert response.signature == b'signature_blob'
@pytest.mark.asyncio
async def test_sign_blob_async_from_dict():
| 64 | 64 | 24 | 14 | 50 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_sign_blob_async_from_dict | test_sign_blob_async_from_dict | 3,628 | 3,630 | 3,628 | 3,629 | 06371873d2d05bea7c203b9a00711b569b4292d0 | bigcode/the-stack | train |
dda44296475af19287352885 | train | function | def test_list_roles_pages():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.list_roles),
'__call__') as call:
# Set the respon... | def test_list_roles_pages():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.list_roles),
'__call__') as call:
# Set the response to a series of pages.
... | Error,
)
metadata = ()
pager = client.list_roles(request={})
assert pager._metadata == metadata
results = [i for i in pager]
assert len(results) == 6
assert all(isinstance(i, iam.Role)
for i in results)
def test_list_roles_pages():
| 66 | 66 | 223 | 6 | 60 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_list_roles_pages | test_list_roles_pages | 5,266 | 5,305 | 5,266 | 5,266 | 49a4f4f7e7564807df58829989db4a2490bf78b5 | bigcode/the-stack | train |
cb56b1788033822f55bbf0db | train | function | def test_delete_service_account_key_flattened():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_service_account_key),
'__call... | def test_delete_service_account_key_flattened():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_service_account_key),
'__call__') as call:
# Designate an appropriate ... | assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
def test_delete_service_account_key_flattened():
| 64 | 64 | 180 | 10 | 54 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_delete_service_account_key_flattened | test_delete_service_account_key_flattened | 3,461 | 3,482 | 3,461 | 3,461 | 8cd363e14fa0fab22d555cd7678ada251ebea528 | bigcode/the-stack | train |
502de3d3c3d8bd80ad88e554 | train | function | def test_query_grantable_roles_pager():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.query_grantable_roles),
'__call__') as call:
... | def test_query_grantable_roles_pager():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.query_grantable_roles),
'__call__') as call:
# Set the response to a series of ... | _credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.query_grantable_roles(
iam.QueryGrantableRolesRequest(),
full_resource_name='full_resource_nam... | 76 | 76 | 254 | 10 | 66 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_query_grantable_roles_pager | test_query_grantable_roles_pager | 4,949 | 4,995 | 4,949 | 4,949 | 624bcbe65f9963b7696a35e86ae9b4412620f64e | bigcode/the-stack | train |
50e8c50593b1cd6285b6149c | train | function | @pytest.mark.asyncio
async def test_get_role_async(transport: str = 'grpc_asyncio', request_type=iam.GetRoleRequest):
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
... | @pytest.mark.asyncio
async def test_get_role_async(transport: str = 'grpc_asyncio', request_type=iam.GetRoleRequest):
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the ... | ='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.get_role),
'__call__') as call:
client.get_role()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == iam.Ge... | 106 | 106 | 354 | 29 | 77 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_role_async | test_get_role_async | 5,463 | 5,503 | 5,463 | 5,464 | cb49340c67644af0bb3e0296913b7e2fb7980982 | bigcode/the-stack | train |
a1b74d24a402fe7c9082bc65 | train | function | def test_undelete_service_account_field_headers():
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.UndeleteServiceAccountRequest()
req... | def test_undelete_service_account_field_headers():
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.UndeleteServiceAccountRequest()
request.name = 'name/value'
# Mock the actual cal... | ServiceAccountRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, iam.UndeleteServiceAccountResponse)
@pytest.mark.asyncio
async def test_undelete_service_account_async_from_dict():
await test_undelete_service_account_async(request_type=dict)
def test_undelete_... | 70 | 70 | 234 | 10 | 60 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_undelete_service_account_field_headers | test_undelete_service_account_field_headers | 2,027 | 2,055 | 2,027 | 2,027 | 99e085158ec67507fef1f7becc37b83bbd70d8aa | bigcode/the-stack | train |
485ad7e7e2197bad215497c2 | train | function | def test_get_role(transport: str = 'grpc', request_type=iam.GetRoleRequest):
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so j... | def test_get_role(transport: str = 'grpc', request_type=iam.GetRoleRequest):
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actua... | .ListRolesResponse(
roles=[
iam.Role(),
iam.Role(),
],
),
RuntimeError,
)
pages = []
async for page_ in (await client.list_roles(request={})).pages:
pages.append(page_)
for page_, ... | 101 | 101 | 338 | 20 | 80 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_role | test_get_role | 5,399 | 5,438 | 5,399 | 5,399 | c13ae56b0a9af62dbfe3f327c721d84b33be5d11 | bigcode/the-stack | train |
5ec6793876415760c93a12b1 | train | function | def test_lint_policy_from_dict():
test_lint_policy(request_type=dict)
| def test_lint_policy_from_dict():
| test_lint_policy(request_type=dict)
| .mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == iam.LintPolicyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, iam.LintPolicyResponse)
def test_lint_policy_from_dict():
| 64 | 64 | 17 | 8 | 56 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_lint_policy_from_dict | test_lint_policy_from_dict | 6,655 | 6,656 | 6,655 | 6,655 | 035145e9479e8987b98d8df6b97ffab5b5d90aab | bigcode/the-stack | train |
1505236bfdb211747cff666f | train | function | @pytest.mark.asyncio
async def test_get_service_account_key_field_headers_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.Get... | @pytest.mark.asyncio
async def test_get_service_account_key_field_headers_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = iam.GetServiceAccountKeyRequest()
request.name = 'name/value'
# Mock the actual ... | ]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
@pytest.mark.asyncio
async def test_get_service_account_key_field_headers_async():
| 72 | 72 | 241 | 16 | 56 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_service_account_key_field_headers_async | test_get_service_account_key_field_headers_async | 2,756 | 2,785 | 2,756 | 2,757 | c55a2c1b047ca1e33dc788c196e11bc0cc8acb18 | bigcode/the-stack | train |
0c4dccdf47cb634472e9f23c | train | function | @pytest.mark.asyncio
async def test_delete_service_account_flattened_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_service... | @pytest.mark.asyncio
async def test_delete_service_account_flattened_async():
| client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.delete_service_account),
'__call__') as call:
# Designate an appropriate... | ing to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete_service_account(
iam.DeleteServiceAccountRequest(),
name='name_value',
)
@pytest.mark.asyncio
async def test_delete_service_account_flattened_... | 64 | 64 | 199 | 16 | 48 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_delete_service_account_flattened_async | test_delete_service_account_flattened_async | 1,901 | 1,925 | 1,901 | 1,902 | 17d304fe771855944cdf59cb93bdf3f0d7ca382f | bigcode/the-stack | train |
35d87281cab06d605255ef49 | train | function | def test_disable_service_account_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the... | def test_disable_service_account_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.disable_service_account),
'__call__') as call:
clie... | assert response is None
def test_disable_service_account_from_dict():
test_disable_service_account(request_type=dict)
def test_disable_service_account_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
| 64 | 64 | 138 | 41 | 23 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_disable_service_account_empty_call | test_disable_service_account_empty_call | 2,266 | 2,281 | 2,266 | 2,268 | c56948d099b26b2487f8fd2b6483dad8a7b6f634 | bigcode/the-stack | train |
269e1003e9b868ede2916a05 | train | function | def test_get_service_account_key(transport: str = 'grpc', request_type=iam.GetServiceAccountKeyRequest):
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mock... | def test_get_service_account_key(transport: str = 'grpc', request_type=iam.GetServiceAccountKeyRequest):
| client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actua... | @pytest.mark.asyncio
async def test_list_service_account_keys_flattened_error_async():
client = IAMAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
... | 130 | 130 | 434 | 24 | 106 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_get_service_account_key | test_get_service_account_key | 2,613 | 2,652 | 2,613 | 2,613 | 13fd95a4e9ac4f2283d5b28b7deb07770c3ed85b | bigcode/the-stack | train |
cb34b3112ade39c2a39e7f91 | train | function | def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.IAMGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = IAMClient(
credentials=ga_credentia... | def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
| transport = transports.IAMGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = IAMClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# It is an error to provide a crede... | is the type that we expect.
assert isinstance(response, iam.LintPolicyResponse)
@pytest.mark.asyncio
async def test_lint_policy_async_from_dict():
await test_lint_policy_async(request_type=dict)
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
| 64 | 64 | 204 | 20 | 44 | googleapis/googleapis-gen | google/iam/admin/v1/iam-admin-v1-py/tests/unit/gapic/admin_v1/test_iam.py | Python | test_credentials_transport_error | test_credentials_transport_error | 6,711 | 6,740 | 6,711 | 6,712 | af3c8c8c779b1ec01d4835c2c7f06e09940485b5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.