body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
d136c8177a772f0738fdd383246db46419efedc01f764a59b07413aa6eb236ab | def create_electricity_market_for_fuel_prep(self):
' This function fills the electricity market that supplies battery charging operations\n and hydrogen production through electrolysis.\n '
try:
losses_to_low = float(self.bs.losses[self.country]['LV'])
except KeyError:
losses_t... | This function fills the electricity market that supplies battery charging operations
and hydrogen production through electrolysis. | carculator/inventory.py | create_electricity_market_for_fuel_prep | rena-nong/carculator | 1 | python | def create_electricity_market_for_fuel_prep(self):
' This function fills the electricity market that supplies battery charging operations\n and hydrogen production through electrolysis.\n '
try:
losses_to_low = float(self.bs.losses[self.country]['LV'])
except KeyError:
losses_t... | def create_electricity_market_for_fuel_prep(self):
' This function fills the electricity market that supplies battery charging operations\n and hydrogen production through electrolysis.\n '
try:
losses_to_low = float(self.bs.losses[self.country]['LV'])
except KeyError:
losses_t... |
b6849d08b40dcab8a054435f4fb0d84689024d0cf3ab5c2840cb2c7d027236af | def create_electricity_market_for_battery_production(self):
'\n This function fills in the column in `self.A` concerned with the electricity mix used for manufacturing battery cells\n :return:\n '
battery_origin = self.background_configuration['energy storage']['electric']['origin']
if ... | This function fills in the column in `self.A` concerned with the electricity mix used for manufacturing battery cells
:return: | carculator/inventory.py | create_electricity_market_for_battery_production | rena-nong/carculator | 1 | python | def create_electricity_market_for_battery_production(self):
'\n This function fills in the column in `self.A` concerned with the electricity mix used for manufacturing battery cells\n :return:\n '
battery_origin = self.background_configuration['energy storage']['electric']['origin']
if ... | def create_electricity_market_for_battery_production(self):
'\n This function fills in the column in `self.A` concerned with the electricity mix used for manufacturing battery cells\n :return:\n '
battery_origin = self.background_configuration['energy storage']['electric']['origin']
if ... |
45287ae3111093efbd0c7588e18c83555e8797190ab8f02124ed31f5cbbafe96 | def set_actual_range(self):
'\n Set the actual range considering the blend.\n Liquid bio-fuels and synthetic fuels typically have a lower calorific value. Hence, the need to recalculate\n the vehicle range.\n Modifies parameter `range` of `array` in place\n '
if {'ICEV-p', 'HE... | Set the actual range considering the blend.
Liquid bio-fuels and synthetic fuels typically have a lower calorific value. Hence, the need to recalculate
the vehicle range.
Modifies parameter `range` of `array` in place | carculator/inventory.py | set_actual_range | rena-nong/carculator | 1 | python | def set_actual_range(self):
'\n Set the actual range considering the blend.\n Liquid bio-fuels and synthetic fuels typically have a lower calorific value. Hence, the need to recalculate\n the vehicle range.\n Modifies parameter `range` of `array` in place\n '
if {'ICEV-p', 'HE... | def set_actual_range(self):
'\n Set the actual range considering the blend.\n Liquid bio-fuels and synthetic fuels typically have a lower calorific value. Hence, the need to recalculate\n the vehicle range.\n Modifies parameter `range` of `array` in place\n '
if {'ICEV-p', 'HE... |
094ba0d4eb48c25ba263488a2529367143767c5f3d59d9ee81469176152861b6 | def define_fuel_blends(self):
'\n This function defines fuel blends from what is passed in `background_configuration`.\n It populates a dictionary `self.fuel_blends` that contains the respective shares, lower heating values\n and CO2 emission factors of the fuels used.\n :return:\n ... | This function defines fuel blends from what is passed in `background_configuration`.
It populates a dictionary `self.fuel_blends` that contains the respective shares, lower heating values
and CO2 emission factors of the fuels used.
:return: | carculator/inventory.py | define_fuel_blends | rena-nong/carculator | 1 | python | def define_fuel_blends(self):
'\n This function defines fuel blends from what is passed in `background_configuration`.\n It populates a dictionary `self.fuel_blends` that contains the respective shares, lower heating values\n and CO2 emission factors of the fuels used.\n :return:\n ... | def define_fuel_blends(self):
'\n This function defines fuel blends from what is passed in `background_configuration`.\n It populates a dictionary `self.fuel_blends` that contains the respective shares, lower heating values\n and CO2 emission factors of the fuels used.\n :return:\n ... |
2c8771d34dc4927441b17fb8852d27243cb4bf632e8a312e8e8b5fc1d6c06b19 | def get_sulfur_content(self, location, fuel, year):
'\n Return the sulfur content in the fuel.\n If a region is passed, the average sulfur content over\n the countries the region contains is returned.\n :param location: str. A country or region ISO code\n :param fuel: str. "diesel... | Return the sulfur content in the fuel.
If a region is passed, the average sulfur content over
the countries the region contains is returned.
:param location: str. A country or region ISO code
:param fuel: str. "diesel" or "gasoline
:return: float. Sulfur content in ppm. | carculator/inventory.py | get_sulfur_content | rena-nong/carculator | 1 | python | def get_sulfur_content(self, location, fuel, year):
'\n Return the sulfur content in the fuel.\n If a region is passed, the average sulfur content over\n the countries the region contains is returned.\n :param location: str. A country or region ISO code\n :param fuel: str. "diesel... | def get_sulfur_content(self, location, fuel, year):
'\n Return the sulfur content in the fuel.\n If a region is passed, the average sulfur content over\n the countries the region contains is returned.\n :param location: str. A country or region ISO code\n :param fuel: str. "diesel... |
b73f03d444dbd53f10cc9c9439e3304b5f12637e37010b4b06f3f7058d98306a | def create_fuel_markets(self, fuel_type, primary=None, secondary=None, tertiary=None, primary_share=None, secondary_share=None, tertiary_share=None):
'\n This function creates markets for fuel, considering a given blend, a given fuel type and a given year.\n It also adds separate electricity input in ... | This function creates markets for fuel, considering a given blend, a given fuel type and a given year.
It also adds separate electricity input in case hydrogen from electrolysis is needed somewhere in the fuel supply chain.
:return: | carculator/inventory.py | create_fuel_markets | rena-nong/carculator | 1 | python | def create_fuel_markets(self, fuel_type, primary=None, secondary=None, tertiary=None, primary_share=None, secondary_share=None, tertiary_share=None):
'\n This function creates markets for fuel, considering a given blend, a given fuel type and a given year.\n It also adds separate electricity input in ... | def create_fuel_markets(self, fuel_type, primary=None, secondary=None, tertiary=None, primary_share=None, secondary_share=None, tertiary_share=None):
'\n This function creates markets for fuel, considering a given blend, a given fuel type and a given year.\n It also adds separate electricity input in ... |
224d07899ad25842055dea3c2a5527ceebe1b2c96cb1e8c0194501185c7faef4 | def find_inputs(self, value_in, value_out, find_input_by='name', zero_out_input=False):
"\n Finds the exchange inputs to a specified functional unit\n :param find_input_by: can be 'name' or 'unit'\n :param value_in: value to look for\n :param value_out: functional unit output\n :r... | Finds the exchange inputs to a specified functional unit
:param find_input_by: can be 'name' or 'unit'
:param value_in: value to look for
:param value_out: functional unit output
:return: indices of all inputs to FU, indices of inputs of intereste
:rtype: tuple | carculator/inventory.py | find_inputs | rena-nong/carculator | 1 | python | def find_inputs(self, value_in, value_out, find_input_by='name', zero_out_input=False):
"\n Finds the exchange inputs to a specified functional unit\n :param find_input_by: can be 'name' or 'unit'\n :param value_in: value to look for\n :param value_out: functional unit output\n :r... | def find_inputs(self, value_in, value_out, find_input_by='name', zero_out_input=False):
"\n Finds the exchange inputs to a specified functional unit\n :param find_input_by: can be 'name' or 'unit'\n :param value_in: value to look for\n :param value_out: functional unit output\n :r... |
674b4f06b11eb8d6584f7e1737b306f73d8891ff7a3b0df3e68ed304cc4f4ee8 | def set_inputs_in_A_matrix(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glider, passeng... | Fill-in the A matrix. Does not return anything. Modifies in place.
Shape of the A matrix (values, products, activities).
:param array: :attr:`array` from :class:`CarModel` class | carculator/inventory.py | set_inputs_in_A_matrix | rena-nong/carculator | 1 | python | def set_inputs_in_A_matrix(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glider, passeng... | def set_inputs_in_A_matrix(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glider, passeng... |
e97394747f44ae23d8c972fd38bddbef5a3d095dbd4489dd40fc5f2b7228f77c | def set_inputs_in_A_matrix_for_export(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glid... | Fill-in the A matrix. Does not return anything. Modifies in place.
Shape of the A matrix (values, products, activities).
:param array: :attr:`array` from :class:`CarModel` class | carculator/inventory.py | set_inputs_in_A_matrix_for_export | rena-nong/carculator | 1 | python | def set_inputs_in_A_matrix_for_export(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glid... | def set_inputs_in_A_matrix_for_export(self, array):
'\n Fill-in the A matrix. Does not return anything. Modifies in place.\n Shape of the A matrix (values, products, activities).\n\n :param array: :attr:`array` from :class:`CarModel` class\n '
self.A[(:, self.inputs[('market for glid... |
a053c18baafbfed19c3ae99bd992a190ac036c6dd469b74980610011c984b628 | def select_heat_supplier(self, heat_supplier):
'\n The heat supply is an important aspect of direct air capture.\n Here, we can change the supplier of heat.\n :param heat_supplier: by default "waste heat". Must be one of "waste heat", "biomass heat",\n "natural gas heat", "market heat".\... | The heat supply is an important aspect of direct air capture.
Here, we can change the supplier of heat.
:param heat_supplier: by default "waste heat". Must be one of "waste heat", "biomass heat",
"natural gas heat", "market heat".
:type heat_supplier: str
:return: | carculator/inventory.py | select_heat_supplier | rena-nong/carculator | 1 | python | def select_heat_supplier(self, heat_supplier):
'\n The heat supply is an important aspect of direct air capture.\n Here, we can change the supplier of heat.\n :param heat_supplier: by default "waste heat". Must be one of "waste heat", "biomass heat",\n "natural gas heat", "market heat".\... | def select_heat_supplier(self, heat_supplier):
'\n The heat supply is an important aspect of direct air capture.\n Here, we can change the supplier of heat.\n :param heat_supplier: by default "waste heat". Must be one of "waste heat", "biomass heat",\n "natural gas heat", "market heat".\... |
4723af1b0692eca50429a0b5922435a55f4c5efd85e46919f1730b3793beef8d | def report(filename, limit, lemmas, dbname=db, documents=None, most=True, display_format='html'):
'generate report and save to file\n '
if lemmas:
print('lemmas')
direction = ''
if most:
direction = 'DESC'
if (not lemmas):
sql = 'SELECT s.sentence, d.document, w.word\n ... | generate report and save to file | report.py | report | ImKogan/nlp | 0 | python | def report(filename, limit, lemmas, dbname=db, documents=None, most=True, display_format='html'):
'\n '
if lemmas:
print('lemmas')
direction =
if most:
direction = 'DESC'
if (not lemmas):
sql = 'SELECT s.sentence, d.document, w.word\n FROM lemma_word_sentence lws\n... | def report(filename, limit, lemmas, dbname=db, documents=None, most=True, display_format='html'):
'\n '
if lemmas:
print('lemmas')
direction =
if most:
direction = 'DESC'
if (not lemmas):
sql = 'SELECT s.sentence, d.document, w.word\n FROM lemma_word_sentence lws\n... |
37607367ab1efa0d102b7248213bbb670ac7ac6cf672141f195caa19ba038d52 | def __init__(self, img_size=(480, 892), render_type='naive'):
'\n img_size: List or Tuple with two elemets: h, w\n '
assert (render_type in self._render_types), 'render_type:{} is not supported!'.format(render_type)
self.render_type = render_type
self.img_size = img_size
(self.ylim, se... | img_size: List or Tuple with two elemets: h, w | plugin/packnet/pipelines.py | __init__ | a1600012888/mmdetection3d | 0 | python | def __init__(self, img_size=(480, 892), render_type='naive'):
'\n \n '
assert (render_type in self._render_types), 'render_type:{} is not supported!'.format(render_type)
self.render_type = render_type
self.img_size = img_size
(self.ylim, self.xlim) = img_size | def __init__(self, img_size=(480, 892), render_type='naive'):
'\n \n '
assert (render_type in self._render_types), 'render_type:{} is not supported!'.format(render_type)
self.render_type = render_type
self.img_size = img_size
(self.ylim, self.xlim) = img_size<|docstring|>img_size: List... |
727d71ad7c24d9f875d78690b9ec5ba4155f2095a33a9a5a4044848f10b51d34 | def sort_points(self, points):
'\n sort the points accroding to their depth in descending order\n '
depth = points[(:, 2)]
idx = np.argsort(depth)
idx = idx[::(- 1)]
new_points = points[idx]
return new_points | sort the points accroding to their depth in descending order | plugin/packnet/pipelines.py | sort_points | a1600012888/mmdetection3d | 0 | python | def sort_points(self, points):
'\n \n '
depth = points[(:, 2)]
idx = np.argsort(depth)
idx = idx[::(- 1)]
new_points = points[idx]
return new_points | def sort_points(self, points):
'\n \n '
depth = points[(:, 2)]
idx = np.argsort(depth)
idx = idx[::(- 1)]
new_points = points[idx]
return new_points<|docstring|>sort the points accroding to their depth in descending order<|endoftext|> |
8256e2ed8339e8141d7e859dd3c8002bd431f8101baf15ffc9a429e5b5847aa3 | def naive_depth_render(self, points, depth_map):
'\n for float cord, use its int version\n '
points = self.sort_points(points)
x_cords = ((points[(:, 0)] * self.xlim) / 1600.0)
y_cords = ((points[(:, 1)] * self.ylim) / 900.0)
depth = points[(:, 2)]
depth = np.clip(depth, a_min=1e-0... | for float cord, use its int version | plugin/packnet/pipelines.py | naive_depth_render | a1600012888/mmdetection3d | 0 | python | def naive_depth_render(self, points, depth_map):
'\n \n '
points = self.sort_points(points)
x_cords = ((points[(:, 0)] * self.xlim) / 1600.0)
y_cords = ((points[(:, 1)] * self.ylim) / 900.0)
depth = points[(:, 2)]
depth = np.clip(depth, a_min=1e-05, a_max=99999)
x_cords = x_cor... | def naive_depth_render(self, points, depth_map):
'\n \n '
points = self.sort_points(points)
x_cords = ((points[(:, 0)] * self.xlim) / 1600.0)
y_cords = ((points[(:, 1)] * self.ylim) / 900.0)
depth = points[(:, 2)]
depth = np.clip(depth, a_min=1e-05, a_max=99999)
x_cords = x_cor... |
34087245f3dd50ca7ced4c489a9bc4e5da72764e300e57fa8a142bc0ba40dd64 | def split_path(path):
'Convert PATH to (parent-path, name), unless it is None.\n '
return (posixpath.split(path) if (path is not None) else None) | Convert PATH to (parent-path, name), unless it is None. | notes/move-tracking/path_pairs_to_eid_map.py | split_path | auycro/subversion | 3 | python | def split_path(path):
'\n '
return (posixpath.split(path) if (path is not None) else None) | def split_path(path):
'\n '
return (posixpath.split(path) if (path is not None) else None)<|docstring|>Convert PATH to (parent-path, name), unless it is None.<|endoftext|> |
95cc59cdd466bfdff9f938a9197c850e8fe4ba43fdbd051dc3d958e14b945199 | def add_eid_mapping_and_make_parents(mapping, side, eid, parent_path, name):
'Add a (parent_eid, name) entry for SIDE:EID, and for each of its parent\n paths that lacks an EID, up to a path that has an EID.\n Add this same mapping to the other side as well, but without caring\n whether the parent elemen... | Add a (parent_eid, name) entry for SIDE:EID, and for each of its parent
paths that lacks an EID, up to a path that has an EID.
Add this same mapping to the other side as well, but without caring
whether the parent element exists on the other side. ### Is this right? | notes/move-tracking/path_pairs_to_eid_map.py | add_eid_mapping_and_make_parents | auycro/subversion | 3 | python | def add_eid_mapping_and_make_parents(mapping, side, eid, parent_path, name):
'Add a (parent_eid, name) entry for SIDE:EID, and for each of its parent\n paths that lacks an EID, up to a path that has an EID.\n Add this same mapping to the other side as well, but without caring\n whether the parent elemen... | def add_eid_mapping_and_make_parents(mapping, side, eid, parent_path, name):
'Add a (parent_eid, name) entry for SIDE:EID, and for each of its parent\n paths that lacks an EID, up to a path that has an EID.\n Add this same mapping to the other side as well, but without caring\n whether the parent elemen... |
1e1f2e05456fe028c17405f25618818dbf4106f5ca03fe6aa6a3ec31bb5fef5e | def add_new(mapping, side, path):
'Add a new EID and (parent_eid, name) entry for PATH, and for each\n of its parents that lacks an EID.\n\n Add this same mapping to the other side as well, but without caring\n whether the parent element exists on the other side.\n ### Why is this right?\n '
... | Add a new EID and (parent_eid, name) entry for PATH, and for each
of its parents that lacks an EID.
Add this same mapping to the other side as well, but without caring
whether the parent element exists on the other side.
### Why is this right? | notes/move-tracking/path_pairs_to_eid_map.py | add_new | auycro/subversion | 3 | python | def add_new(mapping, side, path):
'Add a new EID and (parent_eid, name) entry for PATH, and for each\n of its parents that lacks an EID.\n\n Add this same mapping to the other side as well, but without caring\n whether the parent element exists on the other side.\n ### Why is this right?\n '
... | def add_new(mapping, side, path):
'Add a new EID and (parent_eid, name) entry for PATH, and for each\n of its parents that lacks an EID.\n\n Add this same mapping to the other side as well, but without caring\n whether the parent element exists on the other side.\n ### Why is this right?\n '
... |
736e25364a49b61b68e857bb6ceb36adbd70f78493f7542dc38ebee6e7076355 | def write_parent_eid(mapping, side, eid):
'Write a (parent_eid, name) mapping corresponding to the existing\n (parent-path, name) mapping for SIDE:EID.\n\n For each of its parent paths in SIDE that lacks an EID, up to a path\n that has an EID, allocate an EID and write a (parent-eid, name) mapping\n ... | Write a (parent_eid, name) mapping corresponding to the existing
(parent-path, name) mapping for SIDE:EID.
For each of its parent paths in SIDE that lacks an EID, up to a path
that has an EID, allocate an EID and write a (parent-eid, name) mapping
in BOTH sides. | notes/move-tracking/path_pairs_to_eid_map.py | write_parent_eid | auycro/subversion | 3 | python | def write_parent_eid(mapping, side, eid):
'Write a (parent_eid, name) mapping corresponding to the existing\n (parent-path, name) mapping for SIDE:EID.\n\n For each of its parent paths in SIDE that lacks an EID, up to a path\n that has an EID, allocate an EID and write a (parent-eid, name) mapping\n ... | def write_parent_eid(mapping, side, eid):
'Write a (parent_eid, name) mapping corresponding to the existing\n (parent-path, name) mapping for SIDE:EID.\n\n For each of its parent paths in SIDE that lacks an EID, up to a path\n that has an EID, allocate an EID and write a (parent-eid, name) mapping\n ... |
3e0aca8c33fdda76cdf78872d971fa8346ce1110b645983a7d6cf53ba8b58045 | def __setitem__(self, k, v):
'Ensure no duplicate value already exists.'
assert (v not in self.values()), (k, v)
dict.__setitem__(self, k, v) | Ensure no duplicate value already exists. | notes/move-tracking/path_pairs_to_eid_map.py | __setitem__ | auycro/subversion | 3 | python | def __setitem__(self, k, v):
assert (v not in self.values()), (k, v)
dict.__setitem__(self, k, v) | def __setitem__(self, k, v):
assert (v not in self.values()), (k, v)
dict.__setitem__(self, k, v)<|docstring|>Ensure no duplicate value already exists.<|endoftext|> |
a6dd5b0f90f492064a454bffd23ce08c6623278e1b5eb89433942cdb59f5aaf2 | def eid_from_relpath(self, relpath):
'Return the EID for RELPATH, or -1 if the EID for RELPATH is not known.\n '
if (relpath == ''):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if (loc == (parent_path, name)):
return eid
retu... | Return the EID for RELPATH, or -1 if the EID for RELPATH is not known. | notes/move-tracking/path_pairs_to_eid_map.py | eid_from_relpath | auycro/subversion | 3 | python | def eid_from_relpath(self, relpath):
'\n '
if (relpath == ):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if (loc == (parent_path, name)):
return eid
return (- 1) | def eid_from_relpath(self, relpath):
'\n '
if (relpath == ):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if (loc == (parent_path, name)):
return eid
return (- 1)<|docstring|>Return the EID for RELPATH, or -1 if the EID for RE... |
ac1f0fdca15fe6064da66db171573136568a748492739f39fcc04af2a9a0f150 | def eid_from_relpath(self, relpath):
'Return the EID for RELPATH, or -1 if the EID for RELPATH is not known.\n '
if (relpath == ''):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if ((loc[1] == name) and (loc[0] == self.eid_from_relpath(parent... | Return the EID for RELPATH, or -1 if the EID for RELPATH is not known. | notes/move-tracking/path_pairs_to_eid_map.py | eid_from_relpath | auycro/subversion | 3 | python | def eid_from_relpath(self, relpath):
'\n '
if (relpath == ):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if ((loc[1] == name) and (loc[0] == self.eid_from_relpath(parent_path))):
return eid
return (- 1) | def eid_from_relpath(self, relpath):
'\n '
if (relpath == ):
return 0
(parent_path, name) = posixpath.split(relpath)
for (eid, loc) in self.items():
if ((loc[1] == name) and (loc[0] == self.eid_from_relpath(parent_path))):
return eid
return (- 1)<|docstring|>Return the... |
c61bf7aca96382692d66e5be0c29b86d7c8ef5a2bc42c5b6047a8187fb0ed7c8 | def eid_from_loc(self, loc):
'Return the EID for LOC, or -1 if the EID for LOC is not known.\n LOC is (parent_eid, name).\n '
if (loc is None):
return 0
for (eid, this_loc) in self.items():
if (loc == this_loc):
return eid
return (- 1) | Return the EID for LOC, or -1 if the EID for LOC is not known.
LOC is (parent_eid, name). | notes/move-tracking/path_pairs_to_eid_map.py | eid_from_loc | auycro/subversion | 3 | python | def eid_from_loc(self, loc):
'Return the EID for LOC, or -1 if the EID for LOC is not known.\n LOC is (parent_eid, name).\n '
if (loc is None):
return 0
for (eid, this_loc) in self.items():
if (loc == this_loc):
return eid
return (- 1) | def eid_from_loc(self, loc):
'Return the EID for LOC, or -1 if the EID for LOC is not known.\n LOC is (parent_eid, name).\n '
if (loc is None):
return 0
for (eid, this_loc) in self.items():
if (loc == this_loc):
return eid
return (- 1)<|docstring|>Return the EID for ... |
69d189e775945b3350c2870fde432a16afd09022352be5b95795893bc3f13786 | def relpath_from_eid(self, eid):
'Return the relpath of element EID in a mapping from EID to\n (parent_eid, name).\n '
if (eid == 0):
return ''
element = self.get(eid)
if (element is None):
return None
(parent_eid, name) = element
parent_path = self.relpath_from_eid(pare... | Return the relpath of element EID in a mapping from EID to
(parent_eid, name). | notes/move-tracking/path_pairs_to_eid_map.py | relpath_from_eid | auycro/subversion | 3 | python | def relpath_from_eid(self, eid):
'Return the relpath of element EID in a mapping from EID to\n (parent_eid, name).\n '
if (eid == 0):
return
element = self.get(eid)
if (element is None):
return None
(parent_eid, name) = element
parent_path = self.relpath_from_eid(parent... | def relpath_from_eid(self, eid):
'Return the relpath of element EID in a mapping from EID to\n (parent_eid, name).\n '
if (eid == 0):
return
element = self.get(eid)
if (element is None):
return None
(parent_eid, name) = element
parent_path = self.relpath_from_eid(parent... |
3b18bfa128a0cff212d1e31476613035476ce3a90993fef398ea88be64acd142 | def set_peid_loc(self, side, eid, loc):
'Set the mapping for SIDE:EID to LOC. (If no mapping for EID already\n exists, implicitly set the other side to None.)\n LOC is (parent-eid, name).\n '
assert (type(loc[0]) is int)
self.peid_maps[side][eid] = loc | Set the mapping for SIDE:EID to LOC. (If no mapping for EID already
exists, implicitly set the other side to None.)
LOC is (parent-eid, name). | notes/move-tracking/path_pairs_to_eid_map.py | set_peid_loc | auycro/subversion | 3 | python | def set_peid_loc(self, side, eid, loc):
'Set the mapping for SIDE:EID to LOC. (If no mapping for EID already\n exists, implicitly set the other side to None.)\n LOC is (parent-eid, name).\n '
assert (type(loc[0]) is int)
self.peid_maps[side][eid] = loc | def set_peid_loc(self, side, eid, loc):
'Set the mapping for SIDE:EID to LOC. (If no mapping for EID already\n exists, implicitly set the other side to None.)\n LOC is (parent-eid, name).\n '
assert (type(loc[0]) is int)
self.peid_maps[side][eid] = loc<|docstring|>Set the mapping for SIDE:EID... |
bde5193bd7d6aee0719fff1d8f63ce9385edbe143af942a94d9e48c8d1cf5650 | def find_eid_from_relpath(self, side, relpath):
'Return the EID for SIDE:RELPATH, or -1 if not found.\n '
eid = self.path_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
eid = self.peid_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
pass
return eid | Return the EID for SIDE:RELPATH, or -1 if not found. | notes/move-tracking/path_pairs_to_eid_map.py | find_eid_from_relpath | auycro/subversion | 3 | python | def find_eid_from_relpath(self, side, relpath):
'\n '
eid = self.path_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
eid = self.peid_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
pass
return eid | def find_eid_from_relpath(self, side, relpath):
'\n '
eid = self.path_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
eid = self.peid_locs_for_side(side).eid_from_relpath(relpath)
if (eid < 0):
pass
return eid<|docstring|>Return the EID for SIDE:RELPATH, or -1 if not f... |
45fffffb91f00357ba8272b6e9f58ca6a8447d9353e616a81750235617323920 | def test(did_pass):
' Print the result of a test. '
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = 'Test at line {0} ok.'.format(linenum)
else:
msg = 'Test at line {0} FAILED.'.format(linenum)
print(msg) | Print the result of a test. | Chapter7/Exercise15.py | test | NoahNacho/Python-project-tests | 2 | python | def test(did_pass):
' '
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = 'Test at line {0} ok.'.format(linenum)
else:
msg = 'Test at line {0} FAILED.'.format(linenum)
print(msg) | def test(did_pass):
' '
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = 'Test at line {0} ok.'.format(linenum)
else:
msg = 'Test at line {0} FAILED.'.format(linenum)
print(msg)<|docstring|>Print the result of a test.<|endoftext|> |
9ac4993dc114358527b3be52bcb3dd76b8d7881cc4d874218a6c58a1b45182a1 | def inst_variable(x, y, z):
'\n Instrumental variable method\n Args:\n x: the input matrix [T n]\n y: the output matrix [T]\n z: the instrument [T n]\n Returns:\n the estimation of theta in y = x theta + n by instrumental variable\n '
(T, n) = x.shape
A = np.zeros((n, n))... | Instrumental variable method
Args:
x: the input matrix [T n]
y: the output matrix [T]
z: the instrument [T n]
Returns:
the estimation of theta in y = x theta + n by instrumental variable | lq/funlib.py | inst_variable | FarnazAdib/Crash_course_on_RL | 53 | python | def inst_variable(x, y, z):
'\n Instrumental variable method\n Args:\n x: the input matrix [T n]\n y: the output matrix [T]\n z: the instrument [T n]\n Returns:\n the estimation of theta in y = x theta + n by instrumental variable\n '
(T, n) = x.shape
A = np.zeros((n, n))... | def inst_variable(x, y, z):
'\n Instrumental variable method\n Args:\n x: the input matrix [T n]\n y: the output matrix [T]\n z: the instrument [T n]\n Returns:\n the estimation of theta in y = x theta + n by instrumental variable\n '
(T, n) = x.shape
A = np.zeros((n, n))... |
608541fa0fe28bf70df4dba1abdf8b3256f2dccbba4e2850ba9dd58218a92d0e | def GtoP(G, K):
'\n :param G: The kernel of Q function\n :param K: The gain\n :return: The P associated with G and K\n '
(_, n) = K.shape
M = np.concatenate((np.eye(n), K.T), axis=1)
return ((M @ G) @ M.T) | :param G: The kernel of Q function
:param K: The gain
:return: The P associated with G and K | lq/funlib.py | GtoP | FarnazAdib/Crash_course_on_RL | 53 | python | def GtoP(G, K):
'\n :param G: The kernel of Q function\n :param K: The gain\n :return: The P associated with G and K\n '
(_, n) = K.shape
M = np.concatenate((np.eye(n), K.T), axis=1)
return ((M @ G) @ M.T) | def GtoP(G, K):
'\n :param G: The kernel of Q function\n :param K: The gain\n :return: The P associated with G and K\n '
(_, n) = K.shape
M = np.concatenate((np.eye(n), K.T), axis=1)
return ((M @ G) @ M.T)<|docstring|>:param G: The kernel of Q function
:param K: The gain
:return: The P assoc... |
ef797bdc7fdc7c5e4822702d0f060cfb56a22af3bbbfaf8613b8abe02b63a1a2 | def vecv(x):
'\n :param x: input vector of shape [T , n]\n :return: vector of x^2 of shape [T, n(n+1)/2]\n '
(T, n) = x.shape
N = int(((n * (n + 1)) / 2))
y = np.zeros((T, N))
for t in range(T):
yt = []
for i in range(n):
for j in range(i, n):
if ... | :param x: input vector of shape [T , n]
:return: vector of x^2 of shape [T, n(n+1)/2] | lq/funlib.py | vecv | FarnazAdib/Crash_course_on_RL | 53 | python | def vecv(x):
'\n :param x: input vector of shape [T , n]\n :return: vector of x^2 of shape [T, n(n+1)/2]\n '
(T, n) = x.shape
N = int(((n * (n + 1)) / 2))
y = np.zeros((T, N))
for t in range(T):
yt = []
for i in range(n):
for j in range(i, n):
if ... | def vecv(x):
'\n :param x: input vector of shape [T , n]\n :return: vector of x^2 of shape [T, n(n+1)/2]\n '
(T, n) = x.shape
N = int(((n * (n + 1)) / 2))
y = np.zeros((T, N))
for t in range(T):
yt = []
for i in range(n):
for j in range(i, n):
if ... |
6793f7973c3dcfe9f42ecf5af40ae722b86830bccc3431a635f698363202cc13 | def SquareMat(v, n):
'\n :param v: a vector\n :param n: dimension of the symmetric square matrix\n :return: a symmetric square matrix using v\n '
P = np.zeros((n, n))
s = 0
for i in range(n):
e = ((s + n) - i)
m = v[s:e].T
P[(i, i:)] = m
P[(i:, i)] = m
... | :param v: a vector
:param n: dimension of the symmetric square matrix
:return: a symmetric square matrix using v | lq/funlib.py | SquareMat | FarnazAdib/Crash_course_on_RL | 53 | python | def SquareMat(v, n):
'\n :param v: a vector\n :param n: dimension of the symmetric square matrix\n :return: a symmetric square matrix using v\n '
P = np.zeros((n, n))
s = 0
for i in range(n):
e = ((s + n) - i)
m = v[s:e].T
P[(i, i:)] = m
P[(i:, i)] = m
... | def SquareMat(v, n):
'\n :param v: a vector\n :param n: dimension of the symmetric square matrix\n :return: a symmetric square matrix using v\n '
P = np.zeros((n, n))
s = 0
for i in range(n):
e = ((s + n) - i)
m = v[s:e].T
P[(i, i:)] = m
P[(i:, i)] = m
... |
ac32a1bc33a5955c689e28c4edff143fd1f83864032c1f3a41552d20790da98a | def opt_onestep(self, g):
'\n This function calculate one iteration of adam optimization. It takes the gradient of cost functin with repect to\n parameter thetha and return dtheta. Note that you should use +dtheta when you are maximizing and -dtheta when\n minimizing.\n return the chang... | This function calculate one iteration of adam optimization. It takes the gradient of cost functin with repect to
parameter thetha and return dtheta. Note that you should use +dtheta when you are maximizing and -dtheta when
minimizing.
return the changes for the learning parameter
:param g: Assume as gradient of loss w... | lq/funlib.py | opt_onestep | FarnazAdib/Crash_course_on_RL | 53 | python | def opt_onestep(self, g):
'\n This function calculate one iteration of adam optimization. It takes the gradient of cost functin with repect to\n parameter thetha and return dtheta. Note that you should use +dtheta when you are maximizing and -dtheta when\n minimizing.\n return the chang... | def opt_onestep(self, g):
'\n This function calculate one iteration of adam optimization. It takes the gradient of cost functin with repect to\n parameter thetha and return dtheta. Note that you should use +dtheta when you are maximizing and -dtheta when\n minimizing.\n return the chang... |
db503034a0b394fdfbfd38f43bf369cf35ce71f460bf62ceb80f0e3ac4697f94 | @cached_property
def additional_properties_type():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n '
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type) | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded | intersight/model/boot_san.py | additional_properties_type | CiscoDevNet/intersight-python | 5 | python | @cached_property
def additional_properties_type():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n '
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type) | @cached_property
def additional_properties_type():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n '
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)<|docstring|>This must... |
ce20c930b8a8913807427169502712e588195e5348ae3255ce295d958c22ce8b | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ... | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. | intersight/model/boot_san.py | openapi_types | CiscoDevNet/intersight-python | 5 | python | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ... | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n ... |
42cff2cb9ec50dc66236bda3e41900c8499a159d4658edd482490f4b27d5d8cd | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'BootSan - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload ... | BootSan - a model defined in OpenAPI
Args:
Keyword Args:
class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "boot.San", must be one of ["boot.San", ] # noqa: ... | intersight/model/boot_san.py | __init__ | CiscoDevNet/intersight-python | 5 | python | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'BootSan - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload ... | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'BootSan - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload ... |
b34409f988bcc424201d148b010d9934c0f15caabbce3f9cfa440f2add9afbda | def iBEAt_test_DTI(Elastix_Parameter_file_PATH, output_dir, sorted_slice_files, ArrayDicomiBEAt, image_parameters, filenameDCM, lstFilesDCM):
' Example application of MDR in renal DTI (iBEAt data) \n\n Description\n -----------\n This function performs model driven registration for selected DTI sequence o... | Example application of MDR in renal DTI (iBEAt data)
Description
-----------
This function performs model driven registration for selected DTI sequence on a single selected slice
and returns as output the MDR registered images, signal model fit, deformation field x, deformation field y,
fitted parameters FA and AD... | tests/MDR_test_DTI.py | iBEAt_test_DTI | QIB-Sheffield/MDR-Library | 0 | python | def iBEAt_test_DTI(Elastix_Parameter_file_PATH, output_dir, sorted_slice_files, ArrayDicomiBEAt, image_parameters, filenameDCM, lstFilesDCM):
' Example application of MDR in renal DTI (iBEAt data) \n\n Description\n -----------\n This function performs model driven registration for selected DTI sequence o... | def iBEAt_test_DTI(Elastix_Parameter_file_PATH, output_dir, sorted_slice_files, ArrayDicomiBEAt, image_parameters, filenameDCM, lstFilesDCM):
' Example application of MDR in renal DTI (iBEAt data) \n\n Description\n -----------\n This function performs model driven registration for selected DTI sequence o... |
94f15fd820c1fceab101c975a603ce08351cbf64c13d90d88606b22fe67e075a | def read_dicom_tags_DTI(fname, lstFilesDCM):
' This function reads the DICOM header from the DTI sequence and returns the corresponding DTI tags.\n\n Args\n ----\n fname (pathlib.PosixPath): dicom filenames to process. \n lstFilesDCM (list): list of dicom files to process. \n\n Returns\n -------... | This function reads the DICOM header from the DTI sequence and returns the corresponding DTI tags.
Args
----
fname (pathlib.PosixPath): dicom filenames to process.
lstFilesDCM (list): list of dicom files to process.
Returns
-------
b-values (list): list of DTI b-values (s/mm2).
b_Vec_original (list): original ... | tests/MDR_test_DTI.py | read_dicom_tags_DTI | QIB-Sheffield/MDR-Library | 0 | python | def read_dicom_tags_DTI(fname, lstFilesDCM):
' This function reads the DICOM header from the DTI sequence and returns the corresponding DTI tags.\n\n Args\n ----\n fname (pathlib.PosixPath): dicom filenames to process. \n lstFilesDCM (list): list of dicom files to process. \n\n Returns\n -------... | def read_dicom_tags_DTI(fname, lstFilesDCM):
' This function reads the DICOM header from the DTI sequence and returns the corresponding DTI tags.\n\n Args\n ----\n fname (pathlib.PosixPath): dicom filenames to process. \n lstFilesDCM (list): list of dicom files to process. \n\n Returns\n -------... |
d0bdfc1c168c71660383d952cc65eede72ebe681cacdb06835260eecb34859cd | def detect_card(image_path: str, output_dir: str='output/', unwarp: bool=True, model_name: str='maskrcnn_resnet50', color: tuple=(0, 0, 0)):
'\n Arguments:\n image_path: path to the image to be processed\n output_dir: path to the results to be exported\n unwarp: unwarp detected id card to re... | Arguments:
image_path: path to the image to be processed
output_dir: path to the results to be exported
unwarp: unwarp detected id card to rectangle
model_name: model to be used in the inference
color: color to be used in the mask/bbox/quad visualizations | id_card_detector/__init__.py | detect_card | SaddamBInSyed/id-card-detector | 3 | python | def detect_card(image_path: str, output_dir: str='output/', unwarp: bool=True, model_name: str='maskrcnn_resnet50', color: tuple=(0, 0, 0)):
'\n Arguments:\n image_path: path to the image to be processed\n output_dir: path to the results to be exported\n unwarp: unwarp detected id card to re... | def detect_card(image_path: str, output_dir: str='output/', unwarp: bool=True, model_name: str='maskrcnn_resnet50', color: tuple=(0, 0, 0)):
'\n Arguments:\n image_path: path to the image to be processed\n output_dir: path to the results to be exported\n unwarp: unwarp detected id card to re... |
9d19a07b1ce1c3fe46cfd55be73b390e720553ee601dfe88a5d35c87c8d5c68b | def validate_columns(columns):
'\n Validates the columns based on their validity, returning a set\n :param columns: \n :return: a set of columns, constructed from the iterable passed in as the param\n '
columns = tuple(columns)
if (len(columns) == 0):
raise Exception('Pipeline must read ... | Validates the columns based on their validity, returning a set
:param columns:
:return: a set of columns, constructed from the iterable passed in as the param | tensorflow/contrib/persona/python/ops/io_pipe.py | validate_columns | epfl-dcsl/ptf-system | 0 | python | def validate_columns(columns):
'\n Validates the columns based on their validity, returning a set\n :param columns: \n :return: a set of columns, constructed from the iterable passed in as the param\n '
columns = tuple(columns)
if (len(columns) == 0):
raise Exception('Pipeline must read ... | def validate_columns(columns):
'\n Validates the columns based on their validity, returning a set\n :param columns: \n :return: a set of columns, constructed from the iterable passed in as the param\n '
columns = tuple(columns)
if (len(columns) == 0):
raise Exception('Pipeline must read ... |
a726ea82effec8d5a28b9c0f187a7fdb3cd27ee40dd6c178cc2b3a1039e00198 | def expand_column_extensions(key, columns):
'\n Expands a given AGD key into the full extensions, based on the columns\n :param keys: an iterator of scalar strings, representing the keys for a given parallelism level\n :param columns: assumed to have been validated previously be the caller\n :yield: a g... | Expands a given AGD key into the full extensions, based on the columns
:param keys: an iterator of scalar strings, representing the keys for a given parallelism level
:param columns: assumed to have been validated previously be the caller
:yield: a generator for keys | tensorflow/contrib/persona/python/ops/io_pipe.py | expand_column_extensions | epfl-dcsl/ptf-system | 0 | python | def expand_column_extensions(key, columns):
'\n Expands a given AGD key into the full extensions, based on the columns\n :param keys: an iterator of scalar strings, representing the keys for a given parallelism level\n :param columns: assumed to have been validated previously be the caller\n :yield: a g... | def expand_column_extensions(key, columns):
'\n Expands a given AGD key into the full extensions, based on the columns\n :param keys: an iterator of scalar strings, representing the keys for a given parallelism level\n :param columns: assumed to have been validated previously be the caller\n :yield: a g... |
e3a1bd5fdd1610b6fae0bdb0dcc335a80c430900a1ba9b7084fc48623545a851 | def ceph_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, delete_after_read=False, name='ceph_read_pipeline', log_directory=None, metadata=None):
'\n Create a ceph input pipeline.\n \n ... | Create a ceph input pipeline.
:param upstream_tensors: a tuple of tensors (key, namespace), which are typically found in the metadata file. This controls the parallelism
:param user_name:
:param cluster_name:
:param ceph_conf_path:
:param columns:
:param downstream_parallel: the level of parallelism to create for ... | tensorflow/contrib/persona/python/ops/io_pipe.py | ceph_read_pipeline | epfl-dcsl/ptf-system | 0 | python | def ceph_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, delete_after_read=False, name='ceph_read_pipeline', log_directory=None, metadata=None):
'\n Create a ceph input pipeline.\n \n ... | def ceph_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, delete_after_read=False, name='ceph_read_pipeline', log_directory=None, metadata=None):
'\n Create a ceph input pipeline.\n \n ... |
a671e0af1524b1a18aab1dfdcf0e0f8ae617acdb35623c471c65ef6ba2311caa | def ceph_lazy_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, records_per_segment, segments_to_buffer, delete_after_read=False, name='ceph_lazy_read_pipeline'):
'\n Create a lazy ceph input pipeline.\n\n :param upstream_tensors: a tuple of tensors (key, namespace),... | Create a lazy ceph input pipeline.
:param upstream_tensors: a tuple of tensors (key, namespace), which are typically found in the metadata file. This controls the parallelism
:param user_name:
:param cluster_name:
:param ceph_conf_path:
:param columns:
:param pool_name:
:param records_per_segment:
:param segments_to_b... | tensorflow/contrib/persona/python/ops/io_pipe.py | ceph_lazy_read_pipeline | epfl-dcsl/ptf-system | 0 | python | def ceph_lazy_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, records_per_segment, segments_to_buffer, delete_after_read=False, name='ceph_lazy_read_pipeline'):
'\n Create a lazy ceph input pipeline.\n\n :param upstream_tensors: a tuple of tensors (key, namespace),... | def ceph_lazy_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, columns, pool_name, records_per_segment, segments_to_buffer, delete_after_read=False, name='ceph_lazy_read_pipeline'):
'\n Create a lazy ceph input pipeline.\n\n :param upstream_tensors: a tuple of tensors (key, namespace),... |
7365d4dec8551457ffeb96a576bb1abbac22181eba852444484542000442dc88 | def ceph_combo_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, pool_name, columns, records_per_segment, segments_to_buffer, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, eager_column_types=(), delete_after_read=False, name='ceph_combo_read_pipeline'):
'\n ... | Create a lazy ceph input pipeline.
:param upstream_tensors: a tuple of tensors (key, namespace), which are typically found in the metadata file. This controls the parallelism
:param user_name:
:param cluster_name:
:param ceph_conf_path:
:param columns:
:param pool_name:
:param records_per_segment:
:param segments_to_b... | tensorflow/contrib/persona/python/ops/io_pipe.py | ceph_combo_read_pipeline | epfl-dcsl/ptf-system | 0 | python | def ceph_combo_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, pool_name, columns, records_per_segment, segments_to_buffer, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, eager_column_types=(), delete_after_read=False, name='ceph_combo_read_pipeline'):
'\n ... | def ceph_combo_read_pipeline(upstream_tensors, user_name, cluster_name, ceph_conf_path, pool_name, columns, records_per_segment, segments_to_buffer, ceph_read_size=(2 ** 26), buffer_pool=None, buffer_pool_args=pool_default_args, eager_column_types=(), delete_after_read=False, name='ceph_combo_read_pipeline'):
'\n ... |
623db8a3b8f01540218b569a3b0b5641a02f1e5516c025e8f3f21cc2bf7c267b | def aligner_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='aligner_compress_pipeline'):
'\n Compresses a list of upstream tensors of buffer list (via handles) into buffers\n :param upstream_tensors: \n :param name: \n :return: a stacked matrix of compress... | Compresses a list of upstream tensors of buffer list (via handles) into buffers
:param upstream_tensors:
:param name:
:return: a stacked matrix of compressed buffers | tensorflow/contrib/persona/python/ops/io_pipe.py | aligner_compress_pipeline | epfl-dcsl/ptf-system | 0 | python | def aligner_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='aligner_compress_pipeline'):
'\n Compresses a list of upstream tensors of buffer list (via handles) into buffers\n :param upstream_tensors: \n :param name: \n :return: a stacked matrix of compress... | def aligner_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='aligner_compress_pipeline'):
'\n Compresses a list of upstream tensors of buffer list (via handles) into buffers\n :param upstream_tensors: \n :param name: \n :return: a stacked matrix of compress... |
1d19b338993e8ce235a508c81668742bc1fe8254041b44fa7f1fec40f6fd3bb4 | def sorter_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='sorter_compress_pipeline'):
'\n :param upstream_tensors: a generator of stacked (i.e. matrix of (N,2) references to buffer pairs) to compress\n :param buffer_pool:\n :param buffer_pool_args:\n :par... | :param upstream_tensors: a generator of stacked (i.e. matrix of (N,2) references to buffer pairs) to compress
:param buffer_pool:
:param buffer_pool_args:
:param name:
:return: a generator of stacked references to buffers, in the same shape as upstream_tensors for each item | tensorflow/contrib/persona/python/ops/io_pipe.py | sorter_compress_pipeline | epfl-dcsl/ptf-system | 0 | python | def sorter_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='sorter_compress_pipeline'):
'\n :param upstream_tensors: a generator of stacked (i.e. matrix of (N,2) references to buffer pairs) to compress\n :param buffer_pool:\n :param buffer_pool_args:\n :par... | def sorter_compress_pipeline(upstream_tensors, buffer_pool=None, buffer_pool_args=pool_default_args, name='sorter_compress_pipeline'):
'\n :param upstream_tensors: a generator of stacked (i.e. matrix of (N,2) references to buffer pairs) to compress\n :param buffer_pool:\n :param buffer_pool_args:\n :par... |
56228b6abe7f4d2c0cc6d883afe1bcf45e20d8c5541e6269f322c5d598fae1d3 | def ceph_write_pipeline(upstream_tensors, user_name, cluster_name, pool_name, ceph_conf_path, compressed, record_types=default_records_type, name='ceph_write_pipeline', log_directory=None, metadata=None):
'\n :param upstream_tensors: a list of aligner output tensors of type (key, namespace, num_records, first or... | :param upstream_tensors: a list of aligner output tensors of type (key, namespace, num_records, first ordinal, record id, column handle)
:param user_name:
:param cluster_name:
:param ceph_conf_path:
:param name:
:return: yields the output of ceph write columns | tensorflow/contrib/persona/python/ops/io_pipe.py | ceph_write_pipeline | epfl-dcsl/ptf-system | 0 | python | def ceph_write_pipeline(upstream_tensors, user_name, cluster_name, pool_name, ceph_conf_path, compressed, record_types=default_records_type, name='ceph_write_pipeline', log_directory=None, metadata=None):
'\n :param upstream_tensors: a list of aligner output tensors of type (key, namespace, num_records, first or... | def ceph_write_pipeline(upstream_tensors, user_name, cluster_name, pool_name, ceph_conf_path, compressed, record_types=default_records_type, name='ceph_write_pipeline', log_directory=None, metadata=None):
'\n :param upstream_tensors: a list of aligner output tensors of type (key, namespace, num_records, first or... |
1f0c0d9a3abc077a7a3211656d9b40cc15b4427c35ffa713368de1e5f52089dc | def local_read_group_pipeline(upstream_tensors, sync=True, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_group_pipeline'):
"\n Takes a bunch of groups of files and makes synchronous filemmap groups from them\n :param upstream_tensors: a generator of either a vector tensor or a list of sca... | Takes a bunch of groups of files and makes synchronous filemmap groups from them
:param upstream_tensors: a generator of either a vector tensor or a list of scalar tensors of filenames to read. each of these constitutes a grop which will have control dependencies
:param sync: whether or not to synchronously map the fil... | tensorflow/contrib/persona/python/ops/io_pipe.py | local_read_group_pipeline | epfl-dcsl/ptf-system | 0 | python | def local_read_group_pipeline(upstream_tensors, sync=True, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_group_pipeline'):
"\n Takes a bunch of groups of files and makes synchronous filemmap groups from them\n :param upstream_tensors: a generator of either a vector tensor or a list of sca... | def local_read_group_pipeline(upstream_tensors, sync=True, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_group_pipeline'):
"\n Takes a bunch of groups of files and makes synchronous filemmap groups from them\n :param upstream_tensors: a generator of either a vector tensor or a list of sca... |
c50ce0101a519ec5bcdd4db978167501b29c6fef1f86f5a155ce597673fdb0fb | def local_read_pipeline(upstream_tensors, columns, sync=True, delete_after_use=False, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_pipeline'):
"\n Create a read pipeline to read from the filesystem\n :param upstream_tensors: a list of file keys, as extracted from the metadata file\n :... | Create a read pipeline to read from the filesystem
:param upstream_tensors: a list of file keys, as extracted from the metadata file
:param columns: a list of columns to extract. See `valid_columns` for the set of valid columns
:param sync: whether or not to synchronously map the files
:param mmap_pool: if not None, pr... | tensorflow/contrib/persona/python/ops/io_pipe.py | local_read_pipeline | epfl-dcsl/ptf-system | 0 | python | def local_read_pipeline(upstream_tensors, columns, sync=True, delete_after_use=False, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_pipeline'):
"\n Create a read pipeline to read from the filesystem\n :param upstream_tensors: a list of file keys, as extracted from the metadata file\n :... | def local_read_pipeline(upstream_tensors, columns, sync=True, delete_after_use=False, mmap_pool=None, mmap_pool_args=pool_default_args, name='local_read_pipeline'):
"\n Create a read pipeline to read from the filesystem\n :param upstream_tensors: a list of file keys, as extracted from the metadata file\n :... |
0b648d132718799c8ba8f92325e11271e11a5a4e01548765151dd63f23330548 | def local_write_pipeline(upstream_tensors, compressed, record_types=default_records_type, record_suffix='', name='local_write_pipeline'):
'\n Create a local write pipeline, based on the number of upstream tensors received.\n :param upstream_tensors: a list of tensor tuples of type: buffer_list_handle, record_... | Create a local write pipeline, based on the number of upstream tensors received.
:param upstream_tensors: a list of tensor tuples of type: buffer_list_handle, record_id, first_ordinal, num_records, file_path
:param record_type: the type of results to write. See persona_ops.cc for valid types
:param name:
:return: yiel... | tensorflow/contrib/persona/python/ops/io_pipe.py | local_write_pipeline | epfl-dcsl/ptf-system | 0 | python | def local_write_pipeline(upstream_tensors, compressed, record_types=default_records_type, record_suffix=, name='local_write_pipeline'):
'\n Create a local write pipeline, based on the number of upstream tensors received.\n :param upstream_tensors: a list of tensor tuples of type: buffer_list_handle, record_id... | def local_write_pipeline(upstream_tensors, compressed, record_types=default_records_type, record_suffix=, name='local_write_pipeline'):
'\n Create a local write pipeline, based on the number of upstream tensors received.\n :param upstream_tensors: a list of tensor tuples of type: buffer_list_handle, record_id... |
4887c7faf9b91bb3544bba63b557603843831aa810d280b645ba0546aa76a3d7 | def agd_reader_pipeline(upstream_tensors, verify=False, buffer_pool=None, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_pipeline'):
"\n Yield a pipeline of input buffers processed by AGDReader.\n \n This processes ONLY A SINGLE COLUMN. Use agd_reader_multi_column_pipeline to do multiple... | Yield a pipeline of input buffers processed by AGDReader.
This processes ONLY A SINGLE COLUMN. Use agd_reader_multi_column_pipeline to do multiple columns in parallel.
:param upstream_tensors: a tensor of handles to resources of type Data (in C++ persona code)
:param verify: if True, enable format verification by AGD... | tensorflow/contrib/persona/python/ops/io_pipe.py | agd_reader_pipeline | epfl-dcsl/ptf-system | 0 | python | def agd_reader_pipeline(upstream_tensors, verify=False, buffer_pool=None, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_pipeline'):
"\n Yield a pipeline of input buffers processed by AGDReader.\n \n This processes ONLY A SINGLE COLUMN. Use agd_reader_multi_column_pipeline to do multiple... | def agd_reader_pipeline(upstream_tensors, verify=False, buffer_pool=None, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_pipeline'):
"\n Yield a pipeline of input buffers processed by AGDReader.\n \n This processes ONLY A SINGLE COLUMN. Use agd_reader_multi_column_pipeline to do multiple... |
6c8c958991621cd774bf49d19d0f926b501baf6aeb629f484f83190bd733cd0c | def agd_reader_multi_column_pipeline(upstream_tensorz, control_ops=None, verify=False, buffer_pool=None, share_buffer_pool=True, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_multi_column_pipeline'):
"\n Create an AGDReader pipeline for an iterable of columns. Each column group is assumed to ... | Create an AGDReader pipeline for an iterable of columns. Each column group is assumed to have the same first ordinal, number of records, and record id.
:param upstream_tensorz: a list of list of tensors, each item being a column group
:param verify: whether or not to invoke the verification for AGD columns
:param buffe... | tensorflow/contrib/persona/python/ops/io_pipe.py | agd_reader_multi_column_pipeline | epfl-dcsl/ptf-system | 0 | python | def agd_reader_multi_column_pipeline(upstream_tensorz, control_ops=None, verify=False, buffer_pool=None, share_buffer_pool=True, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_multi_column_pipeline'):
"\n Create an AGDReader pipeline for an iterable of columns. Each column group is assumed to ... | def agd_reader_multi_column_pipeline(upstream_tensorz, control_ops=None, verify=False, buffer_pool=None, share_buffer_pool=True, buffer_pool_args=pool_default_args, repack=None, name='agd_reader_multi_column_pipeline'):
"\n Create an AGDReader pipeline for an iterable of columns. Each column group is assumed to ... |
44e98f53d9877db5475dce4510095fefe2a34fd67f18e03f8c04c4e28c23ee45 | def agd_bwa_read_assembler(upstream_tensors, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_bwa_read datatypes from the upstream tensors. BWA paired aligner requires specific data structures\n :param upstream_tensors: a list of tuples... | Generate agd_bwa_read datatypes from the upstream tensors. BWA paired aligner requires specific data structures
:param upstream_tensors: a list of tuples of tensors with type: (column_buffers, num_reads)
:param agd_read_pool: if not None, pass in an instance of persona_ops.agd_read_pool to share
:param agd_read_pool_ar... | tensorflow/contrib/persona/python/ops/io_pipe.py | agd_bwa_read_assembler | epfl-dcsl/ptf-system | 0 | python | def agd_bwa_read_assembler(upstream_tensors, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_bwa_read datatypes from the upstream tensors. BWA paired aligner requires specific data structures\n :param upstream_tensors: a list of tuples... | def agd_bwa_read_assembler(upstream_tensors, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_bwa_read datatypes from the upstream tensors. BWA paired aligner requires specific data structures\n :param upstream_tensors: a list of tuples... |
789f095a6f5719e39b10eb014465a9e011c02db01ef1cf4bad6119113760c39c | def agd_read_assembler(upstream_tensors, control_deps=None, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_read datatypes from the upstream tensors\n :param upstream_tensors: a list of tuples of tensors with type: (column_buffers, num... | Generate agd_read datatypes from the upstream tensors
:param upstream_tensors: a list of tuples of tensors with type: (column_buffers, num_reads)
:param agd_read_pool: if not None, pass in an instance of persona_ops.agd_read_pool to share
:param agd_read_pool_args: args for deafult construction of agd_read_pool if it's... | tensorflow/contrib/persona/python/ops/io_pipe.py | agd_read_assembler | epfl-dcsl/ptf-system | 0 | python | def agd_read_assembler(upstream_tensors, control_deps=None, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_read datatypes from the upstream tensors\n :param upstream_tensors: a list of tuples of tensors with type: (column_buffers, num... | def agd_read_assembler(upstream_tensors, control_deps=None, agd_read_pool=None, agd_read_pool_args=pool_default_args, include_meta=False, name='agd_read_assembler'):
"\n Generate agd_read datatypes from the upstream tensors\n :param upstream_tensors: a list of tuples of tensors with type: (column_buffers, num... |
d1e4746de554a42482775dc8f8af0c76f9d8cf10e4b06028ed958969187413da | @tf.function
def call(self, inputs):
'\n :param inputs: batched ids corresponding to text\n :return the probabilities as a tensor, [batch_size x num_classes]\n '
embedding = tf.nn.embedding_lookup(self.E, inputs)
embedding = self.pos_embed(embedding)
x = self.transformer(embedding)
... | :param inputs: batched ids corresponding to text
:return the probabilities as a tensor, [batch_size x num_classes] | transformer_model/code/transformer_model.py | call | nate-gillman/alzheimers-DL-final | 0 | python | @tf.function
def call(self, inputs):
'\n :param inputs: batched ids corresponding to text\n :return the probabilities as a tensor, [batch_size x num_classes]\n '
embedding = tf.nn.embedding_lookup(self.E, inputs)
embedding = self.pos_embed(embedding)
x = self.transformer(embedding)
... | @tf.function
def call(self, inputs):
'\n :param inputs: batched ids corresponding to text\n :return the probabilities as a tensor, [batch_size x num_classes]\n '
embedding = tf.nn.embedding_lookup(self.E, inputs)
embedding = self.pos_embed(embedding)
x = self.transformer(embedding)
... |
d943cb1ccda179e93309de0e0b5171ca0ad59285b1b10fdfb0e869dbf510a2ee | def accuracy(self, logits, labels):
"\n Calculates the model's prediction accuracy by comparing\n logits to correct labels – no need to modify this.\n \n :param logits: a matrix of size (num_inputs, self.num_classes); during training, this will be (batch_size, self.num_classes)\n ... | Calculates the model's prediction accuracy by comparing
logits to correct labels – no need to modify this.
:param logits: a matrix of size (num_inputs, self.num_classes); during training, this will be (batch_size, self.num_classes)
containing the result of multiple convolution and feed forward layers
:param labels: ma... | transformer_model/code/transformer_model.py | accuracy | nate-gillman/alzheimers-DL-final | 0 | python | def accuracy(self, logits, labels):
"\n Calculates the model's prediction accuracy by comparing\n logits to correct labels – no need to modify this.\n \n :param logits: a matrix of size (num_inputs, self.num_classes); during training, this will be (batch_size, self.num_classes)\n ... | def accuracy(self, logits, labels):
"\n Calculates the model's prediction accuracy by comparing\n logits to correct labels – no need to modify this.\n \n :param logits: a matrix of size (num_inputs, self.num_classes); during training, this will be (batch_size, self.num_classes)\n ... |
4ab77a2e02628b424fc2ad60f13d9fa55ddef53ce3309e426206ea23c0f8af54 | def loss_function(self, prbs, labels, mask):
'\n\t\tCalculates the model cross-entropy loss after one forward pass\n\t\tPlease use reduce sum here instead of reduce mean to make things easier in calculating per symbol accuracy.\n\n\t\t:param prbs: float tensor, word prediction probabilities [batch_size x window_si... | Calculates the model cross-entropy loss after one forward pass
Please use reduce sum here instead of reduce mean to make things easier in calculating per symbol accuracy.
:param prbs: float tensor, word prediction probabilities [batch_size x window_size x english_vocab_size]
:param labels: integer tensor, word predi... | transformer_model/code/transformer_model.py | loss_function | nate-gillman/alzheimers-DL-final | 0 | python | def loss_function(self, prbs, labels, mask):
'\n\t\tCalculates the model cross-entropy loss after one forward pass\n\t\tPlease use reduce sum here instead of reduce mean to make things easier in calculating per symbol accuracy.\n\n\t\t:param prbs: float tensor, word prediction probabilities [batch_size x window_si... | def loss_function(self, prbs, labels, mask):
'\n\t\tCalculates the model cross-entropy loss after one forward pass\n\t\tPlease use reduce sum here instead of reduce mean to make things easier in calculating per symbol accuracy.\n\n\t\t:param prbs: float tensor, word prediction probabilities [batch_size x window_si... |
c26d7ec7296685ef4962d4d5316996e82179196890578dfd579ba100d362381a | @staticmethod
def maxArea(height: List[int]) -> int:
'\n (以下段落摘抄自评论区)\n 其实我们显然可以发现影响问题的两个关键因素,一个是最短的短板,一个是宽度。\n 如果宽度变小,那么面积想比之前的更大,唯一的可能是最短的短板比之前要高。\n 所以更高的木板根本没必要移动,动它没有任何意义。如果想在更短的宽度得到更大的面积,唯一的可能是移动最短的短板,以期望其变高。短板原理啊,朋友们,是不是刷着刷着题突然就领悟到了人生的哲理。\n 所以大家不要老是想这道题该不该用双指针去解;看清这题的本质,自然而然... | (以下段落摘抄自评论区)
其实我们显然可以发现影响问题的两个关键因素,一个是最短的短板,一个是宽度。
如果宽度变小,那么面积想比之前的更大,唯一的可能是最短的短板比之前要高。
所以更高的木板根本没必要移动,动它没有任何意义。如果想在更短的宽度得到更大的面积,唯一的可能是移动最短的短板,以期望其变高。短板原理啊,朋友们,是不是刷着刷着题突然就领悟到了人生的哲理。
所以大家不要老是想这道题该不该用双指针去解;看清这题的本质,自然而然就意识到双指针显然是个较优解。 | problems/11_most_water/good_solution.py | maxArea | TanyeeZhang/leet-note-code | 0 | python | @staticmethod
def maxArea(height: List[int]) -> int:
'\n (以下段落摘抄自评论区)\n 其实我们显然可以发现影响问题的两个关键因素,一个是最短的短板,一个是宽度。\n 如果宽度变小,那么面积想比之前的更大,唯一的可能是最短的短板比之前要高。\n 所以更高的木板根本没必要移动,动它没有任何意义。如果想在更短的宽度得到更大的面积,唯一的可能是移动最短的短板,以期望其变高。短板原理啊,朋友们,是不是刷着刷着题突然就领悟到了人生的哲理。\n 所以大家不要老是想这道题该不该用双指针去解;看清这题的本质,自然而然... | @staticmethod
def maxArea(height: List[int]) -> int:
'\n (以下段落摘抄自评论区)\n 其实我们显然可以发现影响问题的两个关键因素,一个是最短的短板,一个是宽度。\n 如果宽度变小,那么面积想比之前的更大,唯一的可能是最短的短板比之前要高。\n 所以更高的木板根本没必要移动,动它没有任何意义。如果想在更短的宽度得到更大的面积,唯一的可能是移动最短的短板,以期望其变高。短板原理啊,朋友们,是不是刷着刷着题突然就领悟到了人生的哲理。\n 所以大家不要老是想这道题该不该用双指针去解;看清这题的本质,自然而然... |
2110a4e980c233cbc87bcc4252708ccd1535e5255a0fa1e7d34a9aae26b04e84 | def random_date(start, end):
'\n This function will return a random datetime between two datetime\n objects.\n '
delta = (end - start)
int_delta = ((((delta.days * 24) * 60) * 60) + delta.seconds)
random_second = randrange(int_delta)
return (start + timedelta(seconds=random_second)) | This function will return a random datetime between two datetime
objects. | src/tuberlin/inventory/management/commands/random_objekts.py | random_date | CircularBerlin/gmit | 0 | python | def random_date(start, end):
'\n This function will return a random datetime between two datetime\n objects.\n '
delta = (end - start)
int_delta = ((((delta.days * 24) * 60) * 60) + delta.seconds)
random_second = randrange(int_delta)
return (start + timedelta(seconds=random_second)) | def random_date(start, end):
'\n This function will return a random datetime between two datetime\n objects.\n '
delta = (end - start)
int_delta = ((((delta.days * 24) * 60) * 60) + delta.seconds)
random_second = randrange(int_delta)
return (start + timedelta(seconds=random_second))<|docstr... |
dc36bb4e4e6d6d904a1f62da78c769858183c37827e92be6951cd9713f1daab6 | def run_network(pgm):
'Run the intcode network'
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
computers[c].intcode()
... | Run the intcode network | aoc2019/day23.py | run_network | zoeimogen/AoC2019 | 0 | python | def run_network(pgm):
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
computers[c].intcode()
if (len(computers[c].s... | def run_network(pgm):
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
computers[c].intcode()
if (len(computers[c].s... |
193efc06f56f550f4c7309ce113644e509f44dee5e8b216e0fffa3a6aa14ab49 | def run_network_p2(pgm):
'Run the intcode network with NAT'
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
nat = (0, 0)
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
com... | Run the intcode network with NAT | aoc2019/day23.py | run_network_p2 | zoeimogen/AoC2019 | 0 | python | def run_network_p2(pgm):
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
nat = (0, 0)
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
computers[c].intcode()
if... | def run_network_p2(pgm):
computers = []
for c in range(0, 50):
computers.append(intcode.Program('network', copy.copy(pgm), [c]))
nat = (0, 0)
while True:
for c in range(0, 50):
if (computers[c].state['ptr'] != (- 1)):
computers[c].intcode()
if... |
cc9938fcc0b25533a32636449b49c6e3339aa6db4f7f3b3d60d8ad46a882ca71 | def run() -> Tuple[(int, int)]:
'Main'
with open('inputs/day23.txt') as f:
data = list(map(int, f.readline().split(',')))
part1 = run_network(data)
part2 = run_network_p2(data)
return (part1, part2) | Main | aoc2019/day23.py | run | zoeimogen/AoC2019 | 0 | python | def run() -> Tuple[(int, int)]:
with open('inputs/day23.txt') as f:
data = list(map(int, f.readline().split(',')))
part1 = run_network(data)
part2 = run_network_p2(data)
return (part1, part2) | def run() -> Tuple[(int, int)]:
with open('inputs/day23.txt') as f:
data = list(map(int, f.readline().split(',')))
part1 = run_network(data)
part2 = run_network_p2(data)
return (part1, part2)<|docstring|>Main<|endoftext|> |
10c9f699fffc1cbcf3ef2f8089e22e31bc66714bc61df7a9d49bb8028f6af31b | @staticmethod
def store_result(result: dict, filepath: str):
'Store the given result at the specified location'
ScanResultProcessor.store_json_convertible_result(result, filepath) | Store the given result at the specified location | core/scan_result_processor.py | store_result | RE4CT10N/avain | 51 | python | @staticmethod
def store_result(result: dict, filepath: str):
ScanResultProcessor.store_json_convertible_result(result, filepath) | @staticmethod
def store_result(result: dict, filepath: str):
ScanResultProcessor.store_json_convertible_result(result, filepath)<|docstring|>Store the given result at the specified location<|endoftext|> |
113c1b0d55e7ed547e0cbb64907791f9843e631372b31b3fc2acd27fdb70f9a3 | @staticmethod
def store_aggregated_result(aggr_result, filepath: str):
'Store the given aggregated result at the specified location'
ScanResultProcessor.store_json_convertible_result(aggr_result, filepath) | Store the given aggregated result at the specified location | core/scan_result_processor.py | store_aggregated_result | RE4CT10N/avain | 51 | python | @staticmethod
def store_aggregated_result(aggr_result, filepath: str):
ScanResultProcessor.store_json_convertible_result(aggr_result, filepath) | @staticmethod
def store_aggregated_result(aggr_result, filepath: str):
ScanResultProcessor.store_json_convertible_result(aggr_result, filepath)<|docstring|>Store the given aggregated result at the specified location<|endoftext|> |
438957c3c005e0f6186514b204c6154fab84c949c79ed6a5880c6276a3165d4e | def aggregate_results(self):
'\n Accumulate all retrieved scan results to one scan result.\n\n :return: a dict having host IPs as keys and their scan results as values\n '
if (not self.results):
result = {}
elif (len(self.results) == 1):
result = copy.deepcopy(self.resul... | Accumulate all retrieved scan results to one scan result.
:return: a dict having host IPs as keys and their scan results as values | core/scan_result_processor.py | aggregate_results | RE4CT10N/avain | 51 | python | def aggregate_results(self):
'\n Accumulate all retrieved scan results to one scan result.\n\n :return: a dict having host IPs as keys and their scan results as values\n '
if (not self.results):
result = {}
elif (len(self.results) == 1):
result = copy.deepcopy(self.resul... | def aggregate_results(self):
'\n Accumulate all retrieved scan results to one scan result.\n\n :return: a dict having host IPs as keys and their scan results as values\n '
if (not self.results):
result = {}
elif (len(self.results) == 1):
result = copy.deepcopy(self.resul... |
70b14611f18c094ea25c41400714b70519060e0e353ce51b5ad0341516cff6bf | def _group_by_product(self, intermediate_results):
'\n Group the intermediate results by their CPE product value (if it exists). Two items\n are grouped if they have the same part and vendor and the cosine similarity of their\n product strings is greater than 0.45.\n\n :param intermediat... | Group the intermediate results by their CPE product value (if it exists). Two items
are grouped if they have the same part and vendor and the cosine similarity of their
product strings is greater than 0.45.
:param intermediate_results: the intermediate results after first group and reduce
:return: the intermediate res... | core/scan_result_processor.py | _group_by_product | RE4CT10N/avain | 51 | python | def _group_by_product(self, intermediate_results):
'\n Group the intermediate results by their CPE product value (if it exists). Two items\n are grouped if they have the same part and vendor and the cosine similarity of their\n product strings is greater than 0.45.\n\n :param intermediat... | def _group_by_product(self, intermediate_results):
'\n Group the intermediate results by their CPE product value (if it exists). Two items\n are grouped if they have the same part and vendor and the cosine similarity of their\n product strings is greater than 0.45.\n\n :param intermediat... |
f2a28f43f1ecf0e11b1a930a321e5ccb094fb85b82eca91f9c70f77eda66fbc2 | def _aggregate_results(self):
'\n Aggregate the "grouped and reduced" results to one final result. The\n aggregation is done depending on the config value for "scan_result_aggr_scheme".\n\n Value "SINGLE" : the single result with the highest trust rating is chosen\n Value "MULTIPLE" : ... | Aggregate the "grouped and reduced" results to one final result. The
aggregation is done depending on the config value for "scan_result_aggr_scheme".
Value "SINGLE" : the single result with the highest trust rating is chosen
Value "MULTIPLE" : the results are returned without further processing
Value "FILTER" : si... | core/scan_result_processor.py | _aggregate_results | RE4CT10N/avain | 51 | python | def _aggregate_results(self):
'\n Aggregate the "grouped and reduced" results to one final result. The\n aggregation is done depending on the config value for "scan_result_aggr_scheme".\n\n Value "SINGLE" : the single result with the highest trust rating is chosen\n Value "MULTIPLE" : ... | def _aggregate_results(self):
'\n Aggregate the "grouped and reduced" results to one final result. The\n aggregation is done depending on the config value for "scan_result_aggr_scheme".\n\n Value "SINGLE" : the single result with the highest trust rating is chosen\n Value "MULTIPLE" : ... |
48b7ca6898c8dff73f5f2e911e3bb852fe924c95a9c4c716d89a46941eb96fb1 | def _group_and_reduce(self):
'\n First groups all the different OS and port information of every host\n retrieved from the different scanning modules into groups that contain\n similar items. For example, "OS: macOS 10.10 is" grouped together with\n "macOS 10.10.4".\n Next, these ... | First groups all the different OS and port information of every host
retrieved from the different scanning modules into groups that contain
similar items. For example, "OS: macOS 10.10 is" grouped together with
"macOS 10.10.4".
Next, these groups are reduced / aggregated to one entry each. This
can be done in several w... | core/scan_result_processor.py | _group_and_reduce | RE4CT10N/avain | 51 | python | def _group_and_reduce(self):
'\n First groups all the different OS and port information of every host\n retrieved from the different scanning modules into groups that contain\n similar items. For example, "OS: macOS 10.10 is" grouped together with\n "macOS 10.10.4".\n Next, these ... | def _group_and_reduce(self):
'\n First groups all the different OS and port information of every host\n retrieved from the different scanning modules into groups that contain\n similar items. For example, "OS: macOS 10.10 is" grouped together with\n "macOS 10.10.4".\n Next, these ... |
fd2794def9651aceac8cac8b1cb75b4b10d5c77985ce647793ad1b9d0483d951 | @staticmethod
def _add_trust(host: dict, trust_value: float):
'\n Add a trust value to every OS and port entry of the current host.\n '
def add_to_ports(protocol: str):
'\n Add trust values to the ports used by the given transport protocol.\n '
if (protocol i... | Add a trust value to every OS and port entry of the current host. | core/scan_result_processor.py | _add_trust | RE4CT10N/avain | 51 | python | @staticmethod
def _add_trust(host: dict, trust_value: float):
'\n \n '
def add_to_ports(protocol: str):
'\n Add trust values to the ports used by the given transport protocol.\n '
if (protocol in host):
for (portid, portitems) in host[protocol].it... | @staticmethod
def _add_trust(host: dict, trust_value: float):
'\n \n '
def add_to_ports(protocol: str):
'\n Add trust values to the ports used by the given transport protocol.\n '
if (protocol in host):
for (portid, portitems) in host[protocol].it... |
c169c550dcc8fec52df3305d8a05badef966edc9fc8fc18f3b9e89656573a08c | @staticmethod
def remove_trust_values(result: dict):
'\n Remove all potential "trust" fields stored in the given scan result\n '
def remove_in_protocol(protocol: str):
'\n Remove the trust values stored under the given transport protocol.\n '
if (protocol in ... | Remove all potential "trust" fields stored in the given scan result | core/scan_result_processor.py | remove_trust_values | RE4CT10N/avain | 51 | python | @staticmethod
def remove_trust_values(result: dict):
'\n \n '
def remove_in_protocol(protocol: str):
'\n Remove the trust values stored under the given transport protocol.\n '
if (protocol in host):
if ('trust' in host[protocol]):
... | @staticmethod
def remove_trust_values(result: dict):
'\n \n '
def remove_in_protocol(protocol: str):
'\n Remove the trust values stored under the given transport protocol.\n '
if (protocol in host):
if ('trust' in host[protocol]):
... |
102c56939e7ab1ad4e4bf481dec79a27ae14b822426c7c247134735b551e184c | def _group_item(self, ip: str, module, item: dict, dest: dict, iter_access_func: Callable[([dict], dict)]):
"\n Build a group based on the given item. The group consists of all entries that are\n similar to the given item. The mentioned entries are provided by all modules'\n scan results.\n\n ... | Build a group based on the given item. The group consists of all entries that are
similar to the given item. The mentioned entries are provided by all modules'
scan results.
:param item: the base item to group other items with
:param dest: the dictionary to store the resulting group in
:param iter_access_func: a funct... | core/scan_result_processor.py | _group_item | RE4CT10N/avain | 51 | python | def _group_item(self, ip: str, module, item: dict, dest: dict, iter_access_func: Callable[([dict], dict)]):
"\n Build a group based on the given item. The group consists of all entries that are\n similar to the given item. The mentioned entries are provided by all modules'\n scan results.\n\n ... | def _group_item(self, ip: str, module, item: dict, dest: dict, iter_access_func: Callable[([dict], dict)]):
"\n Build a group based on the given item. The group consists of all entries that are\n similar to the given item. The mentioned entries are provided by all modules'\n scan results.\n\n ... |
84239209e4a87a5b9722f9caed62520217b8c33d1f37aabc1828e62ad9f015ae | @staticmethod
def _get_most_specific_group_entry(group: list):
"\n Retrieve the most specific entry contained in the given group.\n\n :param group: the group of which to find its most specific entry\n :return: the given group's most specific entry as a dict\n "
most_specific_entry = ... | Retrieve the most specific entry contained in the given group.
:param group: the group of which to find its most specific entry
:return: the given group's most specific entry as a dict | core/scan_result_processor.py | _get_most_specific_group_entry | RE4CT10N/avain | 51 | python | @staticmethod
def _get_most_specific_group_entry(group: list):
"\n Retrieve the most specific entry contained in the given group.\n\n :param group: the group of which to find its most specific entry\n :return: the given group's most specific entry as a dict\n "
most_specific_entry = ... | @staticmethod
def _get_most_specific_group_entry(group: list):
"\n Retrieve the most specific entry contained in the given group.\n\n :param group: the group of which to find its most specific entry\n :return: the given group's most specific entry as a dict\n "
most_specific_entry = ... |
2ab7958e3b4416e154fb7a0c426baf35710c691ad52278965161ceeaf9a20ebb | @staticmethod
def _group_in(group: list, list_groups: list):
'\n Check if there exists a group in the second list parameter\n that contains all items in the given group (first list).\n\n :param group: the group to check whether all its items are already\n in a group contained in list_gro... | Check if there exists a group in the second list parameter
that contains all items in the given group (first list).
:param group: the group to check whether all its items are already
in a group contained in list_groups
:param list_groups: a list of item groups
:return: True if there is a group in list_groups that cont... | core/scan_result_processor.py | _group_in | RE4CT10N/avain | 51 | python | @staticmethod
def _group_in(group: list, list_groups: list):
'\n Check if there exists a group in the second list parameter\n that contains all items in the given group (first list).\n\n :param group: the group to check whether all its items are already\n in a group contained in list_gro... | @staticmethod
def _group_in(group: list, list_groups: list):
'\n Check if there exists a group in the second list parameter\n that contains all items in the given group (first list).\n\n :param group: the group to check whether all its items are already\n in a group contained in list_gro... |
8618d78d7e636ef999a97b53259129eb59458b0f9cc2b23f057751b458993347 | def _aggregate_group(self, group: list):
'\n Reduce the given group based on the algorithm specified by the\n respective configuration parameter.\n\n :param group: the group to reduce\n '
if (not group):
return {}
if (len(group) == 1):
return group[0]
if (not ... | Reduce the given group based on the algorithm specified by the
respective configuration parameter.
:param group: the group to reduce | core/scan_result_processor.py | _aggregate_group | RE4CT10N/avain | 51 | python | def _aggregate_group(self, group: list):
'\n Reduce the given group based on the algorithm specified by the\n respective configuration parameter.\n\n :param group: the group to reduce\n '
if (not group):
return {}
if (len(group) == 1):
return group[0]
if (not ... | def _aggregate_group(self, group: list):
'\n Reduce the given group based on the algorithm specified by the\n respective configuration parameter.\n\n :param group: the group to reduce\n '
if (not group):
return {}
if (len(group) == 1):
return group[0]
if (not ... |
bebfcc0dc6bfd5ff18e3a4ccb8448af293683c4e8c2e82f7b803f553f5978b3a | @staticmethod
def _aggregate_group_by_trust_max(group: list):
'\n Reduce the given group to the item with the highest trust value.\n\n :param group: the group to reduce\n '
return max(group, key=(lambda member: member['trust'])) | Reduce the given group to the item with the highest trust value.
:param group: the group to reduce | core/scan_result_processor.py | _aggregate_group_by_trust_max | RE4CT10N/avain | 51 | python | @staticmethod
def _aggregate_group_by_trust_max(group: list):
'\n Reduce the given group to the item with the highest trust value.\n\n :param group: the group to reduce\n '
return max(group, key=(lambda member: member['trust'])) | @staticmethod
def _aggregate_group_by_trust_max(group: list):
'\n Reduce the given group to the item with the highest trust value.\n\n :param group: the group to reduce\n '
return max(group, key=(lambda member: member['trust']))<|docstring|>Reduce the given group to the item with the highes... |
0c0bd2b002a8c668415bfa37b6319a5c3659eaaca9a8c164095c5516b9344a50 | @staticmethod
def _aggregate_group_by_trust_aggregation(group: list):
'\n Reduce the given group to its most specific entry and giving it a\n trust value based on all trust values contained in the group.\n\n :param group: the group to reduce\n '
grouping_strength = 0.675
most_spe... | Reduce the given group to its most specific entry and giving it a
trust value based on all trust values contained in the group.
:param group: the group to reduce | core/scan_result_processor.py | _aggregate_group_by_trust_aggregation | RE4CT10N/avain | 51 | python | @staticmethod
def _aggregate_group_by_trust_aggregation(group: list):
'\n Reduce the given group to its most specific entry and giving it a\n trust value based on all trust values contained in the group.\n\n :param group: the group to reduce\n '
grouping_strength = 0.675
most_spe... | @staticmethod
def _aggregate_group_by_trust_aggregation(group: list):
'\n Reduce the given group to its most specific entry and giving it a\n trust value based on all trust values contained in the group.\n\n :param group: the group to reduce\n '
grouping_strength = 0.675
most_spe... |
2ee892c01589760de760ea4f510ac18d96195bbc4f5baffc42885515ffc8967d | def group_os():
'\n Group the OS entry of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if ('os' not in host):
return
if (not ('os' in groups[ip])):
groups[ip]['os'] = []
if isinstanc... | Group the OS entry of the current host (of the current module)
with similar entries from other modules. | core/scan_result_processor.py | group_os | RE4CT10N/avain | 51 | python | def group_os():
'\n Group the OS entry of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if ('os' not in host):
return
if (not ('os' in groups[ip])):
groups[ip]['os'] = []
if isinstanc... | def group_os():
'\n Group the OS entry of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if ('os' not in host):
return
if (not ('os' in groups[ip])):
groups[ip]['os'] = []
if isinstanc... |
739e4da81c5a9ccc09ccf39409f69669d28e3d63a01c692f3d4820695bfe42d4 | def group_ports(protocol):
'\n Group the port entries of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if (protocol not in host):
return
if (protocol not in groups[ip]):
groups[ip][protoc... | Group the port entries of the current host (of the current module)
with similar entries from other modules. | core/scan_result_processor.py | group_ports | RE4CT10N/avain | 51 | python | def group_ports(protocol):
'\n Group the port entries of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if (protocol not in host):
return
if (protocol not in groups[ip]):
groups[ip][protoc... | def group_ports(protocol):
'\n Group the port entries of the current host (of the current module)\n with similar entries from other modules.\n '
nonlocal ip, host, module
if (protocol not in host):
return
if (protocol not in groups[ip]):
groups[ip][protoc... |
1c9b71ee8f66913ad95820940d5ff9be05e68662836bdb98b0a5bbdbd7d51df8 | def add_to_ports(protocol: str):
'\n Add trust values to the ports used by the given transport protocol.\n '
if (protocol in host):
for (portid, portitems) in host[protocol].items():
if (not isinstance(portitems, list)):
portitems = [portitems]
... | Add trust values to the ports used by the given transport protocol. | core/scan_result_processor.py | add_to_ports | RE4CT10N/avain | 51 | python | def add_to_ports(protocol: str):
'\n \n '
if (protocol in host):
for (portid, portitems) in host[protocol].items():
if (not isinstance(portitems, list)):
portitems = [portitems]
for port in portitems:
if ('trust' not in port):... | def add_to_ports(protocol: str):
'\n \n '
if (protocol in host):
for (portid, portitems) in host[protocol].items():
if (not isinstance(portitems, list)):
portitems = [portitems]
for port in portitems:
if ('trust' not in port):... |
c0fb1e09d410cfe47d751b088e32eb829b45dd85a878504ff8c533602c4e2e44 | def remove_in_protocol(protocol: str):
'\n Remove the trust values stored under the given transport protocol.\n '
if (protocol in host):
if ('trust' in host[protocol]):
del host[protocol]['trust']
for (_, portinfos) in host[protocol].items():
for por... | Remove the trust values stored under the given transport protocol. | core/scan_result_processor.py | remove_in_protocol | RE4CT10N/avain | 51 | python | def remove_in_protocol(protocol: str):
'\n \n '
if (protocol in host):
if ('trust' in host[protocol]):
del host[protocol]['trust']
for (_, portinfos) in host[protocol].items():
for portinfo in portinfos:
if ('trust' in portinfo):
... | def remove_in_protocol(protocol: str):
'\n \n '
if (protocol in host):
if ('trust' in host[protocol]):
del host[protocol]['trust']
for (_, portinfos) in host[protocol].items():
for portinfo in portinfos:
if ('trust' in portinfo):
... |
c9722585649f5a522e9bd0ba8ad2f99f37c32d751f204a2763ae491a4e2fd7b4 | def convert_to_unicode(text):
"Converts `text` to Unicode (if it's not already), assuming utf-8 input."
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text))) | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | pretraining/openwebtext/tokenization.py | convert_to_unicode | maact-org/electra-pytorch | 122 | python | def convert_to_unicode(text):
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text))) | def convert_to_unicode(text):
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text)))<|docstring|>Converts `text` to Unicode (if it's not already), assuming utf... |
5d16e8339f1a2108558267007284b132a3b2ff49172ecdca48c30001b7a9ff1f | def printable_text(text):
'Returns text encoded in a way suitable for print.'
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text))) | Returns text encoded in a way suitable for print. | pretraining/openwebtext/tokenization.py | printable_text | maact-org/electra-pytorch | 122 | python | def printable_text(text):
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text))) | def printable_text(text):
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported string type: %s' % type(text)))<|docstring|>Returns text encoded in a way suitable for print.<|endoftext|> |
b6db53f87d2a8191878cd1417b9c7d31d5793ed31cb8ff0c1d754bc43604b03b | def load_vocab(vocab_file):
'Loads a vocabulary file into a dictionary.'
vocab = collections.OrderedDict()
index = 0
with open(vocab_file, 'r') as reader:
while True:
token = convert_to_unicode(reader.readline())
if (not token):
break
token = t... | Loads a vocabulary file into a dictionary. | pretraining/openwebtext/tokenization.py | load_vocab | maact-org/electra-pytorch | 122 | python | def load_vocab(vocab_file):
vocab = collections.OrderedDict()
index = 0
with open(vocab_file, 'r') as reader:
while True:
token = convert_to_unicode(reader.readline())
if (not token):
break
token = token.strip()
vocab[token] = inde... | def load_vocab(vocab_file):
vocab = collections.OrderedDict()
index = 0
with open(vocab_file, 'r') as reader:
while True:
token = convert_to_unicode(reader.readline())
if (not token):
break
token = token.strip()
vocab[token] = inde... |
4a9dc032a794b0b240fd2dcd12395b9c294f5aad2f51268ee098c1a6140d9728 | def convert_by_vocab(vocab, items):
'Converts a sequence of [tokens|ids] using the vocab.'
output = []
for item in items:
output.append(vocab[item])
return output | Converts a sequence of [tokens|ids] using the vocab. | pretraining/openwebtext/tokenization.py | convert_by_vocab | maact-org/electra-pytorch | 122 | python | def convert_by_vocab(vocab, items):
output = []
for item in items:
output.append(vocab[item])
return output | def convert_by_vocab(vocab, items):
output = []
for item in items:
output.append(vocab[item])
return output<|docstring|>Converts a sequence of [tokens|ids] using the vocab.<|endoftext|> |
ca9c93e0f8264eaba166533fb04fc0ffb2ffab9b2aa3fa3f3f2e56caec09269f | def whitespace_tokenize(text):
'Runs basic whitespace cleaning and splitting on a piece of text.'
text = text.strip()
if (not text):
return []
tokens = text.split()
return tokens | Runs basic whitespace cleaning and splitting on a piece of text. | pretraining/openwebtext/tokenization.py | whitespace_tokenize | maact-org/electra-pytorch | 122 | python | def whitespace_tokenize(text):
text = text.strip()
if (not text):
return []
tokens = text.split()
return tokens | def whitespace_tokenize(text):
text = text.strip()
if (not text):
return []
tokens = text.split()
return tokens<|docstring|>Runs basic whitespace cleaning and splitting on a piece of text.<|endoftext|> |
c2af0c892229fa0e53a39bc6664a3159a9badeb37b2eec7ceaddbabd4d14707a | def _is_whitespace(char):
'Checks whether `chars` is a whitespace character.'
if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')):
return True
cat = unicodedata.category(char)
if (cat == 'Zs'):
return True
return False | Checks whether `chars` is a whitespace character. | pretraining/openwebtext/tokenization.py | _is_whitespace | maact-org/electra-pytorch | 122 | python | def _is_whitespace(char):
if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')):
return True
cat = unicodedata.category(char)
if (cat == 'Zs'):
return True
return False | def _is_whitespace(char):
if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')):
return True
cat = unicodedata.category(char)
if (cat == 'Zs'):
return True
return False<|docstring|>Checks whether `chars` is a whitespace character.<|endoftext|> |
67385be4e39d28d240dbee44ee5340c921fd5c03962386dbef535f84b0adf6df | def _is_control(char):
'Checks whether `chars` is a control character.'
if ((char == '\t') or (char == '\n') or (char == '\r')):
return False
cat = unicodedata.category(char)
if cat.startswith('C'):
return True
return False | Checks whether `chars` is a control character. | pretraining/openwebtext/tokenization.py | _is_control | maact-org/electra-pytorch | 122 | python | def _is_control(char):
if ((char == '\t') or (char == '\n') or (char == '\r')):
return False
cat = unicodedata.category(char)
if cat.startswith('C'):
return True
return False | def _is_control(char):
if ((char == '\t') or (char == '\n') or (char == '\r')):
return False
cat = unicodedata.category(char)
if cat.startswith('C'):
return True
return False<|docstring|>Checks whether `chars` is a control character.<|endoftext|> |
3036677df4a6a5fa3c51c846042ea3dd4acd704720bd66e96a0ec2dff3e7804a | def _is_punctuation(char):
'Checks whether `chars` is a punctuation character.'
cp = ord(char)
if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))):
return True
cat = unicodedata.category(char)
if cat.startswith('P'):... | Checks whether `chars` is a punctuation character. | pretraining/openwebtext/tokenization.py | _is_punctuation | maact-org/electra-pytorch | 122 | python | def _is_punctuation(char):
cp = ord(char)
if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))):
return True
cat = unicodedata.category(char)
if cat.startswith('P'):
return True
return False | def _is_punctuation(char):
cp = ord(char)
if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))):
return True
cat = unicodedata.category(char)
if cat.startswith('P'):
return True
return False<|docstring|>Ch... |
ba62f16d20314afeae3ede46ba056ee9eb2c4bd6ef4bfa593c6527add1c57062 | def __init__(self, do_lower_case=True):
'Constructs a BasicTokenizer.\n\n\t\tArgs:\n\t\t\tdo_lower_case: Whether to lower case the input.\n\t\t'
self.do_lower_case = do_lower_case | Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input. | pretraining/openwebtext/tokenization.py | __init__ | maact-org/electra-pytorch | 122 | python | def __init__(self, do_lower_case=True):
'Constructs a BasicTokenizer.\n\n\t\tArgs:\n\t\t\tdo_lower_case: Whether to lower case the input.\n\t\t'
self.do_lower_case = do_lower_case | def __init__(self, do_lower_case=True):
'Constructs a BasicTokenizer.\n\n\t\tArgs:\n\t\t\tdo_lower_case: Whether to lower case the input.\n\t\t'
self.do_lower_case = do_lower_case<|docstring|>Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.<|endoftext|> |
3c7946930bb61b5cc2480959ef1fd494bdc1d3f0739f606533e0f19f895c8340 | def tokenize(self, text):
'Tokenizes a piece of text.'
text = convert_to_unicode(text)
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token ... | Tokenizes a piece of text. | pretraining/openwebtext/tokenization.py | tokenize | maact-org/electra-pytorch | 122 | python | def tokenize(self, text):
text = convert_to_unicode(text)
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
... | def tokenize(self, text):
text = convert_to_unicode(text)
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
... |
666f3fb2d4b7ff45415e4e3c9d59d5fb364eec7360af935fffec5d85341cd417 | def _run_strip_accents(self, text):
'Strips accents from a piece of text.'
text = unicodedata.normalize('NFD', text)
output = []
for char in text:
cat = unicodedata.category(char)
if (cat == 'Mn'):
continue
output.append(char)
return ''.join(output) | Strips accents from a piece of text. | pretraining/openwebtext/tokenization.py | _run_strip_accents | maact-org/electra-pytorch | 122 | python | def _run_strip_accents(self, text):
text = unicodedata.normalize('NFD', text)
output = []
for char in text:
cat = unicodedata.category(char)
if (cat == 'Mn'):
continue
output.append(char)
return .join(output) | def _run_strip_accents(self, text):
text = unicodedata.normalize('NFD', text)
output = []
for char in text:
cat = unicodedata.category(char)
if (cat == 'Mn'):
continue
output.append(char)
return .join(output)<|docstring|>Strips accents from a piece of text.<|endo... |
6f77e2aee6fad165c2cc79fd43331b3689f7566954f401421fd2b3078ba07d15 | def _run_split_on_punc(self, text):
'Splits punctuation on a piece of text.'
chars = list(text)
i = 0
start_new_word = True
output = []
while (i < len(chars)):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
el... | Splits punctuation on a piece of text. | pretraining/openwebtext/tokenization.py | _run_split_on_punc | maact-org/electra-pytorch | 122 | python | def _run_split_on_punc(self, text):
chars = list(text)
i = 0
start_new_word = True
output = []
while (i < len(chars)):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
... | def _run_split_on_punc(self, text):
chars = list(text)
i = 0
start_new_word = True
output = []
while (i < len(chars)):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
... |
b35514042aac23aaf27f35a348b0f9fab0be127d05ecf3a4134759ba41954fc1 | def _tokenize_chinese_chars(self, text):
'Adds whitespace around any CJK character.'
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(' ')
output.append(char)
output.append(' ')
else:
output.appen... | Adds whitespace around any CJK character. | pretraining/openwebtext/tokenization.py | _tokenize_chinese_chars | maact-org/electra-pytorch | 122 | python | def _tokenize_chinese_chars(self, text):
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(' ')
output.append(char)
output.append(' ')
else:
output.append(char)
return .join(output) | def _tokenize_chinese_chars(self, text):
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(' ')
output.append(char)
output.append(' ')
else:
output.append(char)
return .join(output)<|docstring... |
70697919acb3c18bd2db785cf0971a446ae6062102038ca37a477129c8bda201 | def _is_chinese_char(self, cp):
'Checks whether CP is the codepoint of a CJK character.'
if (((cp >= 19968) and (cp <= 40959)) or ((cp >= 13312) and (cp <= 19903)) or ((cp >= 131072) and (cp <= 173791)) or ((cp >= 173824) and (cp <= 177983)) or ((cp >= 177984) and (cp <= 178207)) or ((cp >= 178208) and (cp <= 1... | Checks whether CP is the codepoint of a CJK character. | pretraining/openwebtext/tokenization.py | _is_chinese_char | maact-org/electra-pytorch | 122 | python | def _is_chinese_char(self, cp):
if (((cp >= 19968) and (cp <= 40959)) or ((cp >= 13312) and (cp <= 19903)) or ((cp >= 131072) and (cp <= 173791)) or ((cp >= 173824) and (cp <= 177983)) or ((cp >= 177984) and (cp <= 178207)) or ((cp >= 178208) and (cp <= 183983)) or ((cp >= 63744) and (cp <= 64255)) or ((cp >= ... | def _is_chinese_char(self, cp):
if (((cp >= 19968) and (cp <= 40959)) or ((cp >= 13312) and (cp <= 19903)) or ((cp >= 131072) and (cp <= 173791)) or ((cp >= 173824) and (cp <= 177983)) or ((cp >= 177984) and (cp <= 178207)) or ((cp >= 178208) and (cp <= 183983)) or ((cp >= 63744) and (cp <= 64255)) or ((cp >= ... |
5a6ae5e539033f597bf772d75b92c83ada8c6605fc6627b6ecdbf4cfeba8f187 | def _clean_text(self, text):
'Performs invalid character removal and whitespace cleanup on text.'
output = []
for char in text:
cp = ord(char)
if ((cp == 0) or (cp == 65533) or _is_control(char)):
continue
if _is_whitespace(char):
output.append(' ')
el... | Performs invalid character removal and whitespace cleanup on text. | pretraining/openwebtext/tokenization.py | _clean_text | maact-org/electra-pytorch | 122 | python | def _clean_text(self, text):
output = []
for char in text:
cp = ord(char)
if ((cp == 0) or (cp == 65533) or _is_control(char)):
continue
if _is_whitespace(char):
output.append(' ')
else:
output.append(char)
return .join(output) | def _clean_text(self, text):
output = []
for char in text:
cp = ord(char)
if ((cp == 0) or (cp == 65533) or _is_control(char)):
continue
if _is_whitespace(char):
output.append(' ')
else:
output.append(char)
return .join(output)<|docstr... |
589f10da2306b0e3bc593dcb459ea151773675ddfc1455b5d033d9122817ab47 | def tokenize(self, text):
'Tokenizes a piece of text into its word pieces.\n\n\t\tThis uses a greedy longest-match-first algorithm to perform tokenization\n\t\tusing the given vocabulary.\n\n\t\tFor example:\n\t\t\tinput = "unaffable"\n\t\t\toutput = ["un", "##aff", "##able"]\n\n\t\tArgs:\n\t\t\ttext: A single toke... | Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
... | pretraining/openwebtext/tokenization.py | tokenize | maact-org/electra-pytorch | 122 | python | def tokenize(self, text):
'Tokenizes a piece of text into its word pieces.\n\n\t\tThis uses a greedy longest-match-first algorithm to perform tokenization\n\t\tusing the given vocabulary.\n\n\t\tFor example:\n\t\t\tinput = "unaffable"\n\t\t\toutput = ["un", "##aff", "##able"]\n\n\t\tArgs:\n\t\t\ttext: A single toke... | def tokenize(self, text):
'Tokenizes a piece of text into its word pieces.\n\n\t\tThis uses a greedy longest-match-first algorithm to perform tokenization\n\t\tusing the given vocabulary.\n\n\t\tFor example:\n\t\t\tinput = "unaffable"\n\t\t\toutput = ["un", "##aff", "##able"]\n\n\t\tArgs:\n\t\t\ttext: A single toke... |
351a9c9150297eac4727e1d69579a3f2773b57fbb5492c8d1ef55f11e55d1987 | def xgboost_cv(max_depth: int, gamma: float, min_child_weight: float, scale_pos_weight: float, n_estimators: int, reg_alpha: float, reg_lambda: float, max_delta_step: float, subsample: float, colsample_bytree: float, learning_rate: float, data: pd.DataFrame, targets: pd.DataFrame, n_jobs: int) -> float:
'XGBoost wi... | XGBoost with 5 times repeated 5 fold cross validation.
Parameters
----------
max_depth: int
Maximum depth of a tree.
gamma: float
Minimum loss reduction required to make a further partition on a leaf node of the tree. The larger gamma is,
the more conservative the algorithm will be.
min_child_weight: float... | src/models.py | xgboost_cv | MoritzFeigl/Learning-from-mistakes | 0 | python | def xgboost_cv(max_depth: int, gamma: float, min_child_weight: float, scale_pos_weight: float, n_estimators: int, reg_alpha: float, reg_lambda: float, max_delta_step: float, subsample: float, colsample_bytree: float, learning_rate: float, data: pd.DataFrame, targets: pd.DataFrame, n_jobs: int) -> float:
'XGBoost wi... | def xgboost_cv(max_depth: int, gamma: float, min_child_weight: float, scale_pos_weight: float, n_estimators: int, reg_alpha: float, reg_lambda: float, max_delta_step: float, subsample: float, colsample_bytree: float, learning_rate: float, data: pd.DataFrame, targets: pd.DataFrame, n_jobs: int) -> float:
'XGBoost wi... |
9a623a4fe5de9aac86a680df0ad4f00a59327d2e44d7615edd89d43523882970 | def optimize_xgboost(data: pd.DataFrame, targets: pd.DataFrame, init_points: int, n_iter: int, n_jobs: int) -> bayes_opt.bayesian_optimization.BayesianOptimization:
' Bayesian Optimization of XGBoost parameters\n\n Parameters\n ----------\n data: pd.DataFrame\n Features (input data) used to train th... | Bayesian Optimization of XGBoost parameters
Parameters
----------
data: pd.DataFrame
Features (input data) used to train the model.
targets: pd.DataFrame
Labels used for training.
init_points: int
Number of randomly chosen points at the beginning of the optimization.
n_iter: int
Number of iterations.
n... | src/models.py | optimize_xgboost | MoritzFeigl/Learning-from-mistakes | 0 | python | def optimize_xgboost(data: pd.DataFrame, targets: pd.DataFrame, init_points: int, n_iter: int, n_jobs: int) -> bayes_opt.bayesian_optimization.BayesianOptimization:
' Bayesian Optimization of XGBoost parameters\n\n Parameters\n ----------\n data: pd.DataFrame\n Features (input data) used to train th... | def optimize_xgboost(data: pd.DataFrame, targets: pd.DataFrame, init_points: int, n_iter: int, n_jobs: int) -> bayes_opt.bayesian_optimization.BayesianOptimization:
' Bayesian Optimization of XGBoost parameters\n\n Parameters\n ----------\n data: pd.DataFrame\n Features (input data) used to train th... |
5910dbb38c9796577e48feefd99881745fee08d48c98e719d88bb577fa96f148 | def variance_inflation(self):
'Variance inflation factor for regressors of a linear model\n Computes variance inflation factor for all regressors.\n '
vif = pd.DataFrame({'variables': self.x.columns, 'VIF': [out.variance_inflation_factor(self.x.values, i) for i in range(self.x.shape[1])]})
pri... | Variance inflation factor for regressors of a linear model
Computes variance inflation factor for all regressors. | src/models.py | variance_inflation | MoritzFeigl/Learning-from-mistakes | 0 | python | def variance_inflation(self):
'Variance inflation factor for regressors of a linear model\n Computes variance inflation factor for all regressors.\n '
vif = pd.DataFrame({'variables': self.x.columns, 'VIF': [out.variance_inflation_factor(self.x.values, i) for i in range(self.x.shape[1])]})
pri... | def variance_inflation(self):
'Variance inflation factor for regressors of a linear model\n Computes variance inflation factor for all regressors.\n '
vif = pd.DataFrame({'variables': self.x.columns, 'VIF': [out.variance_inflation_factor(self.x.values, i) for i in range(self.x.shape[1])]})
pri... |
2825ee512f457844ec2b6be1d96fe66180344d3c67f3bf61499906d171f1adfe | def center_data(self):
' Data centering\n Centers data to reduce influence of multicollinearity.\n '
self.x = self.x.drop(columns='const')
data_centered = pd.DataFrame(preprocessing.scale(self.x, with_mean='True', with_std='False'))
data_centered.columns = self.x.columns
data_centered.... | Data centering
Centers data to reduce influence of multicollinearity. | src/models.py | center_data | MoritzFeigl/Learning-from-mistakes | 0 | python | def center_data(self):
' Data centering\n Centers data to reduce influence of multicollinearity.\n '
self.x = self.x.drop(columns='const')
data_centered = pd.DataFrame(preprocessing.scale(self.x, with_mean='True', with_std='False'))
data_centered.columns = self.x.columns
data_centered.... | def center_data(self):
' Data centering\n Centers data to reduce influence of multicollinearity.\n '
self.x = self.x.drop(columns='const')
data_centered = pd.DataFrame(preprocessing.scale(self.x, with_mean='True', with_std='False'))
data_centered.columns = self.x.columns
data_centered.... |
abc4644a30b7271284b6db71fade71d19d2e153b95b98c6b1c1ce328ba5f1f25 | def fit(self):
' Fit OLS regression model\n Fits a OLS regression model of the form y ~ x + intercept\n '
model = api.OLS(self.y, self.x)
results = model.fit()
print(results.summary())
with open('results/tables/regression_model.csv', 'w') as fh:
fh.write(results.summary().as_cs... | Fit OLS regression model
Fits a OLS regression model of the form y ~ x + intercept | src/models.py | fit | MoritzFeigl/Learning-from-mistakes | 0 | python | def fit(self):
' Fit OLS regression model\n Fits a OLS regression model of the form y ~ x + intercept\n '
model = api.OLS(self.y, self.x)
results = model.fit()
print(results.summary())
with open('results/tables/regression_model.csv', 'w') as fh:
fh.write(results.summary().as_cs... | def fit(self):
' Fit OLS regression model\n Fits a OLS regression model of the form y ~ x + intercept\n '
model = api.OLS(self.y, self.x)
results = model.fit()
print(results.summary())
with open('results/tables/regression_model.csv', 'w') as fh:
fh.write(results.summary().as_cs... |
eadde10281031d482273f257c56db1b9bacb3b461bf9a6358de5ed3e74cf139a | def xgboost_crossval(max_depth, gamma, n_estimators, min_child_weight, scale_pos_weight, reg_alpha, reg_lambda, max_delta_step, subsample, colsample_bytree, learning_rate):
'Wrapper of XGBoost cross validation.'
return xgboost_cv(n_estimators=int(n_estimators), max_depth=int(max_depth), gamma=gamma, min_child_w... | Wrapper of XGBoost cross validation. | src/models.py | xgboost_crossval | MoritzFeigl/Learning-from-mistakes | 0 | python | def xgboost_crossval(max_depth, gamma, n_estimators, min_child_weight, scale_pos_weight, reg_alpha, reg_lambda, max_delta_step, subsample, colsample_bytree, learning_rate):
return xgboost_cv(n_estimators=int(n_estimators), max_depth=int(max_depth), gamma=gamma, min_child_weight=min_child_weight, scale_pos_weig... | def xgboost_crossval(max_depth, gamma, n_estimators, min_child_weight, scale_pos_weight, reg_alpha, reg_lambda, max_delta_step, subsample, colsample_bytree, learning_rate):
return xgboost_cv(n_estimators=int(n_estimators), max_depth=int(max_depth), gamma=gamma, min_child_weight=min_child_weight, scale_pos_weig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.