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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6773f13985aa2ae987f886a2 | train | function | def getNameToWorkerDict(workers):
nameToWorker = {}
for w in workers:
nameToWorker[w.getName()] = w
return nameToWorker
| def getNameToWorkerDict(workers):
| nameToWorker = {}
for w in workers:
nameToWorker[w.getName()] = w
return nameToWorker
| w.getPref(hospitals).judge(w)
workers = workers[1:]
if(y is not None):
workers.append(y)
def getWorker(name,workers):
for w in workers:
if(w.getName()==name):
return w
def getNameToWorkerDict(workers):
| 64 | 64 | 39 | 9 | 54 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | getNameToWorkerDict | getNameToWorkerDict | 817 | 821 | 817 | 817 | 3c70d2ca01514789233bc5b6913feffba0ed6be8 | bigcode/the-stack | train |
7fae2acc2baff3eb8e563df3 | train | function | def getR(w):
''' gets rank of hospital w is matched to based on p' (t-algorithm results)
Note that p' is reported preferences '''
h = w.getCurrent()
if(h is None):
return 0 # unmatched
for i in range(len(w.getMatchings())):
if(w.getMatchings()[i].getName() == h.getName()):... | def getR(w):
| ''' gets rank of hospital w is matched to based on p' (t-algorithm results)
Note that p' is reported preferences '''
h = w.getCurrent()
if(h is None):
return 0 # unmatched
for i in range(len(w.getMatchings())):
if(w.getMatchings()[i].getName() == h.getName()):
r... | ):
for w in workers:
if(w.getName()==name):
return w
def getNameToWorkerDict(workers):
nameToWorker = {}
for w in workers:
nameToWorker[w.getName()] = w
return nameToWorker
def getR(w):
| 64 | 64 | 93 | 6 | 57 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | getR | getR | 823 | 832 | 823 | 823 | 966558f0ef631f06708d7065ad9893ad8db009fa | bigcode/the-stack | train |
ee8b2a2c76f0a0133d382195 | train | function | def getR3(w, pprime):
''' gets rank of doctor h is matched to based on p' (IU and CU)
Note that p' is reported preferences '''
h = w.getCurrent()
if(h is None):
return 0 # unmatched
for i in range(len(pprime)):
if(pprime[i] == h.getName()):
return i + 1
retu... | def getR3(w, pprime):
| ''' gets rank of doctor h is matched to based on p' (IU and CU)
Note that p' is reported preferences '''
h = w.getCurrent()
if(h is None):
return 0 # unmatched
for i in range(len(pprime)):
if(pprime[i] == h.getName()):
return i + 1
return -1
| run) '''
h = w.getCurrent()
if(h is None):
return 0 # unmatched
for i in range(len(w.getRanking())):
if(w.getRanking()[i] == h.getName()):
return i + 1
def getR3(w, pprime):
| 64 | 64 | 90 | 10 | 53 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | getR3 | getR3 | 845 | 855 | 845 | 845 | 8942c81ce813724bff60fb95155bea18f3a5885b | bigcode/the-stack | train |
db20028d7cbc16ffc3512862 | train | function | def addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks):
'''
This just updates these lists (this is done the same way every run)
'''
for i in range(1, num_doctors + 1):
docs.append(i)
types.append("Doctor")
runs.append(run_num)
... | def addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks):
| '''
This just updates these lists (this is done the same way every run)
'''
for i in range(1, num_doctors + 1):
docs.append(i)
types.append("Doctor")
runs.append(run_num)
cu_ranks.append(i)
for i in range(1, num_hospitals + 1):
works.append(i)
types.a... | with their own randomized preferences
return workers, hospitals, workers2, workers3, hospitals2, cuw, cuh, workers4, hospitals4
def addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks):
| 64 | 64 | 130 | 31 | 32 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | addDoctorsAndWorkersToLists | addDoctorsAndWorkersToLists | 907 | 921 | 907 | 907 | 35767afeb0a08fd8a929330f384a3e39603c5c5d | bigcode/the-stack | train |
083d076b8476cee2e5e14c23 | train | function | def b(goal, h, workers):
''' same as above but this time hospital "proposes" '''
available = []
for w in workers:
if(h.checkAvailability(goal, w)):
available.append(w)
if len(available) > 0:
temp, available = fastersort(getEquiv(available, h), available)
if(le... | def b(goal, h, workers):
| ''' same as above but this time hospital "proposes" '''
available = []
for w in workers:
if(h.checkAvailability(goal, w)):
available.append(w)
if len(available) > 0:
temp, available = fastersort(getEquiv(available, h), available)
if(len(available) <= goal):
... | if len(available) > 0:
temp, available = fastersort(getEquiv(available, w), available)
if(len(available) <= goal):
return available
else:
top = available[:goal]
return top
def b(goal, h, workers):
| 64 | 64 | 104 | 9 | 54 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | b | b | 703 | 718 | 703 | 703 | 7f5679d418fbcf45b80a438a35cd1512f0b18114 | bigcode/the-stack | train |
2976f986fffeb8c6623ea6ed | train | function | def equate(past, current):
''' checks if matchings remain same in t-algorithm in two consecutive iterations of "proposals" '''
if(len(past) != len(current)):
return False
for i in range(len(past)):
if(len(past[i]) != len(current[i])):
return False
for j in range(len(... | def equate(past, current):
| ''' checks if matchings remain same in t-algorithm in two consecutive iterations of "proposals" '''
if(len(past) != len(current)):
return False
for i in range(len(past)):
if(len(past[i]) != len(current[i])):
return False
for j in range(len(past[i])):
if(p... | (goal, h, workers))
for w in workers:
w.match(todo.pop(0))
total.append(w.getMatchings())
for h in hospitals:
h.match(todo.pop(0))
total.append(h.getMatchings())
return total
def equate(past, current):
| 64 | 64 | 102 | 8 | 55 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | equate | equate | 772 | 783 | 772 | 772 | 117d130800e0c543c027c109cbd6a52b5fee39bc | bigcode/the-stack | train |
7c0c56d0a864f17080896225 | train | function | def swap(pref, ranking, x, y):
temp1 = pref[x]
temp2 = ranking[x]
pref[x] = pref[y]
ranking[x] = ranking[y]
pref[y] = temp1
ranking[y] = temp2
| def swap(pref, ranking, x, y):
| temp1 = pref[x]
temp2 = ranking[x]
pref[x] = pref[y]
ranking[x] = ranking[y]
pref[y] = temp1
ranking[y] = temp2
| ascending order
for i in range(len(pref)):
for k in range(len(pref) - 1, i, -1):
if(pref[k] < pref[k - 1]):
swap(pref,ranking, k, k - 1)
def swap(pref, ranking, x, y):
| 63 | 64 | 56 | 10 | 53 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | swap | swap | 734 | 740 | 734 | 734 | d8685bc96104da233b66a895de3cab9d748b0c90 | bigcode/the-stack | train |
c3cd469bb8bb800d9f3b72a5 | train | function | def profile(filename, func, args=None):
pr = cProfile.Profile()
pr.enable()
if args is not None:
func(**args)
else:
func()
pr.disable()
f = open(filename, 'w')
ps = pstats.Stats(pr, stream=f)
ps.sort_stats('cumulative', 'tottime')
ps.print_stats()
f.close()
| def profile(filename, func, args=None):
| pr = cProfile.Profile()
pr.enable()
if args is not None:
func(**args)
else:
func()
pr.disable()
f = open(filename, 'w')
ps = pstats.Stats(pr, stream=f)
ps.sort_stats('cumulative', 'tottime')
ps.print_stats()
f.close()
| filename + "_key.csv"
fn3 = filename + "_preference_profile.csv"
results.to_csv(fn, index = False)
results2.to_csv(fn2, index = False)
return results, results2
import cProfile
import pstats
def profile(filename, func, args=None):
| 64 | 64 | 85 | 9 | 54 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | profile | profile | 1,643 | 1,661 | 1,643 | 1,644 | 0b67b5ec1faa5a44d309e538522f4939a9648a5d | bigcode/the-stack | train |
ac821202066cc192502704ff | train | function | def iteration(goal, workers, hospitals):
''' this is one iteration of t-algorithm
this is done until no changes are made'''
todo = []
total = []
for w in workers:
todo.append(a(goal, w, hospitals))
for h in hospitals:
todo.append(b(goal, h, workers))
for... | def iteration(goal, workers, hospitals):
| ''' this is one iteration of t-algorithm
this is done until no changes are made'''
todo = []
total = []
for w in workers:
todo.append(a(goal, w, hospitals))
for h in hospitals:
todo.append(b(goal, h, workers))
for w in workers:
w.match(todo.pop(0... | getEquiv(avail, judge):
equiv = []
for a in avail:
equiv.append(getRank(a, judge))
return equiv
def getRank(desired, judge):
ranking = judge.getP_dict()
return ranking[desired.getName()]
def iteration(goal, workers, hospitals):
| 63 | 64 | 121 | 8 | 55 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | iteration | iteration | 752 | 770 | 752 | 752 | b319568a6dc94cd342f136e0f432eb1fb4d4aeed | bigcode/the-stack | train |
d365eab4a6ea0930ff40b012 | train | function | def runTAGS_and_GS(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, cu_ranks, match_gs_p_docs, match_gs_pp_docs, match_gs_p_hosp, match_gs_pp_hosp, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_gs_truncated_p_hosp,
match_gs_truncated_pp_hos... | def runTAGS_and_GS(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, cu_ranks, match_gs_p_docs, match_gs_pp_docs, match_gs_p_hosp, match_gs_pp_hosp, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_gs_truncated_p_hosp,
match_gs_truncated_pp_hos... | workers, hospitals, workers2, workers3, hospitals2, cuw, cuh, workers4, hospitals4 = getDoctorsAndHospitalsExtended(num_doctors, num_hospitals, we_doctors, we_hospitals)
# note that workers and hospitals have the preferences that we use for all the other workers/hospitals lists
# so we can get these prefere... | def runTAGS_and_GS(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, cu_ranks, match_gs_p_docs, match_gs_pp_docs, match_gs_p_hosp, match_gs_pp_hosp, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_gs_truncated_p_hosp,
match_gs_truncated_pp_hos... | 287 | 256 | 3,751 | 287 | 0 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | runTAGS_and_GS | runTAGS_and_GS | 1,178 | 1,523 | 1,178 | 1,180 | dfc36dc369f622078737e8bf00810ceec8bf5a92 | bigcode/the-stack | train |
2c5559f099418be5f826ef4e | train | function | def getWorker(name,workers):
for w in workers:
if(w.getName()==name):
return w
| def getWorker(name,workers):
| for w in workers:
if(w.getName()==name):
return w
| y = None
if(len(w.getWishes()) > 0 and w.getCurrent() is None):
y = w.getPref(hospitals).judge(w)
workers = workers[1:]
if(y is not None):
workers.append(y)
def getWorker(name,workers):
| 64 | 64 | 25 | 7 | 57 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | getWorker | getWorker | 812 | 815 | 812 | 812 | 20ad1f9ea3fbcddb639f1b540cfb578ace1d55d1 | bigcode/the-stack | train |
e1ec8d47b9dda3b65775198d | train | function | def getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals):
'''
we_doctors is weight for common utility for doctors
we_hospitals is weight for common utility for hospitals '''
# First, note that we can change the distribution and its parameters for common utility
cuw =... | def getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals):
| '''
we_doctors is weight for common utility for doctors
we_hospitals is weight for common utility for hospitals '''
# First, note that we can change the distribution and its parameters for common utility
cuw = [np.random.normal(0, 1) for x in range(num_hospitals)] # common utility hospitals... | highest CU, 1 for second highest, etc
hospital is the hospital that the worker matched to (so we can match its name to hospital_name to get its preference)
'''
hospital_index = 0
for h in hospital_names:
if (hospital.getName() == h):
break
hospital_index += 1
return cu_s... | 125 | 125 | 417 | 24 | 101 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | getDoctorsAndHospitals | getDoctorsAndHospitals | 871 | 886 | 871 | 871 | 0db0353d77889e782699505a3bd22492d3baee1c | bigcode/the-stack | train |
70d8bec33bf2fd8ae894679e | train | function | def a(goal, w, hospitals):
''' this is the part of the T-algorithm where each worker "proposes"
returns top n (or less) hospitals
where n is desired number of matchings'''
available = []
for h in hospitals:
if(w.checkAvailability(goal, h)):
available.append(h)
... | def a(goal, w, hospitals):
| ''' this is the part of the T-algorithm where each worker "proposes"
returns top n (or less) hospitals
where n is desired number of matchings'''
available = []
for h in hospitals:
if(w.checkAvailability(goal, h)):
available.append(h)
# available cont... | getWishes(self):
''' returns list of strings of names of workers that will be ranked '''
return self.wishes
def getCurrent(self):
''' returns current match (worker) during Gale Shapley algorithm '''
return self.current
def a(goal, w, hospitals):
| 64 | 64 | 140 | 9 | 54 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | a | a | 682 | 701 | 682 | 682 | 5f1d0fc3d13ca761b7d5de025f55281e163a4984 | bigcode/the-stack | train |
1696e86b2770bd36e1abc4d8 | train | function | def bubblesort(pref, ranking):
# note this sorts in ascending order
for i in range(len(pref)):
for k in range(len(pref) - 1, i, -1):
if(pref[k] < pref[k - 1]):
swap(pref,ranking, k, k - 1)
| def bubblesort(pref, ranking):
# note this sorts in ascending order
| for i in range(len(pref)):
for k in range(len(pref) - 1, i, -1):
if(pref[k] < pref[k - 1]):
swap(pref,ranking, k, k - 1)
| sort in descending order since the first argument, "pref"
# represents utilities
# here, "pref" represents a ranking, so we want "1" to be first
return zip(*sorted(zip(pref, ranking)))
def bubblesort(pref, ranking):
# note this sorts in ascending order
| 64 | 64 | 66 | 16 | 48 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | bubblesort | bubblesort | 727 | 732 | 727 | 728 | df582462ed31bb6bf8145d447a980739bd9fa0e1 | bigcode/the-stack | train |
1f662750d05654233c08eece | train | function | def simulate(n, num_docs, num_hospitals, cud, cuh, max_interviews, filename='empty'):
ids = []
docs = []
works = []
runs = []
cu_ranks = []
types = []
match_in_pp_docs = []
match_in_p_docs = []
match_gs_p_docs = []
match_gs_pp_docs = []
match_gs_p_hosp = []
match_gs_pp_ho... | def simulate(n, num_docs, num_hospitals, cud, cuh, max_interviews, filename='empty'):
| ids = []
docs = []
works = []
runs = []
cu_ranks = []
types = []
match_in_pp_docs = []
match_in_p_docs = []
match_gs_p_docs = []
match_gs_pp_docs = []
match_gs_p_hosp = []
match_gs_pp_hosp = []
match_in_pp_hosp = []
match_in_p_hosp = []
match_gs_truncated_p_do... | , x, y, max_interviews, True, doctors_p2, doctors_pprime2, hospitals_p2, hospital_pprime2, match_gs_truncated_pp_docs, match_gs_truncated_p_docs, bp_GS_Trunc_d, num_doctors, min_index, match_name_gs_trunc_d)
# Now we have hospitals propose
doTruncatedGS(workers, hospitals, x, y, max_interviews, False, doctors_... | 256 | 256 | 1,684 | 25 | 231 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | simulate | simulate | 1,525 | 1,638 | 1,525 | 1,525 | d76ffff922212f78736e805af6ef04f93981923b | bigcode/the-stack | train |
e9a11a7a4a4e156a802f3a18 | train | function | def recordBlockingPairs(x, y, workers_list, hospitals_list, array_to_record, num_doctors, min_index):
# make a dictionary mapping worker names to workers
name_to_worker = getNameToWorkerDict(workers_list)
# same with hospitals
name_to_hospital = getNameToWorkerDict(hospitals_list)
# now we ch... | def recordBlockingPairs(x, y, workers_list, hospitals_list, array_to_record, num_doctors, min_index):
# make a dictionary mapping worker names to workers
| name_to_worker = getNameToWorkerDict(workers_list)
# same with hospitals
name_to_hospital = getNameToWorkerDict(hospitals_list)
# now we check for blocking pairs for each individual doctor/hospital
for i in range(len(x)):
d = x[i]
# get the actual worker
w = name_to_wo... | + 1):
works.append(i)
types.append("Hospital")
runs.append(run_num)
cu_ranks.append(i)
def recordBlockingPairs(x, y, workers_list, hospitals_list, array_to_record, num_doctors, min_index):
# make a dictionary mapping worker names to workers
| 64 | 64 | 190 | 36 | 28 | alistairjwilson/nrmpInterviews_SimData | 500SIGS/Code to Run SIGS only/Sim500_5_50_75.py | Python | recordBlockingPairs | recordBlockingPairs | 923 | 945 | 923 | 924 | 7807793efd52bcd7e456c893e18691a6f4bcb7c2 | bigcode/the-stack | train |
3764bb39171f0ee1c5b52a14 | train | function | def object_copy_conditional_disable(context):
from .classes import ModelCopy
try:
resolved_object = context['resolved_object']
except KeyError:
return False
else:
try:
return ModelCopy.get(
model=resolved_object._meta.model
).te... | def object_copy_conditional_disable(context):
| from .classes import ModelCopy
try:
resolved_object = context['resolved_object']
except KeyError:
return False
else:
try:
return ModelCopy.get(
model=resolved_object._meta.model
).test_condition(instance=resolved_object)
... | .apps.navigation.utils import get_content_type_kwargs_factory
from .icons import (
icon_about, icon_book, icon_documentation, icon_forum, icon_license,
icon_object_copy, icon_setup, icon_source_code, icon_store, icon_support,
icon_tools
)
def object_copy_conditional_disable(context):
| 64 | 64 | 76 | 8 | 56 | CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons | mayan/apps/common/links.py | Python | object_copy_conditional_disable | object_copy_conditional_disable | 13 | 26 | 13 | 13 | 5416eabb99806f4d0bdaa8301aa7db4a68f79a76 | bigcode/the-stack | train |
b7abcade4454cdb793fc05c2 | train | function | def start_test_ip():
from IPython.terminal.interactiveshell import TerminalInteractiveShell
return TerminalInteractiveShell()
| def start_test_ip():
| from IPython.terminal.interactiveshell import TerminalInteractiveShell
return TerminalInteractiveShell()
| Token
from pygments.util import ClassNotFound
from gruvbox.gruvbox import GruvboxStyle
# def setup_module():
# _ip = get_ipython()
# if _ip is None:
# raise unittest.SkipTest("Run inside IPython shell")
def start_test_ip():
| 64 | 64 | 26 | 5 | 59 | CosmosAtlas/gruvbox_pygments | test/test_style.py | Python | start_test_ip | start_test_ip | 20 | 23 | 20 | 20 | e29567623f5f059eea907e739caa08d290611085 | bigcode/the-stack | train |
1204109490925d5b9d99181a | train | class | class TestGruvboxStyleAndIPython(unittest.TestCase):
"""Practicing using the unittest module."""
def setUp(self):
self._ip = get_ipython()
if self._ip is None:
self._ip = start_test_ip()
self.style = GruvboxStyle()
# self.colorscheme = self._ip.highlighting_style.st... | class TestGruvboxStyleAndIPython(unittest.TestCase):
| """Practicing using the unittest module."""
def setUp(self):
self._ip = get_ipython()
if self._ip is None:
self._ip = start_test_ip()
self.style = GruvboxStyle()
# self.colorscheme = self._ip.highlighting_style.style_rules
self.colorscheme = self.style.style... |
from pygments.plugin import find_plugin_styles
from pygments.token import Token
from pygments.util import ClassNotFound
from gruvbox.gruvbox import GruvboxStyle
# def setup_module():
# _ip = get_ipython()
# if _ip is None:
# raise unittest.SkipTest("Run inside IPython shell")
def start_test_ip():
... | 113 | 113 | 379 | 13 | 100 | CosmosAtlas/gruvbox_pygments | test/test_style.py | Python | TestGruvboxStyleAndIPython | TestGruvboxStyleAndIPython | 26 | 69 | 26 | 26 | 97ef204df2ffe5a8df4687082bbc0453480c066e | bigcode/the-stack | train |
120d1e5a359e912ba4c2ab4f | train | class | class _BucketizedColumn(_FeatureColumn, collections.namedtuple(
"_BucketizedColumn", ["source_column", "boundaries"])):
"""Represents a bucketization transformation also known as binning.
Instances of this class are immutable. Values in `source_column` will be
bucketized based on `boundaries`.
For example,... | class _BucketizedColumn(_FeatureColumn, collections.namedtuple(
"_BucketizedColumn", ["source_column", "boundaries"])):
| """Represents a bucketization transformation also known as binning.
Instances of this class are immutable. Values in `source_column` will be
bucketized based on `boundaries`.
For example, if the inputs are:
boundaries = [0, 10, 100]
source_column = [[-5], [150], [10], [0], [4], [19]]
then the bu... | _int = True
is_list_all_float = True
for v in default_value:
if not isinstance(v, int):
is_list_all_int = False
if not (isinstance(v, float) or isinstance(v, int)):
is_list_all_float = False
if is_list_all_int:
if dtype.is_integer:
return _RealValuedColumn(column_na... | 256 | 256 | 1,135 | 28 | 228 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _BucketizedColumn | _BucketizedColumn | 1,280 | 1,405 | 1,280 | 1,281 | e72fffa10bcda82ddd9832b7548eb6033bbe7d94 | bigcode/the-stack | train |
b5df3531972f3db7d1ed9ba7 | train | class | class _EmbeddingColumn(_FeatureColumn, collections.namedtuple(
"_EmbeddingColumn",
["sparse_id_column", "dimension", "combiner", "initializer",
"ckpt_to_load_from", "tensor_name_in_ckpt", "shared_embedding_name",
"shared_vocab_size"])):
"""Represents an embedding column.
Args:
sparse_id_colum... | class _EmbeddingColumn(_FeatureColumn, collections.namedtuple(
"_EmbeddingColumn",
["sparse_id_column", "dimension", "combiner", "initializer",
"ckpt_to_load_from", "tensor_name_in_ckpt", "shared_embedding_name",
"shared_vocab_size"])):
| """Represents an embedding column.
Args:
sparse_id_column: A `_SparseColumn` which is created by
`sparse_column_with_*` or `weighted_sparse_column` functions.
dimension: An integer specifying dimension of the embedding.
combiner: A string specifying how to reduce if there are multiple entries
... | raise ValueError("one_hot_column does not yet support "
"weighted_sparse_column. Column: {}".format(self))
dense_id_tensor = sparse_ops.sparse_tensor_to_dense(
self.sparse_id_column.id_tensor(transformed_input_tensor),
default_value=-1)
check_shape_op = control_flow_ops... | 256 | 256 | 1,197 | 61 | 195 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _EmbeddingColumn | _EmbeddingColumn | 721 | 850 | 721 | 725 | 14562d7b30b501575a0aad718ebc26daf401220a | bigcode/the-stack | train |
be5d40f67e82adffd508d6c5 | train | class | class _SparseIdLookupConfig(
collections.namedtuple("_SparseIdLookupConfig",
["vocabulary_file", "keys", "num_oov_buckets",
"vocab_size", "default_value"])):
"""Defines lookup configuration for a sparse feature.
An immutable object defines lookup table con... | class _SparseIdLookupConfig(
collections.namedtuple("_SparseIdLookupConfig",
["vocabulary_file", "keys", "num_oov_buckets",
"vocab_size", "default_value"])):
| """Defines lookup configuration for a sparse feature.
An immutable object defines lookup table configuration used by
tf.feature_to_id_v2.
Attributes:
vocabulary_file: The vocabulary filename. vocabulary_file cannot be combined
with keys.
keys: A 1-D string iterable that specifies the mapping of ... | array_ops.placeholder(
column_type.dtype,
shape=(None, column_type.shape[0]),
name="Placeholder_{}".format(column_name))
return placeholders
class _SparseIdLookupConfig(
collections.namedtuple("_SparseIdLookupConfig",
["vocabulary_file", "keys", "num_oov_b... | 78 | 78 | 263 | 44 | 33 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _SparseIdLookupConfig | _SparseIdLookupConfig | 1,826 | 1,856 | 1,826 | 1,829 | df41332c86f40aa4778a64acfa1ff8ee37ae4bfc | bigcode/the-stack | train |
5d906bb0c25687dd75c97437 | train | class | class _SparseColumn(_FeatureColumn,
collections.namedtuple("_SparseColumn",
["column_name", "is_integerized",
"bucket_size", "lookup_config",
"combiner", "dtype"])):
"... | class _SparseColumn(_FeatureColumn,
collections.namedtuple("_SparseColumn",
["column_name", "is_integerized",
"bucket_size", "lookup_config",
"combiner", "dtype"])):
| """Represents a sparse feature column also known as categorical features.
Instances of this class are immutable. A sparse column means features are
sparse and dictionary returned by InputBuilder contains a
("column_name", SparseTensor) pair.
One and only one of bucket_size or lookup_config should be set. If
... | its particular properties."""
fields_values = []
# pylint: disable=protected-access
for i, k in enumerate(self._fields):
if k in properties:
# Excludes a property from the key.
# For instance, exclude `initializer` from the key of EmbeddingColumn
# since we don't support users ... | 256 | 256 | 1,179 | 44 | 212 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _SparseColumn | _SparseColumn | 212 | 347 | 212 | 216 | 9b71dddeaa3c80db4aa8d0d59ee9cce77f580c54 | bigcode/the-stack | train |
15b7607647efb6af52dda246 | train | class | class DataFrameColumn(_FeatureColumn,
collections.namedtuple("DataFrameColumn",
["column_name", "series"])):
"""Represents a feature column produced from a `DataFrame`.
Instances of this class are immutable. A `DataFrame` column may be dense or
... | class DataFrameColumn(_FeatureColumn,
collections.namedtuple("DataFrameColumn",
["column_name", "series"])):
| """Represents a feature column produced from a `DataFrame`.
Instances of this class are immutable. A `DataFrame` column may be dense or
sparse, and may have any shape, with the constraint that dimension 0 is
batch_size.
Args:
column_name: a name for this column
series: a `Series` to be wrapped, whi... | Column, or _BucketizedColumn, or
hash_bucket_size is not an int.
ValueError: if hash_bucket_size is not > 1 or
len(columns) is not > 1.
"""
if combiner is None:
logging.warn("The default value of combiner will change from \"sum\" "
"to \"sqrtn\" after 2016/11/01.")
combiner ... | 168 | 168 | 561 | 26 | 142 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | DataFrameColumn | DataFrameColumn | 1,637 | 1,707 | 1,637 | 1,639 | 191d8b26fd55737bacddb8ebf4e7e520b198ee30 | bigcode/the-stack | train |
ed3a027aa603bccc73dc0f70 | train | function | def _get_feature_config(feature_column):
"""Returns configuration for the base feature defined in feature_column."""
if not isinstance(feature_column, _FeatureColumn):
raise TypeError(
"feature_columns should only contain instances of _FeatureColumn. "
"Given column is {}".format(feature_column)... | def _get_feature_config(feature_column):
| """Returns configuration for the base feature defined in feature_column."""
if not isinstance(feature_column, _FeatureColumn):
raise TypeError(
"feature_columns should only contain instances of _FeatureColumn. "
"Given column is {}".format(feature_column))
if isinstance(feature_column, (_Spars... | )
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def _get_feature_config(feature_column):
| 64 | 64 | 133 | 8 | 56 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _get_feature_config | _get_feature_config | 1,710 | 1,723 | 1,710 | 1,710 | a0d98f751252b8e1871fcf89114b5627528c0d20 | bigcode/the-stack | train |
7ce12465b38a761f908c9699 | train | function | def one_hot_column(sparse_id_column):
"""Creates a _OneHotColumn.
Args:
sparse_id_column: A _SparseColumn which is created by
`sparse_column_with_*`
or crossed_column functions. Note that `combiner` defined in
`sparse_id_column` is ignored.
Returns:
An _OneHotColumn.
"""
re... | def one_hot_column(sparse_id_column):
| """Creates a _OneHotColumn.
Args:
sparse_id_column: A _SparseColumn which is created by
`sparse_column_with_*`
or crossed_column functions. Note that `combiner` defined in
`sparse_id_column` is ignored.
Returns:
An _OneHotColumn.
"""
return _OneHotColumn(sparse_id_column)
| _in_ckpt
return None
# pylint: disable=unused-argument
def _to_embedding_lookup_arguments(self, input_tensor):
raise ValueError("Column {} is not supported in linear models. "
"Please use sparse_column.".format(self))
def one_hot_column(sparse_id_column):
| 64 | 64 | 91 | 9 | 55 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | one_hot_column | one_hot_column | 853 | 865 | 853 | 853 | a23bb639ae365ed0e596e9246ca502e698f09f1c | bigcode/the-stack | train |
f93a021823592d6b55671604 | train | class | class _RealValuedColumn(_FeatureColumn, collections.namedtuple(
"_RealValuedColumn",
["column_name", "dimension", "default_value", "dtype", "normalizer"])):
"""Represents a real valued feature column also known as continuous features.
Instances of this class are immutable. A real valued column means featur... | class _RealValuedColumn(_FeatureColumn, collections.namedtuple(
"_RealValuedColumn",
["column_name", "dimension", "default_value", "dtype", "normalizer"])):
| """Represents a real valued feature column also known as continuous features.
Instances of this class are immutable. A real valued column means features are
dense. It means dictionary returned by InputBuilder contains a
("column_name", Tensor) pair. Tensor shape should be (batch_size, 1).
"""
def __new__(... | .")
combiner = "mean"
if (dimension < 1) or (size < 1):
raise ValueError("Dimension and size must be greater than 0. "
"dimension: {}, size: {}, column_name: {}".format(
dimension, size, column_name))
if combiner not in ("mean", "sqrtn", "sum"):
raise Value... | 182 | 182 | 609 | 41 | 141 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _RealValuedColumn | _RealValuedColumn | 1,103 | 1,173 | 1,103 | 1,105 | 905c0be670dfac72d0459cc28dcb665e8333107f | bigcode/the-stack | train |
624cd7f79bcc9d4f90fcf529 | train | function | def make_place_holder_tensors_for_base_features(feature_columns):
"""Returns placeholder tensors for inference.
Args:
feature_columns: An iterable containing all the feature columns. All items
should be instances of classes derived from _FeatureColumn.
Returns:
A dict mapping feature keys to Sparse... | def make_place_holder_tensors_for_base_features(feature_columns):
| """Returns placeholder tensors for inference.
Args:
feature_columns: An iterable containing all the feature columns. All items
should be instances of classes derived from _FeatureColumn.
Returns:
A dict mapping feature keys to SparseTensors (sparse columns) or
placeholder Tensors (dense columns... | dtype=feature.dtype,
allow_missing=(allow_missing_by_default or default_is_set))
else:
raise TypeError(
"Unsupported feature type: {}".format(type(feature).__name__))
sequence_feature_spec[key] = sequence_feature
return sequence_feature_spec
def make_place_holder_tensors_for_base_fe... | 67 | 67 | 226 | 12 | 54 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | make_place_holder_tensors_for_base_features | make_place_holder_tensors_for_base_features | 1,799 | 1,823 | 1,799 | 1,799 | c237dc1b36d74f43da39f1d4f3917221a6ec6bba | bigcode/the-stack | train |
482039a4bbdc98e3348c591b | train | class | class _SparseColumnHashed(_SparseColumn):
"""See `sparse_column_with_hash_bucket`."""
def __new__(cls,
column_name,
hash_bucket_size,
combiner="sum",
dtype=dtypes.string):
if dtype != dtypes.string and not dtype.is_integer:
raise ValueError("dtype ... | class _SparseColumnHashed(_SparseColumn):
| """See `sparse_column_with_hash_bucket`."""
def __new__(cls,
column_name,
hash_bucket_size,
combiner="sum",
dtype=dtypes.string):
if dtype != dtypes.string and not dtype.is_integer:
raise ValueError("dtype must be string or integer. "
... | ("The default value of combiner will change from \"sum\" "
"to \"sqrtn\" after 2016/11/01.")
combiner = "sum"
return _SparseColumnIntegerized(
column_name, bucket_size, combiner=combiner, dtype=dtype)
class _SparseColumnHashed(_SparseColumn):
| 73 | 73 | 246 | 10 | 63 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _SparseColumnHashed | _SparseColumnHashed | 416 | 447 | 416 | 416 | 102de0c44623a26b7a99bce33d6bc2926ab56cfa | bigcode/the-stack | train |
4d9be4006f23b233d2cfb5ec | train | function | def weighted_sparse_column(sparse_id_column,
weight_column_name,
dtype=dtypes.float32):
"""Creates a _SparseColumn by combining sparse_id_column with a weight column.
Args:
sparse_id_column: A `_SparseColumn` which is created by
`sparse_column_with_*`... | def weighted_sparse_column(sparse_id_column,
weight_column_name,
dtype=dtypes.float32):
| """Creates a _SparseColumn by combining sparse_id_column with a weight column.
Args:
sparse_id_column: A `_SparseColumn` which is created by
`sparse_column_with_*` functions.
weight_column_name: A string defining a sparse column name which represents
weight or value of the corresponding sparse ... | "
"Please use embedding_column or one_hot_column. column: {}".format(
self))
def _to_embedding_lookup_arguments(self, input_tensor):
return _EmbeddingLookupArguments(
input_tensor=self.id_tensor(input_tensor),
weight_tensor=self.weight_tensor(input_tensor),
vocab_size... | 104 | 104 | 347 | 21 | 83 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | weighted_sparse_column | weighted_sparse_column | 605 | 641 | 605 | 607 | 53b6e25f13fad9d36ca96d2a3966e5847a89bec2 | bigcode/the-stack | train |
485a01deeefcbc80e33d2559 | train | function | def _create_shared_embeddings(name, shape, dtype, initializer, trainable,
weight_collections):
"""Creates or reuse shared embedding variable.
If called within the scope of a partitioner, will partition the variable and
return a list of `tf.Variable`. If no partitioner is specified, ... | def _create_shared_embeddings(name, shape, dtype, initializer, trainable,
weight_collections):
| """Creates or reuse shared embedding variable.
If called within the scope of a partitioner, will partition the variable and
return a list of `tf.Variable`. If no partitioner is specified, returns a list
with just one variable.
Args:
name: A string specifying the name of the embedding variable.
shape... | is None or not callable.
"""
if name is None:
name = "weights"
if not initializer:
raise ValueError("initializer must be defined.")
if not callable(initializer):
raise ValueError("initializer must be callable.")
embeddings = contrib_variables.model_variable(
name=name,
shape=shape,
... | 162 | 162 | 542 | 21 | 140 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _create_shared_embeddings | _create_shared_embeddings | 1,915 | 1,978 | 1,915 | 1,916 | f7e6844db6746792deae117b8b578c0a686171b9 | bigcode/the-stack | train |
e1dd5ad76d6c76829ddbe222 | train | function | def sparse_column_with_keys(column_name, keys, default_value=-1,
combiner=None):
"""Creates a _SparseColumn with keys.
Look up logic is as follows:
lookup_id = index_of_feature_in_keys if feature in keys else default_value
Args:
column_name: A string defining sparse column name... | def sparse_column_with_keys(column_name, keys, default_value=-1,
combiner=None):
| """Creates a _SparseColumn with keys.
Look up logic is as follows:
lookup_id = index_of_feature_in_keys if feature in keys else default_value
Args:
column_name: A string defining sparse column name.
keys: a string list defining vocabulary.
default_value: The value to use for out-of-vocabulary feat... | insert_transformed_feature(self, columns_to_tensors):
"""Handles sparse column to id conversion."""
columns_to_tensors[self] = contrib_lookup_ops.string_to_index(
tensor=columns_to_tensors[self.name],
mapping=list(self.lookup_config.keys),
default_value=self.lookup_config.default_value,... | 87 | 87 | 290 | 20 | 67 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | sparse_column_with_keys | sparse_column_with_keys | 507 | 535 | 507 | 508 | 45989994cc97434d411074e78af8df13c2c5d0da | bigcode/the-stack | train |
1ad2671fdb5512d3d0f1aa95 | train | class | class _SparseColumnIntegerized(_SparseColumn):
"""See `sparse_column_with_integerized_feature`."""
def __new__(cls, column_name, bucket_size, combiner="sqrtn",
dtype=dtypes.int64):
if not dtype.is_integer:
raise ValueError("dtype must be an integer. "
"dtype: {}, colu... | class _SparseColumnIntegerized(_SparseColumn):
| """See `sparse_column_with_integerized_feature`."""
def __new__(cls, column_name, bucket_size, combiner="sqrtn",
dtype=dtypes.int64):
if not dtype.is_integer:
raise ValueError("dtype must be an integer. "
"dtype: {}, column_name: {}".format(dtype, column_name))
r... | self.dtype == other_column.dtype or
(self.dtype.is_integer and other_column.dtype.is_integer)))
if compatible:
logging.warn("Column {} and {} may not have the same vocabulary.".
format(self.name, other_column.name))
return compatible
class _SparseColumnIntegerized(_Sp... | 64 | 64 | 215 | 10 | 53 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _SparseColumnIntegerized | _SparseColumnIntegerized | 350 | 374 | 350 | 350 | 4b232e7ef9f1bb47ad1df7eaad5d8315eed25d9a | bigcode/the-stack | train |
3af44f393706dc7ab20b901b | train | class | class _OneHotColumn(_FeatureColumn,
collections.namedtuple("_OneHotColumn",
["sparse_id_column"])):
"""Represents a one-hot column for use in deep networks.
Args:
sparse_id_column: A _SparseColumn which is created by `sparse_column_with_*`
fu... | class _OneHotColumn(_FeatureColumn,
collections.namedtuple("_OneHotColumn",
["sparse_id_column"])):
| """Represents a one-hot column for use in deep networks.
Args:
sparse_id_column: A _SparseColumn which is created by `sparse_column_with_*`
function.
"""
@property
def name(self):
return "{}_one_hot".format(self.sparse_id_column.name)
@property
def length(self):
"""Returns vocabulary ... | weighted_sparse_column(words, "tfidf_score")
```
This configuration assumes that input dictionary of model contains the
following two items:
* (key="words", value=word_tensor) where word_tensor is a SparseTensor.
* (key="tfidf_score", value=tfidf_score_tensor) where tfidf_score_tensor
... | 186 | 186 | 620 | 26 | 160 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _OneHotColumn | _OneHotColumn | 644 | 718 | 644 | 646 | 927792f7e7053ab6975fc1a54bcd8069a6f0e280 | bigcode/the-stack | train |
ce057d4a2b7f3c5fb919b924 | train | class | class _EmbeddingLookupArguments(
collections.namedtuple("_EmbeddingLookupArguments",
["input_tensor",
"weight_tensor",
"vocab_size",
"initializer",
"combiner"])):
"""Represent... | class _EmbeddingLookupArguments(
collections.namedtuple("_EmbeddingLookupArguments",
["input_tensor",
"weight_tensor",
"vocab_size",
"initializer",
"combiner"])):
| """Represents the information needed from a column for embedding lookup.
Used to to compute DNN inputs and weighted sum.
"""
pass
| .python.ops import string_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
class _EmbeddingLookupArguments(
collections.namedtuple("_EmbeddingLookupArguments",
["input_tensor",
"weight_tensor",
... | 64 | 64 | 72 | 41 | 22 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _EmbeddingLookupArguments | _EmbeddingLookupArguments | 98 | 109 | 98 | 104 | 7a187da0010dcf562290c342cf8d814434cb10d3 | bigcode/the-stack | train |
416db4dfd512355c6fabde9a | train | function | def _create_sequence_feature_spec_for_parsing(sequence_feature_columns,
allow_missing_by_default=False):
"""Prepares a feature spec for parsing `tf.SequenceExample`s.
Args:
sequence_feature_columns: an iterable containing all the feature columns.
All items sh... | def _create_sequence_feature_spec_for_parsing(sequence_feature_columns,
allow_missing_by_default=False):
| """Prepares a feature spec for parsing `tf.SequenceExample`s.
Args:
sequence_feature_columns: an iterable containing all the feature columns.
All items should be instances of classes derived from `_FeatureColumn`.
allow_missing_by_default: whether to set `allow_missing=True` by default for
`Fix... | iterable containing all the feature columns. All items
should be instances of classes derived from _FeatureColumn.
Returns:
A dict mapping feature keys to FixedLenFeature or VarLenFeature values.
"""
features_config = {}
for column in feature_columns:
features_config.update(_get_feature_config(co... | 90 | 90 | 303 | 20 | 69 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _create_sequence_feature_spec_for_parsing | _create_sequence_feature_spec_for_parsing | 1,764 | 1,796 | 1,764 | 1,765 | 4276d9e20c4ffad62eddad831e429564a1e898e0 | bigcode/the-stack | train |
57c0572843c980ea5b497baa | train | function | def hashed_embedding_column(column_name,
size,
dimension,
combiner=None,
initializer=None):
"""Creates an embedding column of a sparse feature using parameter hashing.
The i-th embedding component of a v... | def hashed_embedding_column(column_name,
size,
dimension,
combiner=None,
initializer=None):
| """Creates an embedding column of a sparse feature using parameter hashing.
The i-th embedding component of a value v is found by retrieving an
embedding weight whose index is a fingerprint of the pair (v,i).
Args:
column_name: A string defining sparse column name.
size: An integer specifying the numb... | , columns_to_tensors):
columns_to_tensors[self] = columns_to_tensors[self.column_name]
def _to_dnn_input_layer(self,
input_tensor,
weight_collections=None,
trainable=True):
embeddings = _create_embeddings(
shape=[self.size]... | 144 | 144 | 483 | 22 | 122 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | hashed_embedding_column | hashed_embedding_column | 1,052 | 1,100 | 1,052 | 1,056 | 8eb904376d1d7e2bdcaf1f5c3d5fa86d76e90c0c | bigcode/the-stack | train |
2e24f2333a97c638ea0b35b4 | train | function | def crossed_column(columns, hash_bucket_size, combiner=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None):
"""Creates a _CrossedColumn.
Args:
columns: An iterable of _FeatureColumn. Items can be an instance of
_SparseColumn, _CrossedColumn, or _BucketizedColumn.... | def crossed_column(columns, hash_bucket_size, combiner=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None):
| """Creates a _CrossedColumn.
Args:
columns: An iterable of _FeatureColumn. Items can be an instance of
_SparseColumn, _CrossedColumn, or _BucketizedColumn.
hash_bucket_size: An int that is > 1. The number of buckets.
combiner: A combiner string, supports sum, mean, sqrtn.
ckpt_to_load_from: (... | self.ckpt_to_load_from is not None:
return self.ckpt_to_load_from, self.tensor_name_in_ckpt
return None
def _to_embedding_lookup_arguments(self, input_tensor):
return _EmbeddingLookupArguments(
input_tensor=input_tensor,
weight_tensor=None,
vocab_size=self.length,
initi... | 111 | 111 | 371 | 29 | 82 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | crossed_column | crossed_column | 1,598 | 1,634 | 1,598 | 1,600 | 629403cdf7eeb1814989a02f8c100697d1707230 | bigcode/the-stack | train |
765abe1890f14eafd216d88d | train | function | def sparse_column_with_integerized_feature(column_name,
bucket_size,
combiner=None,
dtype=dtypes.int64):
"""Creates an integerized _SparseColumn.
Use this when your features are already ... | def sparse_column_with_integerized_feature(column_name,
bucket_size,
combiner=None,
dtype=dtypes.int64):
| """Creates an integerized _SparseColumn.
Use this when your features are already pre-integerized into int64 IDs.
output_id = input_feature
Args:
column_name: A string defining sparse column name.
bucket_size: An int that is > 1. The number of buckets. It should be bigger
than maximum feature. In... | formed_feature(self, columns_to_tensors):
"""Handles sparse column to id conversion."""
sparse_id_values = math_ops.mod(columns_to_tensors[self.name].values,
self.bucket_size,
name="mod")
columns_to_tensors[self] = ops.SparseTensor(
... | 108 | 108 | 360 | 26 | 82 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | sparse_column_with_integerized_feature | sparse_column_with_integerized_feature | 377 | 413 | 377 | 380 | 6940d758017058ade0fefcdc2da5e02f9312ba7a | bigcode/the-stack | train |
215a14929280aadbebdb38ad | train | class | class _CrossedColumn(_FeatureColumn,
collections.namedtuple("_CrossedColumn",
["columns", "hash_bucket_size",
"combiner", "ckpt_to_load_from",
"tensor_name_in_ckpt"]... | class _CrossedColumn(_FeatureColumn,
collections.namedtuple("_CrossedColumn",
["columns", "hash_bucket_size",
"combiner", "ckpt_to_load_from",
"tensor_name_in_ckpt"]... | """Represents a cross transformation also known as conjuction or combination.
Instances of this class are immutable. It crosses given `columns`. Crossed
column output will be hashed to hash_bucket_size.
Conceptually, transformation can be thought as:
Hash(cartesian product of features in columns) % `hash_b... | _ops.to_int64(array_ops.transpose(array_ops.pack((i1, i2))))
shape = math_ops.to_int64(array_ops.pack([batch_size, dimension]))
sparse_id_values = ops.SparseTensor(indices, bucket_indices, shape)
return sparse_id_values
def _to_embedding_lookup_arguments(self, input_tensor):
return _EmbeddingLookupA... | 256 | 256 | 1,494 | 48 | 208 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _CrossedColumn | _CrossedColumn | 1,424 | 1,595 | 1,424 | 1,428 | 80593ee0d8cb99089433506c97f50a3d97cb3435 | bigcode/the-stack | train |
44d18ce5a8b5ba9fafdf03a0 | train | function | def create_feature_spec_for_parsing(feature_columns):
"""Helper that prepares features config from input feature_columns.
The returned feature config can be used as arg 'features' in tf.parse_example.
Typical usage example:
```python
# Define features and transformations
country = sparse_column_with_voca... | def create_feature_spec_for_parsing(feature_columns):
| """Helper that prepares features config from input feature_columns.
The returned feature config can be used as arg 'features' in tf.parse_example.
Typical usage example:
```python
# Define features and transformations
country = sparse_column_with_vocabulary_file("country", VOCAB_FILE)
age = real_valued... | . "
"Given column is {}".format(feature_column))
if isinstance(feature_column, (_SparseColumn, _WeightedSparseColumn,
_EmbeddingColumn, _RealValuedColumn,
_BucketizedColumn, _CrossedColumn,
_OneHotColumn)):
... | 94 | 94 | 315 | 10 | 84 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | create_feature_spec_for_parsing | create_feature_spec_for_parsing | 1,726 | 1,761 | 1,726 | 1,726 | 82af793ca1940351107d9f28cfd7867dcf067260 | bigcode/the-stack | train |
1215b3281ac91c05ea620914 | train | class | class _SparseColumnKeys(_SparseColumn):
"""See `sparse_column_with_keys`."""
def __new__(cls, column_name, keys, default_value=-1, combiner="sum"):
return super(_SparseColumnKeys, cls).__new__(
cls,
column_name,
combiner=combiner,
lookup_config=_SparseIdLookupConfig(
... | class _SparseColumnKeys(_SparseColumn):
| """See `sparse_column_with_keys`."""
def __new__(cls, column_name, keys, default_value=-1, combiner="sum"):
return super(_SparseColumnKeys, cls).__new__(
cls,
column_name,
combiner=combiner,
lookup_config=_SparseIdLookupConfig(
keys=keys, vocab_size=len(keys), defaul... | default value of combiner will change from \"sum\" "
"to \"sqrtn\" after 2016/11/01.")
combiner = "sum"
return _SparseColumnHashed(column_name, hash_bucket_size, combiner, dtype)
class _SparseColumnKeys(_SparseColumn):
| 64 | 64 | 168 | 9 | 55 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _SparseColumnKeys | _SparseColumnKeys | 486 | 504 | 486 | 486 | 85c70cf7829ef8d0d1acf955c02b63c618ce3150 | bigcode/the-stack | train |
af65c8c4098bd097e829b6c2 | train | function | def real_valued_column(column_name,
dimension=1,
default_value=None,
dtype=dtypes.float32,
normalizer=None):
"""Creates a _RealValuedColumn.
Args:
column_name: A string defining real valued column name.
dimension: A... | def real_valued_column(column_name,
dimension=1,
default_value=None,
dtype=dtypes.float32,
normalizer=None):
| """Creates a _RealValuedColumn.
Args:
column_name: A string defining real valued column name.
dimension: An integer specifying dimension of the real valued column.
The default is 1. The Tensor representing the _RealValuedColumn
will have the shape of [batch_size, dimension].
default_value: ... | columns_to_tensors: A mapping from feature columns to tensors. 'string'
key means a base feature (not-transformed). It can have _FeatureColumn
as a key too. That means that _FeatureColumn is already transformed.
"""
# Transform the input tensor according to the normalizer function + reshap... | 256 | 256 | 1,000 | 31 | 224 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | real_valued_column | real_valued_column | 1,176 | 1,277 | 1,176 | 1,180 | cd8608a9f6b45020fb39a570682f546a53de0ce3 | bigcode/the-stack | train |
628fd0543843538260e19254 | train | function | def _create_embedding_lookup(input_tensor, weight_tensor, vocab_size, dimension,
weight_collections, initializer, combiner,
trainable, name="weights",
is_shared_embedding=False):
"""Creates embedding variable and does a lookup.
... | def _create_embedding_lookup(input_tensor, weight_tensor, vocab_size, dimension,
weight_collections, initializer, combiner,
trainable, name="weights",
is_shared_embedding=False):
| """Creates embedding variable and does a lookup.
Args:
input_tensor: A `SparseTensor` which should contain sparse id to look up.
weight_tensor: A `SparseTensor` with the same shape and indices as
`input_tensor`, which contains the float weights corresponding to each
sparse id, or None if all we... | format(name))
else:
embeddings = contrib_variables.model_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
trainable=trainable,
collections=weight_collections)
graph.add_to_collection(shared_embedding_collection_name, embeddings)
if isin... | 147 | 147 | 492 | 40 | 106 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _create_embedding_lookup | _create_embedding_lookup | 1,981 | 2,034 | 1,981 | 1,984 | 92c6f08ec6847dcfe76e0917946d1c86bd2a188a | bigcode/the-stack | train |
e63534c36719a8be73a53e7b | train | function | def shared_embedding_columns(sparse_id_columns,
dimension,
combiner=None,
shared_embedding_name=None,
initializer=None,
ckpt_to_load_from=None,
te... | def shared_embedding_columns(sparse_id_columns,
dimension,
combiner=None,
shared_embedding_name=None,
initializer=None,
ckpt_to_load_from=None,
te... | """Creates a list of `_EmbeddingColumn` sharing the same embedding.
Args:
sparse_id_columns: An iterable of `_SparseColumn`, such as those created by
`sparse_column_with_*` or crossed_column functions. Note that `combiner`
defined in each sparse_id_column is ignored.
dimension: An integer speci... | variable initialization. If not specified, defaults to
`tf.truncated_normal_initializer` with mean 0.0 and standard deviation
1/sqrt(sparse_id_column.length).
ckpt_to_load_from: (Optional). String representing checkpoint name/pattern
to restore the column weights. Required if `tensor_name_in... | 256 | 256 | 914 | 43 | 213 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | shared_embedding_columns | shared_embedding_columns | 910 | 999 | 910 | 916 | 6ef6c9f0f857d677c67b7fddaa55b4e58cd4fb52 | bigcode/the-stack | train |
f9296bd3699df337f1832c98 | train | class | class _FeatureColumn(object):
"""Represents a feature column abstraction.
To distinguish the concept of a feature family and a specific binary feature
within a family, we refer to a feature family like "country" as a feature
column. For example "country:US" is a feature which is in "country" feature
column a... | class _FeatureColumn(object):
| """Represents a feature column abstraction.
To distinguish the concept of a feature family and a specific binary feature
within a family, we refer to a feature family like "country" as a feature
column. For example "country:US" is a feature which is in "country" feature
column and has a feature value ("US").... | collections
import math
from tensorflow.contrib.framework.python.framework import checkpoint_utils
from tensorflow.contrib.framework.python.framework import deprecation
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.layers.python.layers import embedding_ops
... | 249 | 249 | 831 | 6 | 242 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _FeatureColumn | _FeatureColumn | 112 | 208 | 112 | 112 | aee74ea2003453aa5e33673fa59ca41df6c4530a | bigcode/the-stack | train |
b863b44c71e521d7641cf629 | train | function | def embedding_column(sparse_id_column,
dimension,
combiner=None,
initializer=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None):
"""Creates an `_EmbeddingColumn`.
Args:
sparse_id_column: A `_SparseColu... | def embedding_column(sparse_id_column,
dimension,
combiner=None,
initializer=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None):
| """Creates an `_EmbeddingColumn`.
Args:
sparse_id_column: A `_SparseColumn` which is created by for example
`sparse_column_with_*` or crossed_column functions. Note that `combiner`
defined in `sparse_id_column` is ignored.
dimension: An integer specifying dimension of the embedding.
combine... | ))
def one_hot_column(sparse_id_column):
"""Creates a _OneHotColumn.
Args:
sparse_id_column: A _SparseColumn which is created by
`sparse_column_with_*`
or crossed_column functions. Note that `combiner` defined in
`sparse_id_column` is ignored.
Returns:
An _OneHotColumn.
"""... | 128 | 128 | 428 | 36 | 92 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | embedding_column | embedding_column | 868 | 907 | 868 | 873 | 25ac038e7b17536573185f2e6a15b5907a32a57c | bigcode/the-stack | train |
a924d2a29185a1d1db70a0a7 | train | class | class _WeightedSparseColumn(_FeatureColumn, collections.namedtuple(
"_WeightedSparseColumn",
["sparse_id_column", "weight_column_name", "dtype"])):
"""See `weighted_sparse_column`."""
def __new__(cls, sparse_id_column, weight_column_name, dtype):
return super(_WeightedSparseColumn, cls).__new__(cls, sp... | class _WeightedSparseColumn(_FeatureColumn, collections.namedtuple(
"_WeightedSparseColumn",
["sparse_id_column", "weight_column_name", "dtype"])):
| """See `weighted_sparse_column`."""
def __new__(cls, sparse_id_column, weight_column_name, dtype):
return super(_WeightedSparseColumn, cls).__new__(cls, sparse_id_column,
weight_column_name, dtype)
@property
def name(self):
return "{}_weighted_by_{}... | "sqrtn": do l2 normalization on features in the column
For more information: `tf.embedding_lookup_sparse`.
Returns:
A _SparseColumnKeys with keys configuration.
"""
if combiner is None:
logging.warn("The default value of combiner will change from \"sum\" "
"to \"sqrtn\" after 2016... | 150 | 150 | 500 | 35 | 115 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _WeightedSparseColumn | _WeightedSparseColumn | 538 | 602 | 538 | 540 | 14f6c74db1893165c300f63688786551b8e7eb34 | bigcode/the-stack | train |
aaf0945741d9bcb174683e7e | train | function | def _create_embeddings(shape,
dtype,
initializer,
trainable,
weight_collections,
name=None):
"""Creates embedding variable.
If called within the scope of a partitioner, will partition the variable and... | def _create_embeddings(shape,
dtype,
initializer,
trainable,
weight_collections,
name=None):
| """Creates embedding variable.
If called within the scope of a partitioner, will partition the variable and
return a list of `tf.Variable`. If no partitioner is specified, returns a list
with just one variable.
Args:
shape: shape of the embeddding. Note this is not the shape of partitioned
variabl... | _value=-1):
return super(_SparseIdLookupConfig, cls).__new__(cls, vocabulary_file, keys,
num_oov_buckets,
vocab_size, default_value)
def _add_variable_collection(weight_collections):
if weight_collections:... | 108 | 108 | 362 | 25 | 82 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _create_embeddings | _create_embeddings | 1,866 | 1,912 | 1,866 | 1,871 | 63c0f1a6cbd8ed3e0d48b1c96b99d8e6aad0e91f | bigcode/the-stack | train |
fa70bb29e52b4abf53d53ed6 | train | function | def bucketized_column(source_column, boundaries):
"""Creates a _BucketizedColumn.
Args:
source_column: A _RealValuedColumn defining dense column.
boundaries: A list of floats specifying the boundaries. It has to be sorted.
Returns:
A _BucketizedColumn.
Raises:
ValueError: if 'boundaries' is e... | def bucketized_column(source_column, boundaries):
| """Creates a _BucketizedColumn.
Args:
source_column: A _RealValuedColumn defining dense column.
boundaries: A list of floats specifying the boundaries. It has to be sorted.
Returns:
A _BucketizedColumn.
Raises:
ValueError: if 'boundaries' is empty or not sorted.
"""
return _BucketizedColu... | _embedding_lookup_arguments(self, input_tensor):
return _EmbeddingLookupArguments(
input_tensor=self.to_sparse_tensor(input_tensor),
weight_tensor=None,
vocab_size=self.length * self.source_column.dimension,
initializer=init_ops.zeros_initializer,
combiner="sum")
def bucketiz... | 64 | 64 | 93 | 9 | 55 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | bucketized_column | bucketized_column | 1,408 | 1,421 | 1,408 | 1,408 | 6fba8671590a34bb2bbebb46d789b720655fcd8a | bigcode/the-stack | train |
81195f6fd2bd35f4d6791b17 | train | class | class _HashedEmbeddingColumn(collections.namedtuple(
"_HashedEmbeddingColumn", ["column_name", "size", "dimension", "combiner",
"initializer"]), _EmbeddingColumn):
"""See `hashed_embedding_column`."""
def __new__(cls,
column_name,
size,
d... | class _HashedEmbeddingColumn(collections.namedtuple(
"_HashedEmbeddingColumn", ["column_name", "size", "dimension", "combiner",
"initializer"]), _EmbeddingColumn):
| """See `hashed_embedding_column`."""
def __new__(cls,
column_name,
size,
dimension,
combiner="sqrtn",
initializer=None):
if initializer is not None and not callable(initializer):
raise ValueError("initializer must be callable if specif... | _size = sparse_id_columns[0].length
embedded_columns = []
for column in sparse_id_columns:
embedded_columns.append(
_EmbeddingColumn(column, dimension, combiner, initializer,
ckpt_to_load_from, tensor_name_in_ckpt,
shared_embedding_name, sha... | 110 | 110 | 368 | 40 | 70 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _HashedEmbeddingColumn | _HashedEmbeddingColumn | 1,002 | 1,049 | 1,002 | 1,004 | 3233e5e7af7feac5294ef874d8f4f88654ed8c92 | bigcode/the-stack | train |
2089a6179c347339f5f92cf0 | train | function | def sparse_column_with_hash_bucket(column_name,
hash_bucket_size,
combiner=None,
dtype=dtypes.string):
"""Creates a _SparseColumn with hashed bucket configuration.
Use this when your sparse features are in stri... | def sparse_column_with_hash_bucket(column_name,
hash_bucket_size,
combiner=None,
dtype=dtypes.string):
| """Creates a _SparseColumn with hashed bucket configuration.
Use this when your sparse features are in string or integer format, but you
don't have a vocab file that maps each value to an integer ID.
output_id = Hash(input_feature_string) % bucket_size
Args:
column_name: A string defining sparse column ... | _integer:
sparse_values = string_ops.as_string(sparse_tensor.values)
else:
sparse_values = sparse_tensor.values
sparse_id_values = string_ops.string_to_hash_bucket_fast(
sparse_values, self.bucket_size, name="lookup")
columns_to_tensors[self] = ops.SparseTensor(
sparse_tensor.in... | 102 | 102 | 341 | 25 | 77 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | sparse_column_with_hash_bucket | sparse_column_with_hash_bucket | 450 | 483 | 450 | 453 | 4dbafab92f313010c591411cbaf2bd03eb394fe0 | bigcode/the-stack | train |
03cb60c55c9c123f710d4470 | train | function | def _add_variable_collection(weight_collections):
if weight_collections:
weight_collections = list(
set(list(weight_collections) + [ops.GraphKeys.VARIABLES]))
return weight_collections
| def _add_variable_collection(weight_collections):
| if weight_collections:
weight_collections = list(
set(list(weight_collections) + [ops.GraphKeys.VARIABLES]))
return weight_collections
| ,
num_oov_buckets=0,
vocab_size=None,
default_value=-1):
return super(_SparseIdLookupConfig, cls).__new__(cls, vocabulary_file, keys,
num_oov_buckets,
vocab_size, defa... | 64 | 64 | 45 | 9 | 55 | steven0820/tensorflow | tensorflow/contrib/layers/python/layers/feature_column.py | Python | _add_variable_collection | _add_variable_collection | 1,859 | 1,863 | 1,859 | 1,859 | 2ec448af93caf7b7aeb7199963c2f40fca038dd6 | bigcode/the-stack | train |
8d9f0b634cb477131df912e9 | train | function | def message(err_number):
"""Return the error message associated with the error code. Positive
error codes are interpreted as system error numbers, and
negative error codes are interpreted as GEOPM error numbers.
Args:
err_number (int): Error code to be interpreted.
Returns:
str: E... | def message(err_number):
| """Return the error message associated with the error code. Positive
error codes are interpreted as system error numbers, and
negative error codes are interpreted as GEOPM error numbers.
Args:
err_number (int): Error code to be interpreted.
Returns:
str: Error message associated w... | _dl.GEOPM_ERROR_MSR_WRITE
ERROR_AGENT_UNSUPPORTED = _dl.GEOPM_ERROR_AGENT_UNSUPPORTED
ERROR_AFFINITY = _dl.GEOPM_ERROR_AFFINITY
ERROR_NO_AGENT = _dl.GEOPM_ERROR_NO_AGENT
def message(err_number):
| 64 | 64 | 136 | 5 | 58 | avilcheslopez/geopm | service/geopmdpy/error.py | Python | message | message | 46 | 63 | 46 | 46 | 1767a9ec534539b5465997ee3d087e3fc64a973f | bigcode/the-stack | train |
38c1dfa6bca8070149c842a8 | train | class | class TransverseIsotropic(BaseConstitutive):
def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E2/(2*(1+self.nu23))
D11 = np.ones((3,3))
D11[0,0] *= 1./self.E1
D11[1,1... | class TransverseIsotropic(BaseConstitutive):
| def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E2/(2*(1+self.nu23))
D11 = np.ones((3,3))
D11[0,0] *= 1./self.E1
D11[1,1] *= 1./self.E2
D11[2,2] *= 1./self.E2... | 1,2))
D22 = np.array([fc2]).reshape((1,1))
self.De = fc1*np.vstack([np.hstack([D11,D12]),np.hstack([D21,D22])])
def getStress(self, deformation):
sigma = np.matmul(self.De, deformation.eps)
return sigma, self.De
def getTangent(self):
return self.De
# Cell
class Transv... | 100 | 100 | 334 | 10 | 89 | cfgarciar/geomechy | geomechy/constitutive.py | Python | TransverseIsotropic | TransverseIsotropic | 86 | 117 | 86 | 87 | cbfe88afd72eaad2ca715d23370f0ff78d5c658a | bigcode/the-stack | train |
70cc568690362391c43863b7 | train | class | class MMC(BaseConstitutive):
def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(3)-np.eye(3))+(1-self.... | class MMC(BaseConstitutive):
| def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(3)-np.eye(3))+(1-self.nu)*np.eye(3)
D12 = np... | .inv(np.block([[D11,D12],[D21,D22]]))
def getStress(self, deformation):
sigma = np.matmul(self.De, deformation.eps)
return sigma, self.De
def getElasticMatrix(self):
return self.De
# Cell
class MMC(BaseConstitutive):
| 64 | 64 | 212 | 7 | 56 | cfgarciar/geomechy | geomechy/constitutive.py | Python | MMC | MMC | 120 | 148 | 120 | 121 | 7aaeaf9064b2546fa707e2b2d0e7a1af6ff0782d | bigcode/the-stack | train |
437b85700ec0b963811bb158 | train | class | class PlaneStrain(BaseConstitutive):
def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(2)-np.eye(2))+... | class PlaneStrain(BaseConstitutive):
| def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(2)-np.eye(2))+(1-self.nu)*np.eye(2)
D12 = np... | *np.block([[D11,D12],[D21,D22]])
def getStress(self, deformation):
sigma = np.matmul(self.De, deformation.eps)
return sigma, self.De
def getElasticMatrix(self):
return self.De
# Cell
class PlaneStrain(BaseConstitutive):
| 64 | 64 | 209 | 9 | 54 | cfgarciar/geomechy | geomechy/constitutive.py | Python | PlaneStrain | PlaneStrain | 36 | 58 | 36 | 37 | 6ebd182ce6e969a83eef0c7401daaa29ace19cb7 | bigcode/the-stack | train |
a4b166b0fc14937aa59d876d | train | class | class Elastic(BaseConstitutive):
def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(3)-np.eye(3))+(1-s... | class Elastic(BaseConstitutive):
| def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/((1+self.nu)*(1-2*self.nu))
fc2 = (1-2*self.nu)/2
D11 = self.nu*(np.ones(3)-np.eye(3))+(1-self.nu)*np.eye(3)
D12 = np... | otherwise specified).
__all__ = ['Elastic', 'PlaneStrain', 'PlaneStress', 'TransverseIsotropic', 'MMC']
# Cell
import numpy as np
from .base import BaseConstitutive, Properties
from .io import jsonReader
# Cell
class Elastic(BaseConstitutive):
| 64 | 64 | 190 | 7 | 56 | cfgarciar/geomechy | geomechy/constitutive.py | Python | Elastic | Elastic | 11 | 33 | 11 | 12 | 093194331d1a0c3c665c34504a5009d6b7b14eda | bigcode/the-stack | train |
a910970b58c00177d96a9262 | train | class | class PlaneStress(BaseConstitutive):
def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/(1-self.nu**2)
fc2 = 1-self.nu
D11 = self.nu*(np.ones(2)-np.eye(2))+np.eye(2)
D... | class PlaneStress(BaseConstitutive):
| def __init__(self, props):
#Call the BaseMaterial constructor
BaseConstitutive.__init__(self, props)
#Create the hookean matrix
fc1 = self.E/(1-self.nu**2)
fc2 = 1-self.nu
D11 = self.nu*(np.ones(2)-np.eye(2))+np.eye(2)
D12 = np.zeros((2,1))
D21 = np.... | 11,D12]),np.hstack([D21,D22])])
def getStress(self, deformation):
sigma = np.matmul(self.De, deformation.eps)
return sigma, self.De
def getElasticMatrix(self):
return self.De
# Cell
class PlaneStress(BaseConstitutive):
| 64 | 64 | 194 | 8 | 55 | cfgarciar/geomechy | geomechy/constitutive.py | Python | PlaneStress | PlaneStress | 61 | 83 | 61 | 62 | 3cad9dbe0a9472d4024afbc5198b49428d407076 | bigcode/the-stack | train |
2438a328c9b524094d2706b0 | train | class | class PacketError(SyntaxError):
def __init__(self, code):
self.__code = code
def getReason(self):
return _packetErrors[self.__code]
def getCode(self):
return self.__code
| class PacketError(SyntaxError):
| def __init__(self, code):
self.__code = code
def getReason(self):
return _packetErrors[self.__code]
def getCode(self):
return self.__code
| packet type",
"102": "Type of packet type is not a str",
"103": "Packet type is over " + str(_maxPacketTypeLength) + " characters",
"200": "No content",
"300": "Internal server error!"
}
class PacketError(SyntaxError):
| 64 | 64 | 50 | 7 | 57 | abc123me/nasa_dsn | pynet/shared.py | Python | PacketError | PacketError | 17 | 23 | 17 | 17 | 6b6c513cca49c59c9269c135075adb0e564985c4 | bigcode/the-stack | train |
77506fda1c4aca96fb15a3c6 | train | class | class PacketFormatter:
def checkType(t):
if t == None:
raise PacketError(100)
if type(t) != type("str"):
raise PacketError(102)
if len(t) > _maxPacketTypeLength:
raise PacketError(103)
t = t.lower().strip()
if t not in _allowedPacketTypes:
... | class PacketFormatter:
| def checkType(t):
if t == None:
raise PacketError(100)
if type(t) != type("str"):
raise PacketError(102)
if len(t) > _maxPacketTypeLength:
raise PacketError(103)
t = t.lower().strip()
if t not in _allowedPacketTypes:
raise Packe... | "102": "Type of packet type is not a str",
"103": "Packet type is over " + str(_maxPacketTypeLength) + " characters",
"200": "No content",
"300": "Internal server error!"
}
class PacketError(SyntaxError):
def __init__(self, code):
self.__code = code
def getReason(self):
return _pac... | 107 | 107 | 359 | 4 | 102 | abc123me/nasa_dsn | pynet/shared.py | Python | PacketFormatter | PacketFormatter | 25 | 63 | 25 | 25 | f55bcb2e0b1807582b4fc88bb340a8855cb559e9 | bigcode/the-stack | train |
6a342f54c5c409845d439ece | train | class | class AppDialog(dialog.Dialog):
"The dialog box for the application"
def __init__(self, id, dll=None):
self.iconId = win32ui.IDR_MAINFRAME
dialog.Dialog.__init__(self, id, dll)
def OnInitDialog(self):
return dialog.Dialog.OnInitDialog(self)
# Provide support for a dlg app using an icon
def OnPain... | class AppDialog(dialog.Dialog):
| "The dialog box for the application"
def __init__(self, id, dll=None):
self.iconId = win32ui.IDR_MAINFRAME
dialog.Dialog.__init__(self, id, dll)
def OnInitDialog(self):
return dialog.Dialog.OnInitDialog(self)
# Provide support for a dlg app using an icon
def OnPaint(self):
if not self.IsIconic(... | # dlgappcore.
#
# base classes for dialog based apps.
import app
import win32ui
import win32con
import win32api
import sys
from pywin.mfc import dialog
error = "Dialog Application Error"
class AppDialog(dialog.Dialog):
| 56 | 93 | 311 | 6 | 50 | zhanqxun/cv_fish | pythonwin/pywin/framework/dlgappcore.py | Python | AppDialog | AppDialog | 14 | 44 | 14 | 14 | b8751699a08470254beabb87e7b18a22ac98aa86 | bigcode/the-stack | train |
3c4ff9286877a3946d007d3c | train | class | class DialogApp(app.CApp):
"An application class, for an app with main dialog box"
def InitInstance(self):
# win32ui.SetProfileFileName('dlgapp.ini')
win32ui.LoadStdProfileSettings()
win32ui.EnableControlContainer()
win32ui.Enable3dControls()
self.dlg = self.frame = self.CreateDialog()
if self.f... | class DialogApp(app.CApp):
| "An application class, for an app with main dialog box"
def InitInstance(self):
# win32ui.SetProfileFileName('dlgapp.ini')
win32ui.LoadStdProfileSettings()
win32ui.EnableControlContainer()
win32ui.Enable3dControls()
self.dlg = self.frame = self.CreateDialog()
if self.frame is None:
raise erro... | if self.IsIconic():
return 1
else:
return self._obj_.OnEraseBkgnd(dc)
def OnQueryDragIcon(self):
return win32ui.GetApp().LoadIcon(self.iconId)
def PreDoModal(self):
pass
class DialogApp(app.CApp):
| 64 | 64 | 152 | 7 | 56 | zhanqxun/cv_fish | pythonwin/pywin/framework/dlgappcore.py | Python | DialogApp | DialogApp | 47 | 68 | 47 | 47 | f9b849c4ecf463026a6b54e3540c019175e4164a | bigcode/the-stack | train |
103ba295ed8b96d3effefb2c | train | function | def add_args(parser, cfg, prefix=''):
for k, v in cfg.items():
if isinstance(v, str):
parser.add_argument('--' + prefix + k)
elif isinstance(v, int):
parser.add_argument('--' + prefix + k, type=int)
elif isinstance(v, float):
parser.add_argument('--' + pre... | def add_args(parser, cfg, prefix=''):
| for k, v in cfg.items():
if isinstance(v, str):
parser.add_argument('--' + prefix + k)
elif isinstance(v, int):
parser.add_argument('--' + prefix + k, type=int)
elif isinstance(v, float):
parser.add_argument('--' + prefix + k, type=float)
elif isin... | except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no "
f"attribute '{name}'")
except Exception as e:
ex = e
else:
return value
raise ex
def add_args(parser, cfg, prefix=''):
| 64 | 64 | 178 | 10 | 53 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | add_args | add_args | 99 | 115 | 99 | 99 | 204b7a8d56d7553437070e22d17c690fbd64e03c | bigcode/the-stack | train |
4831d06cbfd2f5591649d162 | train | class | class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no "
... | class ConfigDict(Dict):
| def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no "
f"attribute '{... | _imports:
warnings.warn(f'{imp} failed to import and is ignored.',
UserWarning)
imported_tmp = None
else:
raise ImportError
imported.append(imported_tmp)
if single_import:
imported = imported[0]
return impo... | 64 | 64 | 102 | 6 | 57 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | ConfigDict | ConfigDict | 81 | 96 | 81 | 82 | 7c3cf5471071e40dc87b841a271e16d1c101a3fd | bigcode/the-stack | train |
2b9ca8432956f80ae67f3d69 | train | class | class DictAction(Action):
"""
argparse action to split an argument into KEY=VALUE form
on the first = and append to a dictionary. List options can
be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit
brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build
l... | class DictAction(Action):
| """
argparse action to split an argument into KEY=VALUE form
on the first = and append to a dictionary. List options can
be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit
brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build
list/tuple values. e.g. 'KE... | cfg_dict == dict(pipeline=[
... dict(type='SelfLoadImage'), dict(type='LoadAnnotations')])
Args:
options (dict): dict of configs to merge from.
allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
are allowed in ``options`` and will replace the... | 231 | 231 | 770 | 5 | 226 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | DictAction | DictAction | 541 | 632 | 541 | 541 | 0862433f66b4f3e414e61a1b92f6851222b9914c | bigcode/the-stack | train |
a85b2d57885aa19d5ca7ce93 | train | class | class Config:
"""A facility for config and config files.
It supports common file formats as configs: python/json/yaml. The interface
is the same as a dict object and also allows access config values as
attributes.
Example:
>>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
>>> cfg.a
... | class Config:
| """A facility for config and config files.
It supports common file formats as configs: python/json/yaml. The interface
is the same as a dict object and also allows access config values as
attributes.
Example:
>>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
>>> cfg.a
1
... | self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no "
f"attribute '{name}'")
except Exception as e:
ex = e
else:
... | 256 | 256 | 3,615 | 3 | 252 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | Config | Config | 118 | 538 | 118 | 118 | 7fe1d8e1291936be313a3124303624fa6ec14a0b | bigcode/the-stack | train |
a18ab8c50dad26b9b1c27939 | train | function | def import_modules_from_strings(imports, allow_failed_imports=False):
"""Import modules from the given list of strings.
Args:
imports (list | str | None): The given module names to be imported.
allow_failed_imports (bool): If True, the failed imports will return
None. Otherwise, an ... | def import_modules_from_strings(imports, allow_failed_imports=False):
| """Import modules from the given list of strings.
Args:
imports (list | str | None): The given module names to be imported.
allow_failed_imports (bool): If True, the failed imports will return
None. Otherwise, an ImportError is raise. Default: False.
Returns:
list[modul... | Code
if platform.system() == 'Windows':
import regex as re
else:
import re
BASE_KEY = '_base_'
DELETE_KEY = '_delete_'
RESERVED_KEYS = ['filename', 'text', 'pretty_text']
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
if not osp.isfile(filename):
raise FileNotFoundError(ms... | 100 | 100 | 336 | 14 | 86 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | import_modules_from_strings | import_modules_from_strings | 34 | 79 | 34 | 34 | 3f28ba393293a52cb455cdcf0173c6be75f6cc87 | bigcode/the-stack | train |
f5b5696fd8cbd17f7a14a7df | train | function | def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
if not osp.isfile(filename):
raise FileNotFoundError(msg_tmpl.format(filename))
| def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
| if not osp.isfile(filename):
raise FileNotFoundError(msg_tmpl.format(filename))
| platform.system() == 'Windows':
import regex as re
else:
import re
BASE_KEY = '_base_'
DELETE_KEY = '_delete_'
RESERVED_KEYS = ['filename', 'text', 'pretty_text']
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
| 64 | 64 | 36 | 17 | 47 | shinianzhihou/change_detection.pytorch | cd_core/utils/config.py | Python | check_file_exist | check_file_exist | 29 | 31 | 29 | 29 | 363053fb1895632ac8f3246690ecfa0f0ac3c291 | bigcode/the-stack | train |
b8e7d5054acdd28a34bced7c | train | function | def checksum(content: str):
import hashlib
m = hashlib.md5(content.encode())
return m.hexdigest()
| def checksum(content: str):
| import hashlib
m = hashlib.md5(content.encode())
return m.hexdigest()
| save_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
with open(filepath, 'w') as fh:
fh.write('')
def has_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
return os.path.exists(filepath)
def checksum(content: str):
| 64 | 64 | 25 | 6 | 58 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | checksum | checksum | 92 | 95 | 92 | 92 | cc100b5477584b8b059d1f138cb626fc33271ee9 | bigcode/the-stack | train |
8236f6493a622bb8c2cec2dc | train | function | def save_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
with open(filepath, 'w') as fh:
fh.write('')
| def save_checkpoint(file_loc, content):
| filepath = cache_location(content, file_loc)
with open(filepath, 'w') as fh:
fh.write('')
| _location(content, file_loc):
os.makedirs('/tmp/graphql_lint', 0o777, exist_ok=True)
filepath = os.path.join('/tmp/graphql_lint', f'._gql_check_{checksum(file_loc)}.{checksum(content)}')
return filepath
def save_checkpoint(file_loc, content):
| 64 | 64 | 33 | 8 | 55 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | save_checkpoint | save_checkpoint | 81 | 84 | 81 | 81 | 1e70e458218e6e46103f5eb39655e5f7eeceecb8 | bigcode/the-stack | train |
b7144d95e1aef79b9989ebf3 | train | class | class GraphQLLint(TestCase):
def test_graphql_lint(self):
if not is_formatter_available():
print("GRAPHQL FORMATTER NOT AVAILABLE. (please install prettier first)")
print("SKIP GRAPHQL LINT")
return
print("\n---- start to lint graphql ----")
for filename... | class GraphQLLint(TestCase):
| def test_graphql_lint(self):
if not is_formatter_available():
print("GRAPHQL FORMATTER NOT AVAILABLE. (please install prettier first)")
print("SKIP GRAPHQL LINT")
return
print("\n---- start to lint graphql ----")
for filename, c in source_contents():
... | , files in os.walk(project_dir):
for f in files:
if f.endswith('.py'):
p = os.path.join(root, f)
with open(p, 'r') as fh:
content = fh.read()
yield p, content
break
class GraphQLLint(TestCase):
| 64 | 64 | 92 | 7 | 56 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | GraphQLLint | GraphQLLint | 110 | 121 | 110 | 111 | 227b48e0ff513b5cfebcfe49bc946b8326c3606a | bigcode/the-stack | train |
b3424d2bce368bdadf1a566f | train | function | def is_run_in_ci():
return os.environ.get('CI', 'false') == 'true'
| def is_run_in_ci():
| return os.environ.get('CI', 'false') == 'true'
| import ast
import os
import re
import textwrap
from unittest import TestCase
from tests.graphql_formatter import is_formatter_available, format_graphql
def is_run_in_ci():
| 39 | 64 | 21 | 6 | 32 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | is_run_in_ci | is_run_in_ci | 10 | 11 | 10 | 10 | a535604b56a16694e085eb7d140ec90400a779d0 | bigcode/the-stack | train |
ed03a5ee2af057ea448d4d61 | train | function | def source_contents():
project_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '../primehub'))
for root, dirs, files in os.walk(project_dir):
for f in files:
if f.endswith('.py'):
p = os.path.join(root, f)
with open(p, 'r') as fh:
... | def source_contents():
| project_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '../primehub'))
for root, dirs, files in os.walk(project_dir):
for f in files:
if f.endswith('.py'):
p = os.path.join(root, f)
with open(p, 'r') as fh:
content = fh.read... | w') as fh:
fh.write('')
def has_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
return os.path.exists(filepath)
def checksum(content: str):
import hashlib
m = hashlib.md5(content.encode())
return m.hexdigest()
def source_contents():
| 64 | 64 | 87 | 4 | 60 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | source_contents | source_contents | 98 | 107 | 98 | 98 | bcb67d68024184be9fe338b58513224728a1c3ac | bigcode/the-stack | train |
bce9ae18a182d9f056ae873f | train | function | def strip_blank_line(formatted):
return '\n'.join([x for x in formatted.split('\n') if x.strip() != ''])
| def strip_blank_line(formatted):
| return '\n'.join([x for x in formatted.split('\n') if x.strip() != ''])
| line in node.value.s.split('\n'):
if line.strip() == '':
continue
m = re.search(r'^(\s+).*', line)
if m:
first_line_indent = len(m.group(1))
break
return first_line_indent
def strip_blank_line(formatted):
| 64 | 64 | 30 | 7 | 56 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | strip_blank_line | strip_blank_line | 71 | 72 | 71 | 71 | 397ca7cd9fdd4fcab3863e2fbaf8ee3248d5528b | bigcode/the-stack | train |
b8f2d2a97bf8fc7786227323 | train | function | def has_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
return os.path.exists(filepath)
| def has_checkpoint(file_loc, content):
| filepath = cache_location(content, file_loc)
return os.path.exists(filepath)
| int', f'._gql_check_{checksum(file_loc)}.{checksum(content)}')
return filepath
def save_checkpoint(file_loc, content):
filepath = cache_location(content, file_loc)
with open(filepath, 'w') as fh:
fh.write('')
def has_checkpoint(file_loc, content):
| 63 | 64 | 25 | 8 | 56 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | has_checkpoint | has_checkpoint | 87 | 89 | 87 | 87 | e620fd96b04983c3ccfb863d71e32d3b2449cd0a | bigcode/the-stack | train |
b2a8a8b65c5fa73fcb292057 | train | class | class GraphQLQueryFormatChecker(ast.NodeTransformer):
def __init__(self, testutil: TestCase, filename: str):
self.testutil = testutil
self.filename = filename
def visit_Assign(self, node):
try:
n = node.targets[0]
if not hasattr(n, 'id'):
return... | class GraphQLQueryFormatChecker(ast.NodeTransformer):
| def __init__(self, testutil: TestCase, filename: str):
self.testutil = testutil
self.filename = filename
def visit_Assign(self, node):
try:
n = node.targets[0]
if not hasattr(n, 'id'):
return node
if n.id != 'query':
... | import ast
import os
import re
import textwrap
from unittest import TestCase
from tests.graphql_formatter import is_formatter_available, format_graphql
def is_run_in_ci():
return os.environ.get('CI', 'false') == 'true'
class GraphQLQueryFormatChecker(ast.NodeTransformer):
| 64 | 113 | 378 | 10 | 54 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | GraphQLQueryFormatChecker | GraphQLQueryFormatChecker | 14 | 68 | 14 | 15 | f8f79a3b768364643d8870fc3488b488e3177b50 | bigcode/the-stack | train |
c39ddf25c0720f1c7cc15df1 | train | function | def cache_location(content, file_loc):
os.makedirs('/tmp/graphql_lint', 0o777, exist_ok=True)
filepath = os.path.join('/tmp/graphql_lint', f'._gql_check_{checksum(file_loc)}.{checksum(content)}')
return filepath
| def cache_location(content, file_loc):
| os.makedirs('/tmp/graphql_lint', 0o777, exist_ok=True)
filepath = os.path.join('/tmp/graphql_lint', f'._gql_check_{checksum(file_loc)}.{checksum(content)}')
return filepath
| )
if m:
first_line_indent = len(m.group(1))
break
return first_line_indent
def strip_blank_line(formatted):
return '\n'.join([x for x in formatted.split('\n') if x.strip() != ''])
def cache_location(content, file_loc):
| 63 | 64 | 58 | 8 | 55 | InfuseAI/primehub-python-sdk | tests/test_graphql_lint.py | Python | cache_location | cache_location | 75 | 78 | 75 | 75 | afd4a2ebe416c7da89182f654c282da9bf9fd55e | bigcode/the-stack | train |
64c321fe31a24fc17fbdeec9 | train | function | def sort_array(arr):
low, mid = 0, 0
high = len(arr) - 1
i = 0
while i < len(arr):
if array[mid] == 0:
arr[mid], arr[low] = arr[low], arr[mid]
low += 1
mid += 1
elif arr[mid] == 2:
arr[mid], arr[high] = arr[high], arr[mid]
high ... | def sort_array(arr):
| low, mid = 0, 0
high = len(arr) - 1
i = 0
while i < len(arr):
if array[mid] == 0:
arr[mid], arr[low] = arr[low], arr[mid]
low += 1
mid += 1
elif arr[mid] == 2:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
else:
... | from DSA.template.template import *
def sort_array(arr):
| 12 | 64 | 122 | 5 | 7 | RohanMiraje/DSAwithPython | DSA/arrays/gfg_practise/sort_array_of_0_1_2_s.py | Python | sort_array | sort_array | 4 | 18 | 4 | 4 | 8a5aceb7e22d662f4b500045c87c1212dd474179 | bigcode/the-stack | train |
2543fd6fc79a2665d13e88ba | train | class | class Select(Field, HasSelectOptions):
fieldtype_config = {
"handle": "select",
"index_component": "tags",
}
| class Select(Field, HasSelectOptions):
| fieldtype_config = {
"handle": "select",
"index_component": "tags",
}
| from src.form_builder.fieldtypes.HasSelectOptions import HasSelectOptions
from ..Field import Field
class Select(Field, HasSelectOptions):
| 28 | 64 | 31 | 8 | 19 | girardinsamuel/masonite-form-builder | src/form_builder/fieldtypes/Select.py | Python | Select | Select | 5 | 10 | 5 | 6 | b6c812944cf2eca90a13f0c9c567d43ce88d11c2 | bigcode/the-stack | train |
afc3319bdce7d5dc8bfa7bb4 | train | class | class MoleculeCleanTest(TestCase):
def test_clean_db(self):
# clean should remove any molecules without a standard
m1 = Molecule(name='TestMolecule1', sum_formula="C1H2O3")
m1.save()
m2 = Molecule(name='TestMolecule2', sum_formula="C2H2O3")
m2.save()
s1 = Standard(mol... | class MoleculeCleanTest(TestCase):
| def test_clean_db(self):
# clean should remove any molecules without a standard
m1 = Molecule(name='TestMolecule1', sum_formula="C1H2O3")
m1.save()
m2 = Molecule(name='TestMolecule2', sum_formula="C2H2O3")
m2.save()
s1 = Standard(molecule=m1, inventory_id="0")
... | import logging
from django.test import TestCase
from standards_review.models import Molecule, Standard, Dataset, ProcessingError
from standards_review.tools import clear_molecules_without_standard, DatabaseLogHandler
class MoleculeCleanTest(TestCase):
| 48 | 64 | 123 | 8 | 39 | andy-d-palmer/mcf_standard_browse | mcf_standard_browser/standards_review/test_tools.py | Python | MoleculeCleanTest | MoleculeCleanTest | 9 | 19 | 9 | 9 | a7bb7352847d6caeb718c56b3c752f63f20ebf52 | bigcode/the-stack | train |
99f5e40a03d7083371071a79 | train | class | class DatabaseLogHandlerTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.d1 = Dataset(name='foo')
cls.d1.save()
def test_writes_to_database(self):
msg = "Foo message"
self.assertFalse(ProcessingError.objects.filter(message=msg, dataset=self.d1).exists())
reco... | class DatabaseLogHandlerTest(TestCase):
@classmethod
| def setUpTestData(cls):
cls.d1 = Dataset(name='foo')
cls.d1.save()
def test_writes_to_database(self):
msg = "Foo message"
self.assertFalse(ProcessingError.objects.filter(message=msg, dataset=self.d1).exists())
record = logging.makeLogRecord({"msg": msg})
h1 = Dat... | 2H2O3")
m2.save()
s1 = Standard(molecule=m1, inventory_id="0")
s1.save()
clear_molecules_without_standard()
self.assertEqual(Molecule.objects.all().count(), 1)
class DatabaseLogHandlerTest(TestCase):
@classmethod
| 64 | 64 | 122 | 12 | 52 | andy-d-palmer/mcf_standard_browse | mcf_standard_browser/standards_review/test_tools.py | Python | DatabaseLogHandlerTest | DatabaseLogHandlerTest | 22 | 34 | 22 | 23 | f9e8ba2f2824ec4346af1173cd9db56887f17ddf | bigcode/the-stack | train |
671a9a4533882f599551421b | train | function | def get_attributes_and_properties(class_instance):
attributes = []
properties = []
cached_properties = []
functions = []
for val in dir(class_instance.__class__):
if val.startswith("_"):
continue
attr = getattr(class_instance.__class__, val)
if isinstance(attr, m... | def get_attributes_and_properties(class_instance):
| attributes = []
properties = []
cached_properties = []
functions = []
for val in dir(class_instance.__class__):
if val.startswith("_"):
continue
attr = getattr(class_instance.__class__, val)
if isinstance(attr, mirdata.core.cached_property):
cached_pr... | "RM-C003",
"rwc_jazz": "RM-J004",
"rwc_popular": "RM-P001",
"salami": "2",
"tinysol": "Fl-ord-C4-mf-N-T14d",
}
def get_attributes_and_properties(class_instance):
| 64 | 64 | 202 | 8 | 56 | ooyamatakehisa/mirdata | scripts/print_track_docstring.py | Python | get_attributes_and_properties | get_attributes_and_properties | 30 | 62 | 30 | 30 | cb3b63650eb99336da7fc59d22a3bbe9235ff3b5 | bigcode/the-stack | train |
a8891530157fdbabd610468b | train | function | def main(args):
data_home = "tests/resources/mir_datasets/{}".format(dataset.name)
print(data_home)
dataset = mirdata.initialize(args.dataset, data_home=data_home)
if args.dataset in TEST_TRACKIDS.keys():
track_id = TEST_TRACKIDS[args.dataset]
else:
print("No test track found for {... | def main(args):
| data_home = "tests/resources/mir_datasets/{}".format(dataset.name)
print(data_home)
dataset = mirdata.initialize(args.dataset, data_home=data_home)
if args.dataset in TEST_TRACKIDS.keys():
track_id = TEST_TRACKIDS[args.dataset]
else:
print("No test track found for {}. ".format(args... | (attr))
non_attributes = list(
itertools.chain.from_iterable([properties, cached_properties, functions])
)
for val in dir(class_instance):
if val.startswith("_"):
continue
if val not in non_attributes:
attributes.append(val)
return {
"attributes":... | 95 | 95 | 317 | 4 | 91 | ooyamatakehisa/mirdata | scripts/print_track_docstring.py | Python | main | main | 65 | 110 | 65 | 65 | 0bfb13256985a8572698560c22a3531cbde40e46 | bigcode/the-stack | train |
425077992604dd6fd7c4fa39 | train | function | def moveTo(x,y):
global curLowerStepsFromZero, curUpperStepsFromZero
global curElbowX, curElbowY
p1, p2 = circle_intersection((x0,y0,L1), (x,y,L2))
# print("MoveTo x,y ", x, y, " intersection points ", p1, p2)
# Check the y values of each point - if only one is > 0 then choose that one
targetE... | def moveTo(x,y):
| global curLowerStepsFromZero, curUpperStepsFromZero
global curElbowX, curElbowY
p1, p2 = circle_intersection((x0,y0,L1), (x,y,L2))
# print("MoveTo x,y ", x, y, " intersection points ", p1, p2)
# Check the y values of each point - if only one is > 0 then choose that one
targetElbowPt = p1
i... | per step
# Motor shaft pulley has 20 teeth
# Upper arm pulley has 62 teeth
lowerStepsPerDegree = 1/((1.8/16)*(20/62))
print("Lower steps per degree", lowerStepsPerDegree)
# Max ranges of arms from straight forwards
upperArmMaxAngle = 90
lowerArmMaxAngle = 160
# Origin and arm lengths
x0 = 0
y0 = 0
L1 = 100
L2 = 100
... | 256 | 256 | 1,146 | 6 | 249 | robdobsn/SingleArmScaraSoftware | TestPySingleScara/testmotors.py | Python | moveTo | moveTo | 105 | 203 | 105 | 105 | e49494ed0a32f91f5ca08e26e3b038ffc4ff4970 | bigcode/the-stack | train |
637357edc793b85daf95f6a6 | train | function | def stepUpper():
upperArmStep.value(1)
pyb.udelay(pulseWidthUsecs)
upperArmStep.value(0)
pyb.udelay(betweenPulsesUsecs)
| def stepUpper():
| upperArmStep.value(1)
pyb.udelay(pulseWidthUsecs)
upperArmStep.value(0)
pyb.udelay(betweenPulsesUsecs)
|
L1 = 100
L2 = 100
# Accumulated movement and elbow x,y 0position
curLowerStepsFromZero = 0
curUpperStepsFromZero = 0
curElbowX = 0
curElbowY = L1
def stepUpper():
| 64 | 64 | 44 | 4 | 59 | robdobsn/SingleArmScaraSoftware | TestPySingleScara/testmotors.py | Python | stepUpper | stepUpper | 92 | 96 | 92 | 92 | f79a9e103b3d11cb1d7d82d83ed7355c4bb04361 | bigcode/the-stack | train |
015272731943f4e4c57c2f2c | train | function | def circle_intersection(circle1, circle2):
'''
@summary: calculates intersection points of two circles
@param circle1: tuple(x,y,radius)
@param circle2: tuple(x,y,radius)
@result: tuple of intersection points (which are (x,y) tuple)
'''
# return self.circle_intersection_sympy(circle1,circle2... | def circle_intersection(circle1, circle2):
| '''
@summary: calculates intersection points of two circles
@param circle1: tuple(x,y,radius)
@param circle2: tuple(x,y,radius)
@result: tuple of intersection points (which are (x,y) tuple)
'''
# return self.circle_intersection_sympy(circle1,circle2)
x1,y1,r1 = circle1
x2,y2,r2 = cir... | .MPR121(pyb.I2C(1, pyb.I2C.MASTER))
keybd.debounce(3,3)
for electr in range(4):
keybd.threshold(electr, 50, 30)
# LCD
lcd = pyb.LCD('X')
lcd.light(True)
# Maths required for calculations
from math import cos, sin, pi, sqrt, atan2, asin, acos
d2r = pi/180
def circle_intersection(circle1, circle2):
| 107 | 107 | 357 | 10 | 96 | robdobsn/SingleArmScaraSoftware | TestPySingleScara/testmotors.py | Python | circle_intersection | circle_intersection | 18 | 50 | 18 | 18 | bae82cf5083a574b204f5217b4c0b2db8503f6f6 | bigcode/the-stack | train |
74559d7599aef83e4e8a3da0 | train | function | def stepLower():
lowerArmStep.value(1)
pyb.udelay(pulseWidthUsecs)
lowerArmStep.value(0)
pyb.udelay(betweenPulsesUsecs)
| def stepLower():
| lowerArmStep.value(1)
pyb.udelay(pulseWidthUsecs)
lowerArmStep.value(0)
pyb.udelay(betweenPulsesUsecs)
| curElbowX = 0
curElbowY = L1
def stepUpper():
upperArmStep.value(1)
pyb.udelay(pulseWidthUsecs)
upperArmStep.value(0)
pyb.udelay(betweenPulsesUsecs)
def stepLower():
| 64 | 64 | 44 | 4 | 60 | robdobsn/SingleArmScaraSoftware | TestPySingleScara/testmotors.py | Python | stepLower | stepLower | 98 | 102 | 98 | 98 | df10360035645926d14bce250774d43d3396dda3 | bigcode/the-stack | train |
e6f0a2072ccd9f2f72257742 | train | function | @click.command()
@click.option(
'-l', '--language', type=click.STRING, default='de',
help='choose vocabular language (default is "de")'
)
def stemm(language):
start = watch.time()
doc = click.get_text_stream('stdin', 'utf-8').readlines()
log_info(f'stemming')
for i, line in enumerate(stemm_doc... | @click.command()
@click.option(
'-l', '--language', type=click.STRING, default='de',
help='choose vocabular language (default is "de")'
)
def stemm(language):
| start = watch.time()
doc = click.get_text_stream('stdin', 'utf-8').readlines()
log_info(f'stemming')
for i, line in enumerate(stemm_doc_stream(doc, language)):
click.get_text_stream('stdout', 'utf-8').write(f'{line}\n')
log_info(f'stemmed {i+1} lines')
log_info(f'stemming completed in... | _info import log_info
from bda_core.use_cases.nlp.stemm_doc import stemm_doc_stream
@click.command()
@click.option(
'-l', '--language', type=click.STRING, default='de',
help='choose vocabular language (default is "de")'
)
def stemm(language):
| 64 | 64 | 141 | 42 | 21 | bda-19fs/bda-chatbot | app/stemm.py | Python | stemm | stemm | 8 | 23 | 8 | 13 | 47404f50227c0eaac5971a5d9ae6c02b051d1d42 | bigcode/the-stack | train |
41729f5f0d1bedc6104ed02b | train | function | def fcn_8_resnet50(n_classes, input_height=416, input_width=608, channels=3):
model = fcn_8(n_classes, get_resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_resnet50"
return model
| def fcn_8_resnet50(n_classes, input_height=416, input_width=608, channels=3):
| model = fcn_8(n_classes, get_resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_resnet50"
return model
| , get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_vgg"
return model
def fcn_8_resnet50(n_classes, input_height=416, input_width=608, channels=3):
| 64 | 64 | 75 | 26 | 37 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_8_resnet50 | fcn_8_resnet50 | 136 | 140 | 136 | 136 | 272ce75735ecdc72bd61275139617c8d08a027d2 | bigcode/the-stack | train |
7f31f59e7fa58b1904493810 | train | function | def fcn_8_vgg(n_classes, input_height=416, input_width=608, channels=3):
model = fcn_8(n_classes, get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_vgg"
return model
| def fcn_8_vgg(n_classes, input_height=416, input_width=608, channels=3):
| model = fcn_8(n_classes, get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_vgg"
return model
| =False, data_format=IMAGE_ORDERING)(o)
model = get_segmentation_model(img_input, o)
model.model_name = "fcn_32"
return model
def fcn_8_vgg(n_classes, input_height=416, input_width=608, channels=3):
| 64 | 64 | 72 | 25 | 38 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_8_vgg | fcn_8_vgg | 122 | 126 | 122 | 122 | 9918661b786c7dc5feb68346973d34d487ca9a54 | bigcode/the-stack | train |
833ebe13b45c1cbf1061b5f7 | train | function | def fcn_32_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
model = fcn_32(n_classes, get_mobilenet_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_mobilenet"
return model
| def fcn_32_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
| model = fcn_32(n_classes, get_mobilenet_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_mobilenet"
return model
| _mobilenet_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_mobilenet"
return model
def fcn_32_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
| 64 | 64 | 75 | 26 | 37 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_32_mobilenet | fcn_32_mobilenet | 157 | 161 | 157 | 157 | fba07e59a49f41de59445f1a8f84f74e10af71d7 | bigcode/the-stack | train |
8480053c0bb41b841b5a6ded | train | function | def fcn_8_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
model = fcn_8(n_classes, get_mobilenet_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_mobilenet"
return model
| def fcn_8_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
| model = fcn_8(n_classes, get_mobilenet_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_mobilenet"
return model
| _resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_resnet50"
return model
def fcn_8_mobilenet(n_classes, input_height=224, input_width=224, channels=3):
| 64 | 64 | 75 | 26 | 37 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_8_mobilenet | fcn_8_mobilenet | 150 | 154 | 150 | 150 | 6f606b1434243da09d0d5952c8e96b0e142c8341 | bigcode/the-stack | train |
a071ef70e4ecc06198a39a51 | train | function | def fcn_32_resnet50(n_classes, input_height=416, input_width=608, channels=3):
model = fcn_32(n_classes, get_resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_resnet50"
return model
| def fcn_32_resnet50(n_classes, input_height=416, input_width=608, channels=3):
| model = fcn_32(n_classes, get_resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_resnet50"
return model
| _resnet50_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_resnet50"
return model
def fcn_32_resnet50(n_classes, input_height=416, input_width=608, channels=3):
| 64 | 64 | 75 | 26 | 37 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_32_resnet50 | fcn_32_resnet50 | 143 | 147 | 143 | 143 | 93508982826cc9368052368f02d9c7ddcf03444b | bigcode/the-stack | train |
c3901e166b410b95855d53ac | train | function | def fcn_8(n_classes, encoder=vanilla_encoder, input_height=416,
input_width=608, channels=3):
img_input, levels = encoder(
input_height=input_height, input_width=input_width, channels=channels)
[f1, f2, f3, f4, f5] = levels
o = f5
o = (Conv2D(4096, (7, 7), activation='relu',
... | def fcn_8(n_classes, encoder=vanilla_encoder, input_height=416,
input_width=608, channels=3):
| img_input, levels = encoder(
input_height=input_height, input_width=input_width, channels=channels)
[f1, f2, f3, f4, f5] = levels
o = f5
o = (Conv2D(4096, (7, 7), activation='relu',
padding='same', data_format=IMAGE_ORDERING))(o)
o = Dropout(0.5)(o)
o = (Conv2D(4096, (... | 2 = Cropping2D(cropping=((0, 0), (0, cx)),
data_format=IMAGE_ORDERING)(o2)
if output_height1 > output_height2:
o1 = Cropping2D(cropping=((0, cy), (0, 0)),
data_format=IMAGE_ORDERING)(o1)
else:
o2 = Cropping2D(cropping=((0, cy), (0, 0)),
... | 150 | 150 | 501 | 29 | 120 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_8 | fcn_8 | 51 | 93 | 51 | 53 | 2450a4baf84982b17122a7916aadd1651d4a8887 | bigcode/the-stack | train |
01c7dcb9490242b82f62770e | train | function | def crop(o1, o2, i):
o_shape2 = Model(i, o2).output_shape
if IMAGE_ORDERING == 'channels_first':
output_height2 = o_shape2[2]
output_width2 = o_shape2[3]
else:
output_height2 = o_shape2[1]
output_width2 = o_shape2[2]
o_shape1 = Model(i, o1).output_shape
if IMAGE_ORD... | def crop(o1, o2, i):
| o_shape2 = Model(i, o2).output_shape
if IMAGE_ORDERING == 'channels_first':
output_height2 = o_shape2[2]
output_width2 = o_shape2[3]
else:
output_height2 = o_shape2[1]
output_width2 = o_shape2[2]
o_shape1 = Model(i, o1).output_shape
if IMAGE_ORDERING == 'channels_fi... | from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from .config import IMAGE_ORDERING
from .model_utils import get_segmentation_model
from .vgg16 import get_vgg_encoder
from .mobilenet import get_mobilenet_encoder
from .basic_models import vanilla_encoder
from .resnet50 import get_resnet50_enc... | 91 | 103 | 346 | 10 | 80 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | crop | crop | 13 | 48 | 13 | 13 | bc819731f6175f62cb0aa4f5257cc10569c885b6 | bigcode/the-stack | train |
9e6c2317902f9a538e03f891 | train | function | def fcn_32_vgg(n_classes, input_height=416, input_width=608, channels=3):
model = fcn_32(n_classes, get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_vgg"
return model
| def fcn_32_vgg(n_classes, input_height=416, input_width=608, channels=3):
| model = fcn_32(n_classes, get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_32_vgg"
return model
| _classes, get_vgg_encoder,
input_height=input_height, input_width=input_width, channels=channels)
model.model_name = "fcn_8_vgg"
return model
def fcn_32_vgg(n_classes, input_height=416, input_width=608, channels=3):
| 64 | 64 | 72 | 25 | 38 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_32_vgg | fcn_32_vgg | 129 | 133 | 129 | 129 | 5195535b4505cc32567d2a37c69f1074eb2d41bb | bigcode/the-stack | train |
396f8baa0be55488dd1bf443 | train | function | def fcn_32(n_classes, encoder=vanilla_encoder, input_height=416,
input_width=608, channels=3):
img_input, levels = encoder(
input_height=input_height, input_width=input_width, channels=channels)
[f1, f2, f3, f4, f5] = levels
o = f5
o = (Conv2D(4096, (7, 7), activation='relu',
... | def fcn_32(n_classes, encoder=vanilla_encoder, input_height=416,
input_width=608, channels=3):
| img_input, levels = encoder(
input_height=input_height, input_width=input_width, channels=channels)
[f1, f2, f3, f4, f5] = levels
o = f5
o = (Conv2D(4096, (7, 7), activation='relu',
padding='same', data_format=IMAGE_ORDERING))(o)
o = Dropout(0.5)(o)
o = (Conv2D(4096, (... | , 16), strides=(
8, 8), use_bias=False, data_format=IMAGE_ORDERING)(o)
model = get_segmentation_model(img_input, o)
model.model_name = "fcn_8"
return model
def fcn_32(n_classes, encoder=vanilla_encoder, input_height=416,
input_width=608, channels=3):
| 84 | 84 | 283 | 29 | 54 | georgiosouzounis/semantic-segmentation-tf2 | tf2_sem_seg/models/fcn.py | Python | fcn_32 | fcn_32 | 96 | 119 | 96 | 98 | 2cf779aa0cff5c366e255c8919b3aa8a06f4f13e | bigcode/the-stack | train |
7ee4cbe64ff651829e7eb9fa | train | function | def Geekbenchmulticore(CPU):
return f'```The {CPU} scores on average {multicoreGB5.get(CPU)} points in Geekbench 5 multicore```'
| def Geekbenchmulticore(CPU):
| return f'```The {CPU} scores on average {multicoreGB5.get(CPU)} points in Geekbench 5 multicore```'
| *CPU1* *CPU2* = compares two CPUs in multi core Geekbench 5\n" \
"|bpecs = Specs of the system the bot is running on\n" \
"|botinfo = pretty self explanatory" \
"```"
def Geekbenchmulticore(CPU):
| 63 | 64 | 41 | 9 | 54 | monabuntur/BenchBot | BenchBot.py | Python | Geekbenchmulticore | Geekbenchmulticore | 74 | 75 | 74 | 74 | 2f3e5f66a1a472022f0de62065c0bbf7d9d09118 | bigcode/the-stack | train |
66d0a6c7b2119b0c22507d34 | train | function | def BotInfo():
return "```BenchBot 1.2, developed by Monabuntur, April 2021\n" \
"Github: https://github.com/monabuntur/BenchBot```"
| def BotInfo():
| return "```BenchBot 1.2, developed by Monabuntur, April 2021\n" \
"Github: https://github.com/monabuntur/BenchBot```"
|
from gb5scraper import singlecoreGB5
import gb5scraper
import platform
import subprocess
# Opens the file containing the token and reads the first line
TOKEN = open("TOKEN.txt", "r").readline()
client = discord.Client()
OS = platform.system()
def BotInfo():
| 64 | 64 | 45 | 4 | 60 | monabuntur/BenchBot | BenchBot.py | Python | BotInfo | BotInfo | 17 | 19 | 17 | 17 | aef78e417333f65d99ddadda69136b617a04e63d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.