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 |
|---|---|---|---|---|---|---|---|---|---|
1c34ab171b5a6a1be6ff553ea4b6ef16131c413ad24dfe4a611e1ea0768a5725 | def parse(html, solar_duration_as_minutes=False):
'\n Parse the html from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html to a Pandas DataFrame\n\n Parameters\n ----------\n html : str\n solar_duration_as_minutes : bool\n\n Returns\n -------\n Pandas DataFrame\n '
soup = bs4.BeautifulSoup(html, 'html.parser')
day_values = soup.findAll('tbody')[1]
table_rows = day_values.findAll('tr')
titles = table_rows[0].findAll('th')
column_names = ['_'.join(title.text.replace('.', '').split()).lower() for title in titles]
rows = []
last_date = dt.date.today()
for row in reversed(table_rows[2:]):
values = []
for (title, td) in zip(column_names, row.findAll('td')):
if (title == 'datum'):
day = int(td.text.split(' ')[0])
while (day != last_date.day):
last_date = (last_date - dt.timedelta(days=1))
values.append(last_date)
elif (title == 'zon_duur'):
try:
(hour, minute) = td.text.split(':')
if solar_duration_as_minutes:
time = ((int(hour) * 60) + int(minute))
else:
time = dt.time(hour=int(hour), minute=int(minute))
except ValueError:
if solar_duration_as_minutes:
time = float('NaN')
else:
time = pd.NaT
values.append(time)
else:
try:
val = float(td.text.replace(',', '.'))
except ValueError:
val = float('NaN')
values.append(val)
rows.append(values)
df = pd.DataFrame(rows, columns=column_names).set_index('datum')
df.index = pd.DatetimeIndex(df.index)
df = df.sort_index().tz_localize('Europe/Brussels')
return df | Parse the html from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html to a Pandas DataFrame
Parameters
----------
html : str
solar_duration_as_minutes : bool
Returns
-------
Pandas DataFrame | opengrid_dev/library/kmi.py | parse | opengridcc/opengrid_dev | 8 | python | def parse(html, solar_duration_as_minutes=False):
'\n Parse the html from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html to a Pandas DataFrame\n\n Parameters\n ----------\n html : str\n solar_duration_as_minutes : bool\n\n Returns\n -------\n Pandas DataFrame\n '
soup = bs4.BeautifulSoup(html, 'html.parser')
day_values = soup.findAll('tbody')[1]
table_rows = day_values.findAll('tr')
titles = table_rows[0].findAll('th')
column_names = ['_'.join(title.text.replace('.', ).split()).lower() for title in titles]
rows = []
last_date = dt.date.today()
for row in reversed(table_rows[2:]):
values = []
for (title, td) in zip(column_names, row.findAll('td')):
if (title == 'datum'):
day = int(td.text.split(' ')[0])
while (day != last_date.day):
last_date = (last_date - dt.timedelta(days=1))
values.append(last_date)
elif (title == 'zon_duur'):
try:
(hour, minute) = td.text.split(':')
if solar_duration_as_minutes:
time = ((int(hour) * 60) + int(minute))
else:
time = dt.time(hour=int(hour), minute=int(minute))
except ValueError:
if solar_duration_as_minutes:
time = float('NaN')
else:
time = pd.NaT
values.append(time)
else:
try:
val = float(td.text.replace(',', '.'))
except ValueError:
val = float('NaN')
values.append(val)
rows.append(values)
df = pd.DataFrame(rows, columns=column_names).set_index('datum')
df.index = pd.DatetimeIndex(df.index)
df = df.sort_index().tz_localize('Europe/Brussels')
return df | def parse(html, solar_duration_as_minutes=False):
'\n Parse the html from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html to a Pandas DataFrame\n\n Parameters\n ----------\n html : str\n solar_duration_as_minutes : bool\n\n Returns\n -------\n Pandas DataFrame\n '
soup = bs4.BeautifulSoup(html, 'html.parser')
day_values = soup.findAll('tbody')[1]
table_rows = day_values.findAll('tr')
titles = table_rows[0].findAll('th')
column_names = ['_'.join(title.text.replace('.', ).split()).lower() for title in titles]
rows = []
last_date = dt.date.today()
for row in reversed(table_rows[2:]):
values = []
for (title, td) in zip(column_names, row.findAll('td')):
if (title == 'datum'):
day = int(td.text.split(' ')[0])
while (day != last_date.day):
last_date = (last_date - dt.timedelta(days=1))
values.append(last_date)
elif (title == 'zon_duur'):
try:
(hour, minute) = td.text.split(':')
if solar_duration_as_minutes:
time = ((int(hour) * 60) + int(minute))
else:
time = dt.time(hour=int(hour), minute=int(minute))
except ValueError:
if solar_duration_as_minutes:
time = float('NaN')
else:
time = pd.NaT
values.append(time)
else:
try:
val = float(td.text.replace(',', '.'))
except ValueError:
val = float('NaN')
values.append(val)
rows.append(values)
df = pd.DataFrame(rows, columns=column_names).set_index('datum')
df.index = pd.DatetimeIndex(df.index)
df = df.sort_index().tz_localize('Europe/Brussels')
return df<|docstring|>Parse the html from http://www.meteo.be/meteo/view/nl/123763-Huidige+maand.html to a Pandas DataFrame
Parameters
----------
html : str
solar_duration_as_minutes : bool
Returns
-------
Pandas DataFrame<|endoftext|> |
5811cc24baa97e897669c27d91d3e6f0f30eceff1e119c63fc39056505179e63 | def choose_include_text(s, params, source_path):
'Given the contents of a file and !inc[these params], return matching lines\n\n If there was a problem matching parameters, return empty list.\n\n :param s: file\'s text\n :param params: string like "start-at=foo&end-at=bar"\n :param source_path: path to source .md. Useful in error messages\n '
lines = s.splitlines()
start_after = None
start_at = None
end_before = None
end_at = None
for term in params.split('&'):
if ('=' in term):
(param, value) = [p.strip() for p in term.split('=', 1)]
else:
(param, value) = (term.strip(), '')
if (not param):
continue
if (param == 'start-after'):
start_after = value
elif (param == 'start-at'):
start_at = value
elif (param == 'end-before'):
end_before = value
elif (param == 'end-at'):
end_at = value
else:
raise TaskError('Invalid include directive "{0}" in {1}'.format(params, source_path))
chosen_lines = []
for line_ix in range(0, len(lines)):
line = lines[line_ix]
if ((not start_at) and (not start_after)):
break
if ((start_at is not None) and (start_at in line)):
break
if ((start_after is not None) and (start_after in line)):
line_ix += 1
break
else:
return ''
for line_ix in range(line_ix, len(lines)):
line = lines[line_ix]
if ((end_before is not None) and (end_before in line)):
break
chosen_lines.append(line)
if ((end_at is not None) and (end_at in line)):
break
else:
if (end_before or end_at):
return ''
return '\n'.join(chosen_lines) | Given the contents of a file and !inc[these params], return matching lines
If there was a problem matching parameters, return empty list.
:param s: file's text
:param params: string like "start-at=foo&end-at=bar"
:param source_path: path to source .md. Useful in error messages | src/python/pants/backend/core/tasks/markdown_to_html.py | choose_include_text | lcary/pants | 0 | python | def choose_include_text(s, params, source_path):
'Given the contents of a file and !inc[these params], return matching lines\n\n If there was a problem matching parameters, return empty list.\n\n :param s: file\'s text\n :param params: string like "start-at=foo&end-at=bar"\n :param source_path: path to source .md. Useful in error messages\n '
lines = s.splitlines()
start_after = None
start_at = None
end_before = None
end_at = None
for term in params.split('&'):
if ('=' in term):
(param, value) = [p.strip() for p in term.split('=', 1)]
else:
(param, value) = (term.strip(), )
if (not param):
continue
if (param == 'start-after'):
start_after = value
elif (param == 'start-at'):
start_at = value
elif (param == 'end-before'):
end_before = value
elif (param == 'end-at'):
end_at = value
else:
raise TaskError('Invalid include directive "{0}" in {1}'.format(params, source_path))
chosen_lines = []
for line_ix in range(0, len(lines)):
line = lines[line_ix]
if ((not start_at) and (not start_after)):
break
if ((start_at is not None) and (start_at in line)):
break
if ((start_after is not None) and (start_after in line)):
line_ix += 1
break
else:
return
for line_ix in range(line_ix, len(lines)):
line = lines[line_ix]
if ((end_before is not None) and (end_before in line)):
break
chosen_lines.append(line)
if ((end_at is not None) and (end_at in line)):
break
else:
if (end_before or end_at):
return
return '\n'.join(chosen_lines) | def choose_include_text(s, params, source_path):
'Given the contents of a file and !inc[these params], return matching lines\n\n If there was a problem matching parameters, return empty list.\n\n :param s: file\'s text\n :param params: string like "start-at=foo&end-at=bar"\n :param source_path: path to source .md. Useful in error messages\n '
lines = s.splitlines()
start_after = None
start_at = None
end_before = None
end_at = None
for term in params.split('&'):
if ('=' in term):
(param, value) = [p.strip() for p in term.split('=', 1)]
else:
(param, value) = (term.strip(), )
if (not param):
continue
if (param == 'start-after'):
start_after = value
elif (param == 'start-at'):
start_at = value
elif (param == 'end-before'):
end_before = value
elif (param == 'end-at'):
end_at = value
else:
raise TaskError('Invalid include directive "{0}" in {1}'.format(params, source_path))
chosen_lines = []
for line_ix in range(0, len(lines)):
line = lines[line_ix]
if ((not start_at) and (not start_after)):
break
if ((start_at is not None) and (start_at in line)):
break
if ((start_after is not None) and (start_after in line)):
line_ix += 1
break
else:
return
for line_ix in range(line_ix, len(lines)):
line = lines[line_ix]
if ((end_before is not None) and (end_before in line)):
break
chosen_lines.append(line)
if ((end_at is not None) and (end_at in line)):
break
else:
if (end_before or end_at):
return
return '\n'.join(chosen_lines)<|docstring|>Given the contents of a file and !inc[these params], return matching lines
If there was a problem matching parameters, return empty list.
:param s: file's text
:param params: string like "start-at=foo&end-at=bar"
:param source_path: path to source .md. Useful in error messages<|endoftext|> |
24975bd7c365edb85d05b329b9ba46c107860c1df617aa64811f5af29abb7799 | def page_to_html_path(page):
'Given a page target, return partial path for an output `.html`.'
source_path = page.sources_relative_to_buildroot()[0]
return (os.path.splitext(source_path)[0] + '.html') | Given a page target, return partial path for an output `.html`. | src/python/pants/backend/core/tasks/markdown_to_html.py | page_to_html_path | lcary/pants | 0 | python | def page_to_html_path(page):
source_path = page.sources_relative_to_buildroot()[0]
return (os.path.splitext(source_path)[0] + '.html') | def page_to_html_path(page):
source_path = page.sources_relative_to_buildroot()[0]
return (os.path.splitext(source_path)[0] + '.html')<|docstring|>Given a page target, return partial path for an output `.html`.<|endoftext|> |
610d109bed86e33bc8390c0504eb23d552fbb9fc5f7ff7cf3c40e3ac484c8928 | def rst_to_html(in_rst, stderr):
'Renders HTML from an RST fragment.\n\n :param string in_rst: An rst formatted string.\n :param stderr: An open stream to use for docutils stderr output.\n :returns: A tuple of (html rendered rst, return code)\n '
if (not in_rst):
return ('', 0)
orig_sys_exit = sys.exit
orig_sys_stderr = sys.stderr
returncodes = []
try:
sys.exit = returncodes.append
sys.stderr = stderr
pp = publish_parts(in_rst, writer_name='html', settings_overrides=dict(exit_status_level=2, report_level=2), enable_exit_status=True)
finally:
sys.exit = orig_sys_exit
sys.stderr = orig_sys_stderr
return_value = ''
if (('title' in pp) and pp['title']):
return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title'])
return_value += pp['body'].strip()
return (return_value, (returncodes.pop() if returncodes else 0)) | Renders HTML from an RST fragment.
:param string in_rst: An rst formatted string.
:param stderr: An open stream to use for docutils stderr output.
:returns: A tuple of (html rendered rst, return code) | src/python/pants/backend/core/tasks/markdown_to_html.py | rst_to_html | lcary/pants | 0 | python | def rst_to_html(in_rst, stderr):
'Renders HTML from an RST fragment.\n\n :param string in_rst: An rst formatted string.\n :param stderr: An open stream to use for docutils stderr output.\n :returns: A tuple of (html rendered rst, return code)\n '
if (not in_rst):
return (, 0)
orig_sys_exit = sys.exit
orig_sys_stderr = sys.stderr
returncodes = []
try:
sys.exit = returncodes.append
sys.stderr = stderr
pp = publish_parts(in_rst, writer_name='html', settings_overrides=dict(exit_status_level=2, report_level=2), enable_exit_status=True)
finally:
sys.exit = orig_sys_exit
sys.stderr = orig_sys_stderr
return_value =
if (('title' in pp) and pp['title']):
return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title'])
return_value += pp['body'].strip()
return (return_value, (returncodes.pop() if returncodes else 0)) | def rst_to_html(in_rst, stderr):
'Renders HTML from an RST fragment.\n\n :param string in_rst: An rst formatted string.\n :param stderr: An open stream to use for docutils stderr output.\n :returns: A tuple of (html rendered rst, return code)\n '
if (not in_rst):
return (, 0)
orig_sys_exit = sys.exit
orig_sys_stderr = sys.stderr
returncodes = []
try:
sys.exit = returncodes.append
sys.stderr = stderr
pp = publish_parts(in_rst, writer_name='html', settings_overrides=dict(exit_status_level=2, report_level=2), enable_exit_status=True)
finally:
sys.exit = orig_sys_exit
sys.stderr = orig_sys_stderr
return_value =
if (('title' in pp) and pp['title']):
return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title'])
return_value += pp['body'].strip()
return (return_value, (returncodes.pop() if returncodes else 0))<|docstring|>Renders HTML from an RST fragment.
:param string in_rst: An rst formatted string.
:param stderr: An open stream to use for docutils stderr output.
:returns: A tuple of (html rendered rst, return code)<|endoftext|> |
74fcb5c4baa191bbf6791a06ed020a3796e2a9a370d45dffcb1e65441844ec36 | def __init__(self, source_path=None):
'\n :param string source_path: Path to source `.md` file.\n '
markdown.inlinepatterns.Pattern.__init__(self, INCLUDE_PATTERN)
self.source_path = source_path | :param string source_path: Path to source `.md` file. | src/python/pants/backend/core/tasks/markdown_to_html.py | __init__ | lcary/pants | 0 | python | def __init__(self, source_path=None):
'\n \n '
markdown.inlinepatterns.Pattern.__init__(self, INCLUDE_PATTERN)
self.source_path = source_path | def __init__(self, source_path=None):
'\n \n '
markdown.inlinepatterns.Pattern.__init__(self, INCLUDE_PATTERN)
self.source_path = source_path<|docstring|>:param string source_path: Path to source `.md` file.<|endoftext|> |
965944c75524e9ff260d5b7eddf707a6f5760dda8f5c7f7a37b9229534509b3c | def test_source(self):
'\n FileDependency should accept source name wich will be later used as a\n key in .paths.\n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
dependency.set_parent(parent)
assert (dependency.path == 'success') | FileDependency should accept source name wich will be later used as a
key in .paths. | baelfire/dependencies/tests/test_file.py | test_source | socek/baelfire | 0 | python | def test_source(self):
'\n FileDependency should accept source name wich will be later used as a\n key in .paths.\n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
dependency.set_parent(parent)
assert (dependency.path == 'success') | def test_source(self):
'\n FileDependency should accept source name wich will be later used as a\n key in .paths.\n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
dependency.set_parent(parent)
assert (dependency.path == 'success')<|docstring|>FileDependency should accept source name wich will be later used as a
key in .paths.<|endoftext|> |
5e0617f7e2be6e8c440836060d575c59bf90636da0167798d17ebf175a4e4946 | def test_phase_data(self):
'\n FileDependency should add filename in report.\n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
parent.myreport = {'dependencies': []}
dependency.set_parent(parent)
dependency.phase_data()
assert (dependency.myreport == {'filename': 'success', 'name': 'baelfire.dependencies.file.FileDependency'}) | FileDependency should add filename in report. | baelfire/dependencies/tests/test_file.py | test_phase_data | socek/baelfire | 0 | python | def test_phase_data(self):
'\n \n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
parent.myreport = {'dependencies': []}
dependency.set_parent(parent)
dependency.phase_data()
assert (dependency.myreport == {'filename': 'success', 'name': 'baelfire.dependencies.file.FileDependency'}) | def test_phase_data(self):
'\n \n '
dependency = FileDependency('myname')
parent = MagicMock()
parent.paths = {'myname': 'success'}
parent.myreport = {'dependencies': []}
dependency.set_parent(parent)
dependency.phase_data()
assert (dependency.myreport == {'filename': 'success', 'name': 'baelfire.dependencies.file.FileDependency'})<|docstring|>FileDependency should add filename in report.<|endoftext|> |
230e9a429ab7992bf74ea2b4a14e566133af999de027ea5366b5d4ce5e189fe3 | def test_on_output_not_existing(self):
'\n FileChanged should indicate to rebuild if output file does not exists.\n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.output = name
dependency = FileChanged('tmp')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | FileChanged should indicate to rebuild if output file does not exists. | baelfire/dependencies/tests/test_file.py | test_on_output_not_existing | socek/baelfire | 0 | python | def test_on_output_not_existing(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.output = name
dependency = FileChanged('tmp')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | def test_on_output_not_existing(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.output = name
dependency = FileChanged('tmp')
dependency.set_parent(parent)
assert (dependency.should_build() is True)<|docstring|>FileChanged should indicate to rebuild if output file does not exists.<|endoftext|> |
958de3f3d5c545b23ac51acbeed119296ab15a35f1aa9179c627a83a779c49fd | def test_on_source_not_existing(self):
'\n FileChanged should indicate to rebuild if source file does not exists.\n '
name = NamedTemporaryFile(delete=False).name
parent = MagicMock()
parent.output = name
dependency = FileChanged(raw_path=NamedTemporaryFile().name)
dependency.set_parent(parent)
assert (dependency.should_build() is True) | FileChanged should indicate to rebuild if source file does not exists. | baelfire/dependencies/tests/test_file.py | test_on_source_not_existing | socek/baelfire | 0 | python | def test_on_source_not_existing(self):
'\n \n '
name = NamedTemporaryFile(delete=False).name
parent = MagicMock()
parent.output = name
dependency = FileChanged(raw_path=NamedTemporaryFile().name)
dependency.set_parent(parent)
assert (dependency.should_build() is True) | def test_on_source_not_existing(self):
'\n \n '
name = NamedTemporaryFile(delete=False).name
parent = MagicMock()
parent.output = name
dependency = FileChanged(raw_path=NamedTemporaryFile().name)
dependency.set_parent(parent)
assert (dependency.should_build() is True)<|docstring|>FileChanged should indicate to rebuild if source file does not exists.<|endoftext|> |
dd6ed5b4e62d70355af62b5ab2481636b05dd9bec00ebcae7dfec4acb4ad4a55 | def test_on_output_younger(self):
'\n FileChanged should indicate to rebuild if output file is younger then\n the source file.\n '
with NamedTemporaryFile(delete=False) as destination:
destination.close()
sleep(0.01)
with NamedTemporaryFile(delete=False) as source:
source.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | FileChanged should indicate to rebuild if output file is younger then
the source file. | baelfire/dependencies/tests/test_file.py | test_on_output_younger | socek/baelfire | 0 | python | def test_on_output_younger(self):
'\n FileChanged should indicate to rebuild if output file is younger then\n the source file.\n '
with NamedTemporaryFile(delete=False) as destination:
destination.close()
sleep(0.01)
with NamedTemporaryFile(delete=False) as source:
source.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | def test_on_output_younger(self):
'\n FileChanged should indicate to rebuild if output file is younger then\n the source file.\n '
with NamedTemporaryFile(delete=False) as destination:
destination.close()
sleep(0.01)
with NamedTemporaryFile(delete=False) as source:
source.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True)<|docstring|>FileChanged should indicate to rebuild if output file is younger then
the source file.<|endoftext|> |
6ac81a0d72408063f4f95ae3f498bcfc57b9ae2b66676f5dbf5da3466791ac71 | def test_on_output_older(self):
'\n FileChanged should indicate not to rebuild if output file is older then\n the source file.\n '
with NamedTemporaryFile(delete=False) as source:
source.close()
with NamedTemporaryFile(delete=False) as destination:
destination.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | FileChanged should indicate not to rebuild if output file is older then
the source file. | baelfire/dependencies/tests/test_file.py | test_on_output_older | socek/baelfire | 0 | python | def test_on_output_older(self):
'\n FileChanged should indicate not to rebuild if output file is older then\n the source file.\n '
with NamedTemporaryFile(delete=False) as source:
source.close()
with NamedTemporaryFile(delete=False) as destination:
destination.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | def test_on_output_older(self):
'\n FileChanged should indicate not to rebuild if output file is older then\n the source file.\n '
with NamedTemporaryFile(delete=False) as source:
source.close()
with NamedTemporaryFile(delete=False) as destination:
destination.close()
parent = MagicMock()
parent.output = destination.name
parent.paths = {'source': source.name}
dependency = FileChanged('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False)<|docstring|>FileChanged should indicate not to rebuild if output file is older then
the source file.<|endoftext|> |
b2d13d7f57eb7feade50b1fd234332fa15d74ade1c7e98899c25b7f7fcbbbea8 | def test_on_file_not_exists(self):
'\n FileDoesNotExists should indicate to rebuild if file is not existing.\n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | FileDoesNotExists should indicate to rebuild if file is not existing. | baelfire/dependencies/tests/test_file.py | test_on_file_not_exists | socek/baelfire | 0 | python | def test_on_file_not_exists(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | def test_on_file_not_exists(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True)<|docstring|>FileDoesNotExists should indicate to rebuild if file is not existing.<|endoftext|> |
5135f15af3624a3eaa8185c8f6067d631ec4b609b86ca7464d47a2a634a8835e | def test_on_file_exists(self):
'\n FileDoesNotExists should indicate not to rebuild if file exists.\n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | FileDoesNotExists should indicate not to rebuild if file exists. | baelfire/dependencies/tests/test_file.py | test_on_file_exists | socek/baelfire | 0 | python | def test_on_file_exists(self):
'\n \n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | def test_on_file_exists(self):
'\n \n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileDoesNotExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False)<|docstring|>FileDoesNotExists should indicate not to rebuild if file exists.<|endoftext|> |
936cc3af3aa13196a09053c57891945a2e2dd00ad8b335229109d02073bd3cd1 | def test_on_file_not_exists(self):
'\n FileExists should indicate not to rebuild if file is not existing.\n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | FileExists should indicate not to rebuild if file is not existing. | baelfire/dependencies/tests/test_file.py | test_on_file_not_exists | socek/baelfire | 0 | python | def test_on_file_not_exists(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False) | def test_on_file_not_exists(self):
'\n \n '
name = NamedTemporaryFile().name
parent = MagicMock()
parent.paths = {'source': name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is False)<|docstring|>FileExists should indicate not to rebuild if file is not existing.<|endoftext|> |
22a8044c8a5de7f241ce13aaa82e960a423ed6a1e4f3ca937cca997dcbf128d3 | def test_on_file_exists(self):
'\n FileExists should indicate to rebuild if file exists.\n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | FileExists should indicate to rebuild if file exists. | baelfire/dependencies/tests/test_file.py | test_on_file_exists | socek/baelfire | 0 | python | def test_on_file_exists(self):
'\n \n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True) | def test_on_file_exists(self):
'\n \n '
with NamedTemporaryFile(delete=False) as source:
parent = MagicMock()
parent.paths = {'source': source.name}
dependency = FileExists('source')
dependency.set_parent(parent)
assert (dependency.should_build() is True)<|docstring|>FileExists should indicate to rebuild if file exists.<|endoftext|> |
9cbb43064eaddfa6cdf2a8a72b16aedd02b73f22b72ccec9e142029d839328f3 | def update_max_sys_util(self, lc_max_util):
'\n Update quota max and step based on given LC system maximal utilization\n monitored\n lc_max_util - maximal LC workloads utilization monitored\n '
self.quota_max = (lc_max_util * CpuQuota.CPU_QUOTA_PERCENT)
self.quota_step = (self.quota_max / Resource.BUGET_LEV_MAX) | Update quota max and step based on given LC system maximal utilization
monitored
lc_max_util - maximal LC workloads utilization monitored | eris/cpuquota.py | update_max_sys_util | Akiros001/platform-resource-manager | 47 | python | def update_max_sys_util(self, lc_max_util):
'\n Update quota max and step based on given LC system maximal utilization\n monitored\n lc_max_util - maximal LC workloads utilization monitored\n '
self.quota_max = (lc_max_util * CpuQuota.CPU_QUOTA_PERCENT)
self.quota_step = (self.quota_max / Resource.BUGET_LEV_MAX) | def update_max_sys_util(self, lc_max_util):
'\n Update quota max and step based on given LC system maximal utilization\n monitored\n lc_max_util - maximal LC workloads utilization monitored\n '
self.quota_max = (lc_max_util * CpuQuota.CPU_QUOTA_PERCENT)
self.quota_step = (self.quota_max / Resource.BUGET_LEV_MAX)<|docstring|>Update quota max and step based on given LC system maximal utilization
monitored
lc_max_util - maximal LC workloads utilization monitored<|endoftext|> |
5c246ffc21345c037aa512d2f212f042be21d21df5af32561fed640e844a0156 | @staticmethod
def set_share(container, share):
'\n Set CPU share in container\n share - given CPU share value\n '
path = (((CpuQuota.PREFIX + container.parent_path) + container.con_path) + '/cpu.shares')
with open(path, 'w') as shrf:
shrf.write(str(share))
print(((((datetime.now().isoformat(' ') + ' set container ') + container.name) + ' cpu share to ') + str(share))) | Set CPU share in container
share - given CPU share value | eris/cpuquota.py | set_share | Akiros001/platform-resource-manager | 47 | python | @staticmethod
def set_share(container, share):
'\n Set CPU share in container\n share - given CPU share value\n '
path = (((CpuQuota.PREFIX + container.parent_path) + container.con_path) + '/cpu.shares')
with open(path, 'w') as shrf:
shrf.write(str(share))
print(((((datetime.now().isoformat(' ') + ' set container ') + container.name) + ' cpu share to ') + str(share))) | @staticmethod
def set_share(container, share):
'\n Set CPU share in container\n share - given CPU share value\n '
path = (((CpuQuota.PREFIX + container.parent_path) + container.con_path) + '/cpu.shares')
with open(path, 'w') as shrf:
shrf.write(str(share))
print(((((datetime.now().isoformat(' ') + ' set container ') + container.name) + ' cpu share to ') + str(share)))<|docstring|>Set CPU share in container
share - given CPU share value<|endoftext|> |
9ca1334b55d57c94b2432194feb9b07d56cee0197711c7a49330a644b89b51a2 | def detect_margin_exceed(self, lc_utils, be_utils):
'\n Detect if BE workload utilization exceed the safe margin\n lc_utils - utilization of all LC workloads\n be_utils - utilization of all BE workloads\n '
beq = self.cpu_quota
margin = (CpuQuota.CPU_QUOTA_CORE * self.min_margin_ratio)
if self.verbose:
print((datetime.now().isoformat(' ') + ' lcUtils: '), lc_utils, ' beUtils: ', be_utils, ' beq: ', beq, ' margin: ', margin)
exceed = ((lc_utils == 0) or ((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) > self.quota_max))
hold = (((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) + self.quota_step) >= self.quota_max)
return (exceed, hold) | Detect if BE workload utilization exceed the safe margin
lc_utils - utilization of all LC workloads
be_utils - utilization of all BE workloads | eris/cpuquota.py | detect_margin_exceed | Akiros001/platform-resource-manager | 47 | python | def detect_margin_exceed(self, lc_utils, be_utils):
'\n Detect if BE workload utilization exceed the safe margin\n lc_utils - utilization of all LC workloads\n be_utils - utilization of all BE workloads\n '
beq = self.cpu_quota
margin = (CpuQuota.CPU_QUOTA_CORE * self.min_margin_ratio)
if self.verbose:
print((datetime.now().isoformat(' ') + ' lcUtils: '), lc_utils, ' beUtils: ', be_utils, ' beq: ', beq, ' margin: ', margin)
exceed = ((lc_utils == 0) or ((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) > self.quota_max))
hold = (((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) + self.quota_step) >= self.quota_max)
return (exceed, hold) | def detect_margin_exceed(self, lc_utils, be_utils):
'\n Detect if BE workload utilization exceed the safe margin\n lc_utils - utilization of all LC workloads\n be_utils - utilization of all BE workloads\n '
beq = self.cpu_quota
margin = (CpuQuota.CPU_QUOTA_CORE * self.min_margin_ratio)
if self.verbose:
print((datetime.now().isoformat(' ') + ' lcUtils: '), lc_utils, ' beUtils: ', be_utils, ' beq: ', beq, ' margin: ', margin)
exceed = ((lc_utils == 0) or ((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) > self.quota_max))
hold = (((((lc_utils + be_utils) * CpuQuota.CPU_QUOTA_PERCENT) + margin) + self.quota_step) >= self.quota_max)
return (exceed, hold)<|docstring|>Detect if BE workload utilization exceed the safe margin
lc_utils - utilization of all LC workloads
be_utils - utilization of all BE workloads<|endoftext|> |
31676ea29748ea258a2e3e78e404ea77dabfe31f50d17f7064e2d8b8e3f3fb6d | def build_position_encoding(position_encoding_type, out_channels=None, project_pos_dim=(- 1), trainable_position_encoding_kwargs=None, fourier_position_encoding_kwargs=None):
'\n Builds the position encoding.\n\n Args:\n\n - out_channels: refers to the number of channels of the position encodings.\n - project_pos_dim: if specified, will project the position encodings to this dimension.\n\n '
if (position_encoding_type == 'trainable'):
if (not trainable_position_encoding_kwargs):
raise ValueError('Make sure to pass trainable_position_encoding_kwargs')
output_pos_enc = PerceiverTrainablePositionEncoding(**trainable_position_encoding_kwargs)
elif (position_encoding_type == 'fourier'):
if (not fourier_position_encoding_kwargs):
raise ValueError('Make sure to pass fourier_position_encoding_kwargs')
output_pos_enc = PerceiverFourierPositionEncoding(**fourier_position_encoding_kwargs)
else:
raise ValueError(f'Unknown position encoding type: {position_encoding_type}.')
positions_projection = (nn.Linear(out_channels, project_pos_dim) if (project_pos_dim > 0) else nn.Identity())
return (output_pos_enc, positions_projection) | Builds the position encoding.
Args:
- out_channels: refers to the number of channels of the position encodings.
- project_pos_dim: if specified, will project the position encodings to this dimension. | src/transformers/models/perceiver/modeling_perceiver.py | build_position_encoding | mingboiz/transformers | 8,028 | python | def build_position_encoding(position_encoding_type, out_channels=None, project_pos_dim=(- 1), trainable_position_encoding_kwargs=None, fourier_position_encoding_kwargs=None):
'\n Builds the position encoding.\n\n Args:\n\n - out_channels: refers to the number of channels of the position encodings.\n - project_pos_dim: if specified, will project the position encodings to this dimension.\n\n '
if (position_encoding_type == 'trainable'):
if (not trainable_position_encoding_kwargs):
raise ValueError('Make sure to pass trainable_position_encoding_kwargs')
output_pos_enc = PerceiverTrainablePositionEncoding(**trainable_position_encoding_kwargs)
elif (position_encoding_type == 'fourier'):
if (not fourier_position_encoding_kwargs):
raise ValueError('Make sure to pass fourier_position_encoding_kwargs')
output_pos_enc = PerceiverFourierPositionEncoding(**fourier_position_encoding_kwargs)
else:
raise ValueError(f'Unknown position encoding type: {position_encoding_type}.')
positions_projection = (nn.Linear(out_channels, project_pos_dim) if (project_pos_dim > 0) else nn.Identity())
return (output_pos_enc, positions_projection) | def build_position_encoding(position_encoding_type, out_channels=None, project_pos_dim=(- 1), trainable_position_encoding_kwargs=None, fourier_position_encoding_kwargs=None):
'\n Builds the position encoding.\n\n Args:\n\n - out_channels: refers to the number of channels of the position encodings.\n - project_pos_dim: if specified, will project the position encodings to this dimension.\n\n '
if (position_encoding_type == 'trainable'):
if (not trainable_position_encoding_kwargs):
raise ValueError('Make sure to pass trainable_position_encoding_kwargs')
output_pos_enc = PerceiverTrainablePositionEncoding(**trainable_position_encoding_kwargs)
elif (position_encoding_type == 'fourier'):
if (not fourier_position_encoding_kwargs):
raise ValueError('Make sure to pass fourier_position_encoding_kwargs')
output_pos_enc = PerceiverFourierPositionEncoding(**fourier_position_encoding_kwargs)
else:
raise ValueError(f'Unknown position encoding type: {position_encoding_type}.')
positions_projection = (nn.Linear(out_channels, project_pos_dim) if (project_pos_dim > 0) else nn.Identity())
return (output_pos_enc, positions_projection)<|docstring|>Builds the position encoding.
Args:
- out_channels: refers to the number of channels of the position encodings.
- project_pos_dim: if specified, will project the position encodings to this dimension.<|endoftext|> |
e145d4c4077f061080b30b0c87e190d75daaa19f9cc307bb870a38a13f6129ad | def restructure(modality_sizes: ModalitySizeType, inputs: torch.Tensor) -> Mapping[(str, torch.Tensor)]:
'\n Partitions a [B, N, C] tensor into tensors for each modality.\n\n Args:\n modality_sizes\n dict specifying the size of the modality\n inputs:\n input tensor\n\n Returns:\n dict mapping name of modality to its associated tensor.\n '
outputs = {}
index = 0
for modality in sorted(modality_sizes.keys()):
size = modality_sizes[modality]
inp = inputs[(:, index:(index + size))]
index += size
outputs[modality] = inp
return outputs | Partitions a [B, N, C] tensor into tensors for each modality.
Args:
modality_sizes
dict specifying the size of the modality
inputs:
input tensor
Returns:
dict mapping name of modality to its associated tensor. | src/transformers/models/perceiver/modeling_perceiver.py | restructure | mingboiz/transformers | 8,028 | python | def restructure(modality_sizes: ModalitySizeType, inputs: torch.Tensor) -> Mapping[(str, torch.Tensor)]:
'\n Partitions a [B, N, C] tensor into tensors for each modality.\n\n Args:\n modality_sizes\n dict specifying the size of the modality\n inputs:\n input tensor\n\n Returns:\n dict mapping name of modality to its associated tensor.\n '
outputs = {}
index = 0
for modality in sorted(modality_sizes.keys()):
size = modality_sizes[modality]
inp = inputs[(:, index:(index + size))]
index += size
outputs[modality] = inp
return outputs | def restructure(modality_sizes: ModalitySizeType, inputs: torch.Tensor) -> Mapping[(str, torch.Tensor)]:
'\n Partitions a [B, N, C] tensor into tensors for each modality.\n\n Args:\n modality_sizes\n dict specifying the size of the modality\n inputs:\n input tensor\n\n Returns:\n dict mapping name of modality to its associated tensor.\n '
outputs = {}
index = 0
for modality in sorted(modality_sizes.keys()):
size = modality_sizes[modality]
inp = inputs[(:, index:(index + size))]
index += size
outputs[modality] = inp
return outputs<|docstring|>Partitions a [B, N, C] tensor into tensors for each modality.
Args:
modality_sizes
dict specifying the size of the modality
inputs:
input tensor
Returns:
dict mapping name of modality to its associated tensor.<|endoftext|> |
0ddbf4ea51e73b51781818fd776ae5edb78983bd3d8fa5068d956fba583e7be1 | def space_to_depth(frames: torch.Tensor, temporal_block_size: int=1, spatial_block_size: int=1) -> torch.Tensor:
'\n Space to depth transform. Rearranges blocks of spatial data, into depth.\n\n This function assumes the channels to be first, but will place the channels last after transformation.\n\n Based on https://discuss.pytorch.org/t/is-there-any-layer-like-tensorflows-space-to-depth-function/3487/15.\n '
if (len(frames.shape) == 4):
(batch_size, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 2, 4, 3, 5, 1).contiguous()
frames = frames.view(batch_size, (height // spatial_block_size), (width // spatial_block_size), ((spatial_block_size ** 2) * num_channels))
return frames
elif (len(frames.shape) == 5):
(batch_size, time, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, (time // temporal_block_size), temporal_block_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
frames = frames.view(batch_size, (time // temporal_block_size), (height // spatial_block_size), (width // spatial_block_size), ((temporal_block_size * (spatial_block_size ** 2)) * num_channels))
return frames
else:
raise ValueError('Frames should be of rank 4 (batch, channels, height, width) or rank 5 (batch, time, channels, height, width)') | Space to depth transform. Rearranges blocks of spatial data, into depth.
This function assumes the channels to be first, but will place the channels last after transformation.
Based on https://discuss.pytorch.org/t/is-there-any-layer-like-tensorflows-space-to-depth-function/3487/15. | src/transformers/models/perceiver/modeling_perceiver.py | space_to_depth | mingboiz/transformers | 8,028 | python | def space_to_depth(frames: torch.Tensor, temporal_block_size: int=1, spatial_block_size: int=1) -> torch.Tensor:
'\n Space to depth transform. Rearranges blocks of spatial data, into depth.\n\n This function assumes the channels to be first, but will place the channels last after transformation.\n\n Based on https://discuss.pytorch.org/t/is-there-any-layer-like-tensorflows-space-to-depth-function/3487/15.\n '
if (len(frames.shape) == 4):
(batch_size, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 2, 4, 3, 5, 1).contiguous()
frames = frames.view(batch_size, (height // spatial_block_size), (width // spatial_block_size), ((spatial_block_size ** 2) * num_channels))
return frames
elif (len(frames.shape) == 5):
(batch_size, time, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, (time // temporal_block_size), temporal_block_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
frames = frames.view(batch_size, (time // temporal_block_size), (height // spatial_block_size), (width // spatial_block_size), ((temporal_block_size * (spatial_block_size ** 2)) * num_channels))
return frames
else:
raise ValueError('Frames should be of rank 4 (batch, channels, height, width) or rank 5 (batch, time, channels, height, width)') | def space_to_depth(frames: torch.Tensor, temporal_block_size: int=1, spatial_block_size: int=1) -> torch.Tensor:
'\n Space to depth transform. Rearranges blocks of spatial data, into depth.\n\n This function assumes the channels to be first, but will place the channels last after transformation.\n\n Based on https://discuss.pytorch.org/t/is-there-any-layer-like-tensorflows-space-to-depth-function/3487/15.\n '
if (len(frames.shape) == 4):
(batch_size, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 2, 4, 3, 5, 1).contiguous()
frames = frames.view(batch_size, (height // spatial_block_size), (width // spatial_block_size), ((spatial_block_size ** 2) * num_channels))
return frames
elif (len(frames.shape) == 5):
(batch_size, time, num_channels, height, width) = frames.shape
frames = frames.view(batch_size, (time // temporal_block_size), temporal_block_size, num_channels, (height // spatial_block_size), spatial_block_size, (width // spatial_block_size), spatial_block_size)
frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
frames = frames.view(batch_size, (time // temporal_block_size), (height // spatial_block_size), (width // spatial_block_size), ((temporal_block_size * (spatial_block_size ** 2)) * num_channels))
return frames
else:
raise ValueError('Frames should be of rank 4 (batch, channels, height, width) or rank 5 (batch, time, channels, height, width)')<|docstring|>Space to depth transform. Rearranges blocks of spatial data, into depth.
This function assumes the channels to be first, but will place the channels last after transformation.
Based on https://discuss.pytorch.org/t/is-there-any-layer-like-tensorflows-space-to-depth-function/3487/15.<|endoftext|> |
394a7141d6b5d9462ff525c93106542736a2fea88c13af734fdbe2ef0cd626ed | def generate_fourier_features(pos, num_bands, max_resolution=(224, 224), concat_pos=True, sine_only=False):
'\n Generate a Fourier frequency position encoding with linear spacing.\n\n Args:\n pos (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`):\n The Tensor containing the position of n points in d dimensional space.\n num_bands (`int`):\n The number of frequency bands (K) to use.\n max_resolution (`Tuple[int]`, *optional*, defaults to (224, 224)):\n The maximum resolution (i.e. the number of pixels per dim). A tuple representing resolution for each dimension.\n concat_pos (`bool`, *optional*, defaults to `True`):\n Whether to concatenate the input position encoding to the Fourier features.\n sine_only (`bool`, *optional*, defaults to `False`):\n Whether to use a single phase (sin) or two (sin/cos) for each frequency band.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, sequence_length, n_channels)`: The Fourier position embeddings. If\n `concat_pos` is `True` and `sine_only` is `False`, output dimensions are ordered as: [dim_1, dim_2, ..., dim_d,\n sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ..., sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d), cos(pi*f_1*dim_1),\n ..., cos(pi*f_K*dim_1), ..., cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)], where dim_i is pos[:, i] and f_k is the\n kth frequency band.\n '
batch_size = pos.shape[0]
min_freq = 1.0
freq_bands = torch.stack([torch.linspace(start=min_freq, end=(res / 2), steps=num_bands) for res in max_resolution], dim=0)
per_pos_features = (pos[(0, :, :)][(:, :, None)] * freq_bands[(None, :, :)])
per_pos_features = torch.reshape(per_pos_features, [(- 1), np.prod(per_pos_features.shape[1:])])
if sine_only:
per_pos_features = torch.sin((np.pi * per_pos_features))
else:
per_pos_features = torch.cat([torch.sin((np.pi * per_pos_features)), torch.cos((np.pi * per_pos_features))], dim=(- 1))
if concat_pos:
per_pos_features = torch.cat([pos, per_pos_features.expand(batch_size, (- 1), (- 1))], dim=(- 1))
return per_pos_features | Generate a Fourier frequency position encoding with linear spacing.
Args:
pos (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`):
The Tensor containing the position of n points in d dimensional space.
num_bands (`int`):
The number of frequency bands (K) to use.
max_resolution (`Tuple[int]`, *optional*, defaults to (224, 224)):
The maximum resolution (i.e. the number of pixels per dim). A tuple representing resolution for each dimension.
concat_pos (`bool`, *optional*, defaults to `True`):
Whether to concatenate the input position encoding to the Fourier features.
sine_only (`bool`, *optional*, defaults to `False`):
Whether to use a single phase (sin) or two (sin/cos) for each frequency band.
Returns:
`torch.FloatTensor` of shape `(batch_size, sequence_length, n_channels)`: The Fourier position embeddings. If
`concat_pos` is `True` and `sine_only` is `False`, output dimensions are ordered as: [dim_1, dim_2, ..., dim_d,
sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ..., sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d), cos(pi*f_1*dim_1),
..., cos(pi*f_K*dim_1), ..., cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)], where dim_i is pos[:, i] and f_k is the
kth frequency band. | src/transformers/models/perceiver/modeling_perceiver.py | generate_fourier_features | mingboiz/transformers | 8,028 | python | def generate_fourier_features(pos, num_bands, max_resolution=(224, 224), concat_pos=True, sine_only=False):
'\n Generate a Fourier frequency position encoding with linear spacing.\n\n Args:\n pos (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`):\n The Tensor containing the position of n points in d dimensional space.\n num_bands (`int`):\n The number of frequency bands (K) to use.\n max_resolution (`Tuple[int]`, *optional*, defaults to (224, 224)):\n The maximum resolution (i.e. the number of pixels per dim). A tuple representing resolution for each dimension.\n concat_pos (`bool`, *optional*, defaults to `True`):\n Whether to concatenate the input position encoding to the Fourier features.\n sine_only (`bool`, *optional*, defaults to `False`):\n Whether to use a single phase (sin) or two (sin/cos) for each frequency band.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, sequence_length, n_channels)`: The Fourier position embeddings. If\n `concat_pos` is `True` and `sine_only` is `False`, output dimensions are ordered as: [dim_1, dim_2, ..., dim_d,\n sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ..., sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d), cos(pi*f_1*dim_1),\n ..., cos(pi*f_K*dim_1), ..., cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)], where dim_i is pos[:, i] and f_k is the\n kth frequency band.\n '
batch_size = pos.shape[0]
min_freq = 1.0
freq_bands = torch.stack([torch.linspace(start=min_freq, end=(res / 2), steps=num_bands) for res in max_resolution], dim=0)
per_pos_features = (pos[(0, :, :)][(:, :, None)] * freq_bands[(None, :, :)])
per_pos_features = torch.reshape(per_pos_features, [(- 1), np.prod(per_pos_features.shape[1:])])
if sine_only:
per_pos_features = torch.sin((np.pi * per_pos_features))
else:
per_pos_features = torch.cat([torch.sin((np.pi * per_pos_features)), torch.cos((np.pi * per_pos_features))], dim=(- 1))
if concat_pos:
per_pos_features = torch.cat([pos, per_pos_features.expand(batch_size, (- 1), (- 1))], dim=(- 1))
return per_pos_features | def generate_fourier_features(pos, num_bands, max_resolution=(224, 224), concat_pos=True, sine_only=False):
'\n Generate a Fourier frequency position encoding with linear spacing.\n\n Args:\n pos (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`):\n The Tensor containing the position of n points in d dimensional space.\n num_bands (`int`):\n The number of frequency bands (K) to use.\n max_resolution (`Tuple[int]`, *optional*, defaults to (224, 224)):\n The maximum resolution (i.e. the number of pixels per dim). A tuple representing resolution for each dimension.\n concat_pos (`bool`, *optional*, defaults to `True`):\n Whether to concatenate the input position encoding to the Fourier features.\n sine_only (`bool`, *optional*, defaults to `False`):\n Whether to use a single phase (sin) or two (sin/cos) for each frequency band.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, sequence_length, n_channels)`: The Fourier position embeddings. If\n `concat_pos` is `True` and `sine_only` is `False`, output dimensions are ordered as: [dim_1, dim_2, ..., dim_d,\n sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ..., sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d), cos(pi*f_1*dim_1),\n ..., cos(pi*f_K*dim_1), ..., cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)], where dim_i is pos[:, i] and f_k is the\n kth frequency band.\n '
batch_size = pos.shape[0]
min_freq = 1.0
freq_bands = torch.stack([torch.linspace(start=min_freq, end=(res / 2), steps=num_bands) for res in max_resolution], dim=0)
per_pos_features = (pos[(0, :, :)][(:, :, None)] * freq_bands[(None, :, :)])
per_pos_features = torch.reshape(per_pos_features, [(- 1), np.prod(per_pos_features.shape[1:])])
if sine_only:
per_pos_features = torch.sin((np.pi * per_pos_features))
else:
per_pos_features = torch.cat([torch.sin((np.pi * per_pos_features)), torch.cos((np.pi * per_pos_features))], dim=(- 1))
if concat_pos:
per_pos_features = torch.cat([pos, per_pos_features.expand(batch_size, (- 1), (- 1))], dim=(- 1))
return per_pos_features<|docstring|>Generate a Fourier frequency position encoding with linear spacing.
Args:
pos (`torch.LongTensor` of shape `(batch_size, sequence_length, dim)`):
The Tensor containing the position of n points in d dimensional space.
num_bands (`int`):
The number of frequency bands (K) to use.
max_resolution (`Tuple[int]`, *optional*, defaults to (224, 224)):
The maximum resolution (i.e. the number of pixels per dim). A tuple representing resolution for each dimension.
concat_pos (`bool`, *optional*, defaults to `True`):
Whether to concatenate the input position encoding to the Fourier features.
sine_only (`bool`, *optional*, defaults to `False`):
Whether to use a single phase (sin) or two (sin/cos) for each frequency band.
Returns:
`torch.FloatTensor` of shape `(batch_size, sequence_length, n_channels)`: The Fourier position embeddings. If
`concat_pos` is `True` and `sine_only` is `False`, output dimensions are ordered as: [dim_1, dim_2, ..., dim_d,
sin(pi*f_1*dim_1), ..., sin(pi*f_K*dim_1), ..., sin(pi*f_1*dim_d), ..., sin(pi*f_K*dim_d), cos(pi*f_1*dim_1),
..., cos(pi*f_K*dim_1), ..., cos(pi*f_1*dim_d), ..., cos(pi*f_K*dim_d)], where dim_i is pos[:, i] and f_k is the
kth frequency band.<|endoftext|> |
465586bf174602eb0c964800c6b37e1bb7ec45a656f4815ee0ad1fbc1ff6101a | def build_linear_positions(index_dims, output_range=((- 1.0), 1.0)):
'\n Generate an array of position indices for an N-D input array.\n\n Args:\n index_dims (`List[int]`):\n The shape of the index dimensions of the input array.\n output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):\n The min and max values taken by each input index dimension.\n\n Returns:\n `torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`.\n '
def _linspace(n_xels_per_dim):
return torch.linspace(start=output_range[0], end=output_range[1], steps=n_xels_per_dim, dtype=torch.float32)
dim_ranges = [_linspace(n_xels_per_dim) for n_xels_per_dim in index_dims]
array_index_grid = torch.meshgrid(*dim_ranges)
return torch.stack(array_index_grid, dim=(- 1)) | Generate an array of position indices for an N-D input array.
Args:
index_dims (`List[int]`):
The shape of the index dimensions of the input array.
output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):
The min and max values taken by each input index dimension.
Returns:
`torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`. | src/transformers/models/perceiver/modeling_perceiver.py | build_linear_positions | mingboiz/transformers | 8,028 | python | def build_linear_positions(index_dims, output_range=((- 1.0), 1.0)):
'\n Generate an array of position indices for an N-D input array.\n\n Args:\n index_dims (`List[int]`):\n The shape of the index dimensions of the input array.\n output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):\n The min and max values taken by each input index dimension.\n\n Returns:\n `torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`.\n '
def _linspace(n_xels_per_dim):
return torch.linspace(start=output_range[0], end=output_range[1], steps=n_xels_per_dim, dtype=torch.float32)
dim_ranges = [_linspace(n_xels_per_dim) for n_xels_per_dim in index_dims]
array_index_grid = torch.meshgrid(*dim_ranges)
return torch.stack(array_index_grid, dim=(- 1)) | def build_linear_positions(index_dims, output_range=((- 1.0), 1.0)):
'\n Generate an array of position indices for an N-D input array.\n\n Args:\n index_dims (`List[int]`):\n The shape of the index dimensions of the input array.\n output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):\n The min and max values taken by each input index dimension.\n\n Returns:\n `torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`.\n '
def _linspace(n_xels_per_dim):
return torch.linspace(start=output_range[0], end=output_range[1], steps=n_xels_per_dim, dtype=torch.float32)
dim_ranges = [_linspace(n_xels_per_dim) for n_xels_per_dim in index_dims]
array_index_grid = torch.meshgrid(*dim_ranges)
return torch.stack(array_index_grid, dim=(- 1))<|docstring|>Generate an array of position indices for an N-D input array.
Args:
index_dims (`List[int]`):
The shape of the index dimensions of the input array.
output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):
The min and max values taken by each input index dimension.
Returns:
`torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`.<|endoftext|> |
65382ffd23a60b444baefbdfb46c4e094d5958ef03454b47bebdb744950cd62a | def _check_or_build_spatial_positions(pos, index_dims, batch_size):
'\n Checks or builds spatial position features (x, y, ...).\n\n Args:\n pos (`torch.FloatTensor`):\n None, or an array of position features. If None, position features are built. Otherwise, their size is checked.\n index_dims (`List[int]`):\n An iterable giving the spatial/index size of the data to be featurized.\n batch_size (`int`):\n The batch size of the data to be featurized.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, prod(index_dims))` an array of position features.\n '
if (pos is None):
pos = build_linear_positions(index_dims)
pos = torch.broadcast_to(pos[None], ((batch_size,) + pos.shape))
pos = torch.reshape(pos, [batch_size, np.prod(index_dims), (- 1)])
elif (pos.shape[(- 1)] != len(index_dims)):
raise ValueError('Spatial features have the wrong number of dimensions.')
return pos | Checks or builds spatial position features (x, y, ...).
Args:
pos (`torch.FloatTensor`):
None, or an array of position features. If None, position features are built. Otherwise, their size is checked.
index_dims (`List[int]`):
An iterable giving the spatial/index size of the data to be featurized.
batch_size (`int`):
The batch size of the data to be featurized.
Returns:
`torch.FloatTensor` of shape `(batch_size, prod(index_dims))` an array of position features. | src/transformers/models/perceiver/modeling_perceiver.py | _check_or_build_spatial_positions | mingboiz/transformers | 8,028 | python | def _check_or_build_spatial_positions(pos, index_dims, batch_size):
'\n Checks or builds spatial position features (x, y, ...).\n\n Args:\n pos (`torch.FloatTensor`):\n None, or an array of position features. If None, position features are built. Otherwise, their size is checked.\n index_dims (`List[int]`):\n An iterable giving the spatial/index size of the data to be featurized.\n batch_size (`int`):\n The batch size of the data to be featurized.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, prod(index_dims))` an array of position features.\n '
if (pos is None):
pos = build_linear_positions(index_dims)
pos = torch.broadcast_to(pos[None], ((batch_size,) + pos.shape))
pos = torch.reshape(pos, [batch_size, np.prod(index_dims), (- 1)])
elif (pos.shape[(- 1)] != len(index_dims)):
raise ValueError('Spatial features have the wrong number of dimensions.')
return pos | def _check_or_build_spatial_positions(pos, index_dims, batch_size):
'\n Checks or builds spatial position features (x, y, ...).\n\n Args:\n pos (`torch.FloatTensor`):\n None, or an array of position features. If None, position features are built. Otherwise, their size is checked.\n index_dims (`List[int]`):\n An iterable giving the spatial/index size of the data to be featurized.\n batch_size (`int`):\n The batch size of the data to be featurized.\n\n Returns:\n `torch.FloatTensor` of shape `(batch_size, prod(index_dims))` an array of position features.\n '
if (pos is None):
pos = build_linear_positions(index_dims)
pos = torch.broadcast_to(pos[None], ((batch_size,) + pos.shape))
pos = torch.reshape(pos, [batch_size, np.prod(index_dims), (- 1)])
elif (pos.shape[(- 1)] != len(index_dims)):
raise ValueError('Spatial features have the wrong number of dimensions.')
return pos<|docstring|>Checks or builds spatial position features (x, y, ...).
Args:
pos (`torch.FloatTensor`):
None, or an array of position features. If None, position features are built. Otherwise, their size is checked.
index_dims (`List[int]`):
An iterable giving the spatial/index size of the data to be featurized.
batch_size (`int`):
The batch size of the data to be featurized.
Returns:
`torch.FloatTensor` of shape `(batch_size, prod(index_dims))` an array of position features.<|endoftext|> |
90a1206ceecd3ac74ff2fdeb94f211ded6c3f06ee3d6956c05e71cdb0e71804a | def _init_weights(self, module):
'Initialize the weights'
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.bias is not None):
module.bias.data.zero_()
elif hasattr(module, 'latents'):
module.latents.data.normal_(mean=0.0, std=self.config.initializer_range)
elif (hasattr(module, 'position_embeddings') and isinstance(module, PerceiverTrainablePositionEncoding)):
module.position_embeddings.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.ParameterDict):
for modality in module.keys():
module[modality].data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.padding_idx is not None):
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | Initialize the weights | src/transformers/models/perceiver/modeling_perceiver.py | _init_weights | mingboiz/transformers | 8,028 | python | def _init_weights(self, module):
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.bias is not None):
module.bias.data.zero_()
elif hasattr(module, 'latents'):
module.latents.data.normal_(mean=0.0, std=self.config.initializer_range)
elif (hasattr(module, 'position_embeddings') and isinstance(module, PerceiverTrainablePositionEncoding)):
module.position_embeddings.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.ParameterDict):
for modality in module.keys():
module[modality].data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.padding_idx is not None):
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | def _init_weights(self, module):
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.bias is not None):
module.bias.data.zero_()
elif hasattr(module, 'latents'):
module.latents.data.normal_(mean=0.0, std=self.config.initializer_range)
elif (hasattr(module, 'position_embeddings') and isinstance(module, PerceiverTrainablePositionEncoding)):
module.position_embeddings.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.ParameterDict):
for modality in module.keys():
module[modality].data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if (module.padding_idx is not None):
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)<|docstring|>Initialize the weights<|endoftext|> |
f89291a05d0ecb1cb342b4cc82c1c9c1a98b653bd6855f18a09086aca896924e | def _prune_heads(self, heads_to_prune):
'\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n '
for (layer, heads) in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads) | Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel | src/transformers/models/perceiver/modeling_perceiver.py | _prune_heads | mingboiz/transformers | 8,028 | python | def _prune_heads(self, heads_to_prune):
'\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n '
for (layer, heads) in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads) | def _prune_heads(self, heads_to_prune):
'\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n '
for (layer, heads) in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)<|docstring|>Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel<|endoftext|> |
7ea7deab2574262a1b94dcddfc3a1a8da90b56bd846302893d54c3f7b3669c13 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('(batch_size, sequence_length)'))
@replace_return_docstrings(output_type=PerceiverModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: torch.FloatTensor, attention_mask: Optional[torch.FloatTensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.FloatTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverModelOutput)]:
'\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverFeatureExtractor, PerceiverModel\n >>> from transformers.models.perceiver.modeling_perceiver import (\n ... PerceiverTextPreprocessor,\n ... PerceiverImagePreprocessor,\n ... PerceiverClassificationDecoder,\n ... )\n >>> import torch\n >>> import requests\n >>> from PIL import Image\n\n >>> # EXAMPLE 1: using the Perceiver to classify texts\n >>> # - we define a TextPreprocessor, which can be used to embed tokens\n >>> # - we define a ClassificationDecoder, which can be used to decode the\n >>> # final hidden states of the latents to classification logits\n >>> # using trainable position embeddings\n >>> config = PerceiverConfig()\n >>> preprocessor = PerceiverTextPreprocessor(config)\n >>> decoder = PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... )\n >>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)\n\n >>> # you can then do a forward pass as follows:\n >>> tokenizer = PerceiverTokenizer()\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n\n >>> # EXAMPLE 2: using the Perceiver to classify images\n >>> # - we define an ImagePreprocessor, which can be used to embed images\n >>> preprocessor = PerceiverImagePreprocessor(\n ... config,\n ... prep_type="conv1x1",\n ... spatial_downsample=1,\n ... out_channels=256,\n ... position_encoding_type="trainable",\n ... concat_or_add_pos="concat",\n ... project_pos_dim=256,\n ... trainable_position_encoding_kwargs=dict(\n ... num_channels=256,\n ... index_dims=config.image_size**2,\n ... ),\n ... )\n\n >>> model = PerceiverModel(\n ... config,\n ... input_preprocessor=preprocessor,\n ... decoder=PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... ),\n ... )\n\n >>> # you can then do a forward pass as follows:\n >>> feature_extractor = PerceiverFeatureExtractor()\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> inputs = feature_extractor(image, return_tensors="pt").pixel_values\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n ```'
output_attentions = (output_attentions if (output_attentions is not None) else self.config.output_attentions)
output_hidden_states = (output_hidden_states if (output_hidden_states is not None) else self.config.output_hidden_states)
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
if (self.input_preprocessor is not None):
(inputs, modality_sizes, inputs_without_pos) = self.input_preprocessor(inputs)
else:
modality_sizes = None
inputs_without_pos = None
if (inputs.size()[(- 1)] != self.config.d_model):
raise ValueError(f"Last dimension of the inputs: {inputs.size()[(- 1)]} doesn't correspond to config.d_model: {self.config.d_model}. Make sure to set config.d_model appropriately.")
(batch_size, seq_length, _) = inputs.size()
device = inputs.device
if (attention_mask is None):
attention_mask = torch.ones((batch_size, seq_length), device=device)
extended_attention_mask = self.invert_attention_mask(attention_mask)
head_mask = self.get_head_mask(head_mask, (self.config.num_blocks * self.config.num_self_attends_per_block))
embedding_output = self.embeddings(batch_size=batch_size)
encoder_outputs = self.encoder(embedding_output, attention_mask=None, head_mask=head_mask, inputs=inputs, inputs_mask=extended_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
sequence_output = encoder_outputs[0]
logits = None
if self.decoder:
if (subsampled_output_points is not None):
output_modality_sizes = {'audio': subsampled_output_points['audio'].shape[0], 'image': subsampled_output_points['image'].shape[0], 'label': 1}
else:
output_modality_sizes = None
decoder_query = self.decoder.decoder_query(inputs, modality_sizes, inputs_without_pos, subsampled_points=subsampled_output_points)
decoder_outputs = self.decoder(decoder_query, z=sequence_output, query_mask=extended_attention_mask, output_attentions=output_attentions)
logits = decoder_outputs.logits
if (output_attentions and (decoder_outputs.cross_attentions is not None)):
if return_dict:
encoder_outputs.cross_attentions = (encoder_outputs.cross_attentions + decoder_outputs.cross_attentions)
else:
encoder_outputs = (encoder_outputs + decoder_outputs.cross_attentions)
if self.output_postprocessor:
logits = self.output_postprocessor(logits, modality_sizes=output_modality_sizes)
if (not return_dict):
if (logits is not None):
return ((logits, sequence_output) + encoder_outputs[1:])
else:
return ((sequence_output,) + encoder_outputs[1:])
return PerceiverModelOutput(logits=logits, last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions) | Returns:
Examples:
```python
>>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverFeatureExtractor, PerceiverModel
>>> from transformers.models.perceiver.modeling_perceiver import (
... PerceiverTextPreprocessor,
... PerceiverImagePreprocessor,
... PerceiverClassificationDecoder,
... )
>>> import torch
>>> import requests
>>> from PIL import Image
>>> # EXAMPLE 1: using the Perceiver to classify texts
>>> # - we define a TextPreprocessor, which can be used to embed tokens
>>> # - we define a ClassificationDecoder, which can be used to decode the
>>> # final hidden states of the latents to classification logits
>>> # using trainable position embeddings
>>> config = PerceiverConfig()
>>> preprocessor = PerceiverTextPreprocessor(config)
>>> decoder = PerceiverClassificationDecoder(
... config,
... num_channels=config.d_latents,
... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
... use_query_residual=True,
... )
>>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)
>>> # you can then do a forward pass as follows:
>>> tokenizer = PerceiverTokenizer()
>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
>>> with torch.no_grad():
... outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # to train, one can train the model using standard cross-entropy:
>>> criterion = torch.nn.CrossEntropyLoss()
>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)
>>> # EXAMPLE 2: using the Perceiver to classify images
>>> # - we define an ImagePreprocessor, which can be used to embed images
>>> preprocessor = PerceiverImagePreprocessor(
... config,
... prep_type="conv1x1",
... spatial_downsample=1,
... out_channels=256,
... position_encoding_type="trainable",
... concat_or_add_pos="concat",
... project_pos_dim=256,
... trainable_position_encoding_kwargs=dict(
... num_channels=256,
... index_dims=config.image_size**2,
... ),
... )
>>> model = PerceiverModel(
... config,
... input_preprocessor=preprocessor,
... decoder=PerceiverClassificationDecoder(
... config,
... num_channels=config.d_latents,
... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
... use_query_residual=True,
... ),
... )
>>> # you can then do a forward pass as follows:
>>> feature_extractor = PerceiverFeatureExtractor()
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = feature_extractor(image, return_tensors="pt").pixel_values
>>> with torch.no_grad():
... outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # to train, one can train the model using standard cross-entropy:
>>> criterion = torch.nn.CrossEntropyLoss()
>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('(batch_size, sequence_length)'))
@replace_return_docstrings(output_type=PerceiverModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: torch.FloatTensor, attention_mask: Optional[torch.FloatTensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.FloatTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverModelOutput)]:
'\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverFeatureExtractor, PerceiverModel\n >>> from transformers.models.perceiver.modeling_perceiver import (\n ... PerceiverTextPreprocessor,\n ... PerceiverImagePreprocessor,\n ... PerceiverClassificationDecoder,\n ... )\n >>> import torch\n >>> import requests\n >>> from PIL import Image\n\n >>> # EXAMPLE 1: using the Perceiver to classify texts\n >>> # - we define a TextPreprocessor, which can be used to embed tokens\n >>> # - we define a ClassificationDecoder, which can be used to decode the\n >>> # final hidden states of the latents to classification logits\n >>> # using trainable position embeddings\n >>> config = PerceiverConfig()\n >>> preprocessor = PerceiverTextPreprocessor(config)\n >>> decoder = PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... )\n >>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)\n\n >>> # you can then do a forward pass as follows:\n >>> tokenizer = PerceiverTokenizer()\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n\n >>> # EXAMPLE 2: using the Perceiver to classify images\n >>> # - we define an ImagePreprocessor, which can be used to embed images\n >>> preprocessor = PerceiverImagePreprocessor(\n ... config,\n ... prep_type="conv1x1",\n ... spatial_downsample=1,\n ... out_channels=256,\n ... position_encoding_type="trainable",\n ... concat_or_add_pos="concat",\n ... project_pos_dim=256,\n ... trainable_position_encoding_kwargs=dict(\n ... num_channels=256,\n ... index_dims=config.image_size**2,\n ... ),\n ... )\n\n >>> model = PerceiverModel(\n ... config,\n ... input_preprocessor=preprocessor,\n ... decoder=PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... ),\n ... )\n\n >>> # you can then do a forward pass as follows:\n >>> feature_extractor = PerceiverFeatureExtractor()\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> inputs = feature_extractor(image, return_tensors="pt").pixel_values\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n ```'
output_attentions = (output_attentions if (output_attentions is not None) else self.config.output_attentions)
output_hidden_states = (output_hidden_states if (output_hidden_states is not None) else self.config.output_hidden_states)
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
if (self.input_preprocessor is not None):
(inputs, modality_sizes, inputs_without_pos) = self.input_preprocessor(inputs)
else:
modality_sizes = None
inputs_without_pos = None
if (inputs.size()[(- 1)] != self.config.d_model):
raise ValueError(f"Last dimension of the inputs: {inputs.size()[(- 1)]} doesn't correspond to config.d_model: {self.config.d_model}. Make sure to set config.d_model appropriately.")
(batch_size, seq_length, _) = inputs.size()
device = inputs.device
if (attention_mask is None):
attention_mask = torch.ones((batch_size, seq_length), device=device)
extended_attention_mask = self.invert_attention_mask(attention_mask)
head_mask = self.get_head_mask(head_mask, (self.config.num_blocks * self.config.num_self_attends_per_block))
embedding_output = self.embeddings(batch_size=batch_size)
encoder_outputs = self.encoder(embedding_output, attention_mask=None, head_mask=head_mask, inputs=inputs, inputs_mask=extended_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
sequence_output = encoder_outputs[0]
logits = None
if self.decoder:
if (subsampled_output_points is not None):
output_modality_sizes = {'audio': subsampled_output_points['audio'].shape[0], 'image': subsampled_output_points['image'].shape[0], 'label': 1}
else:
output_modality_sizes = None
decoder_query = self.decoder.decoder_query(inputs, modality_sizes, inputs_without_pos, subsampled_points=subsampled_output_points)
decoder_outputs = self.decoder(decoder_query, z=sequence_output, query_mask=extended_attention_mask, output_attentions=output_attentions)
logits = decoder_outputs.logits
if (output_attentions and (decoder_outputs.cross_attentions is not None)):
if return_dict:
encoder_outputs.cross_attentions = (encoder_outputs.cross_attentions + decoder_outputs.cross_attentions)
else:
encoder_outputs = (encoder_outputs + decoder_outputs.cross_attentions)
if self.output_postprocessor:
logits = self.output_postprocessor(logits, modality_sizes=output_modality_sizes)
if (not return_dict):
if (logits is not None):
return ((logits, sequence_output) + encoder_outputs[1:])
else:
return ((sequence_output,) + encoder_outputs[1:])
return PerceiverModelOutput(logits=logits, last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('(batch_size, sequence_length)'))
@replace_return_docstrings(output_type=PerceiverModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: torch.FloatTensor, attention_mask: Optional[torch.FloatTensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.FloatTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverModelOutput)]:
'\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverFeatureExtractor, PerceiverModel\n >>> from transformers.models.perceiver.modeling_perceiver import (\n ... PerceiverTextPreprocessor,\n ... PerceiverImagePreprocessor,\n ... PerceiverClassificationDecoder,\n ... )\n >>> import torch\n >>> import requests\n >>> from PIL import Image\n\n >>> # EXAMPLE 1: using the Perceiver to classify texts\n >>> # - we define a TextPreprocessor, which can be used to embed tokens\n >>> # - we define a ClassificationDecoder, which can be used to decode the\n >>> # final hidden states of the latents to classification logits\n >>> # using trainable position embeddings\n >>> config = PerceiverConfig()\n >>> preprocessor = PerceiverTextPreprocessor(config)\n >>> decoder = PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... )\n >>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)\n\n >>> # you can then do a forward pass as follows:\n >>> tokenizer = PerceiverTokenizer()\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n\n >>> # EXAMPLE 2: using the Perceiver to classify images\n >>> # - we define an ImagePreprocessor, which can be used to embed images\n >>> preprocessor = PerceiverImagePreprocessor(\n ... config,\n ... prep_type="conv1x1",\n ... spatial_downsample=1,\n ... out_channels=256,\n ... position_encoding_type="trainable",\n ... concat_or_add_pos="concat",\n ... project_pos_dim=256,\n ... trainable_position_encoding_kwargs=dict(\n ... num_channels=256,\n ... index_dims=config.image_size**2,\n ... ),\n ... )\n\n >>> model = PerceiverModel(\n ... config,\n ... input_preprocessor=preprocessor,\n ... decoder=PerceiverClassificationDecoder(\n ... config,\n ... num_channels=config.d_latents,\n ... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),\n ... use_query_residual=True,\n ... ),\n ... )\n\n >>> # you can then do a forward pass as follows:\n >>> feature_extractor = PerceiverFeatureExtractor()\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> inputs = feature_extractor(image, return_tensors="pt").pixel_values\n\n >>> with torch.no_grad():\n ... outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n\n >>> # to train, one can train the model using standard cross-entropy:\n >>> criterion = torch.nn.CrossEntropyLoss()\n\n >>> labels = torch.tensor([1])\n >>> loss = criterion(logits, labels)\n ```'
output_attentions = (output_attentions if (output_attentions is not None) else self.config.output_attentions)
output_hidden_states = (output_hidden_states if (output_hidden_states is not None) else self.config.output_hidden_states)
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
if (self.input_preprocessor is not None):
(inputs, modality_sizes, inputs_without_pos) = self.input_preprocessor(inputs)
else:
modality_sizes = None
inputs_without_pos = None
if (inputs.size()[(- 1)] != self.config.d_model):
raise ValueError(f"Last dimension of the inputs: {inputs.size()[(- 1)]} doesn't correspond to config.d_model: {self.config.d_model}. Make sure to set config.d_model appropriately.")
(batch_size, seq_length, _) = inputs.size()
device = inputs.device
if (attention_mask is None):
attention_mask = torch.ones((batch_size, seq_length), device=device)
extended_attention_mask = self.invert_attention_mask(attention_mask)
head_mask = self.get_head_mask(head_mask, (self.config.num_blocks * self.config.num_self_attends_per_block))
embedding_output = self.embeddings(batch_size=batch_size)
encoder_outputs = self.encoder(embedding_output, attention_mask=None, head_mask=head_mask, inputs=inputs, inputs_mask=extended_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
sequence_output = encoder_outputs[0]
logits = None
if self.decoder:
if (subsampled_output_points is not None):
output_modality_sizes = {'audio': subsampled_output_points['audio'].shape[0], 'image': subsampled_output_points['image'].shape[0], 'label': 1}
else:
output_modality_sizes = None
decoder_query = self.decoder.decoder_query(inputs, modality_sizes, inputs_without_pos, subsampled_points=subsampled_output_points)
decoder_outputs = self.decoder(decoder_query, z=sequence_output, query_mask=extended_attention_mask, output_attentions=output_attentions)
logits = decoder_outputs.logits
if (output_attentions and (decoder_outputs.cross_attentions is not None)):
if return_dict:
encoder_outputs.cross_attentions = (encoder_outputs.cross_attentions + decoder_outputs.cross_attentions)
else:
encoder_outputs = (encoder_outputs + decoder_outputs.cross_attentions)
if self.output_postprocessor:
logits = self.output_postprocessor(logits, modality_sizes=output_modality_sizes)
if (not return_dict):
if (logits is not None):
return ((logits, sequence_output) + encoder_outputs[1:])
else:
return ((sequence_output,) + encoder_outputs[1:])
return PerceiverModelOutput(logits=logits, last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions)<|docstring|>Returns:
Examples:
```python
>>> from transformers import PerceiverConfig, PerceiverTokenizer, PerceiverFeatureExtractor, PerceiverModel
>>> from transformers.models.perceiver.modeling_perceiver import (
... PerceiverTextPreprocessor,
... PerceiverImagePreprocessor,
... PerceiverClassificationDecoder,
... )
>>> import torch
>>> import requests
>>> from PIL import Image
>>> # EXAMPLE 1: using the Perceiver to classify texts
>>> # - we define a TextPreprocessor, which can be used to embed tokens
>>> # - we define a ClassificationDecoder, which can be used to decode the
>>> # final hidden states of the latents to classification logits
>>> # using trainable position embeddings
>>> config = PerceiverConfig()
>>> preprocessor = PerceiverTextPreprocessor(config)
>>> decoder = PerceiverClassificationDecoder(
... config,
... num_channels=config.d_latents,
... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
... use_query_residual=True,
... )
>>> model = PerceiverModel(config, input_preprocessor=preprocessor, decoder=decoder)
>>> # you can then do a forward pass as follows:
>>> tokenizer = PerceiverTokenizer()
>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
>>> with torch.no_grad():
... outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # to train, one can train the model using standard cross-entropy:
>>> criterion = torch.nn.CrossEntropyLoss()
>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)
>>> # EXAMPLE 2: using the Perceiver to classify images
>>> # - we define an ImagePreprocessor, which can be used to embed images
>>> preprocessor = PerceiverImagePreprocessor(
... config,
... prep_type="conv1x1",
... spatial_downsample=1,
... out_channels=256,
... position_encoding_type="trainable",
... concat_or_add_pos="concat",
... project_pos_dim=256,
... trainable_position_encoding_kwargs=dict(
... num_channels=256,
... index_dims=config.image_size**2,
... ),
... )
>>> model = PerceiverModel(
... config,
... input_preprocessor=preprocessor,
... decoder=PerceiverClassificationDecoder(
... config,
... num_channels=config.d_latents,
... trainable_position_encoding_kwargs=dict(num_channels=config.d_latents, index_dims=1),
... use_query_residual=True,
... ),
... )
>>> # you can then do a forward pass as follows:
>>> feature_extractor = PerceiverFeatureExtractor()
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = feature_extractor(image, return_tensors="pt").pixel_values
>>> with torch.no_grad():
... outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # to train, one can train the model using standard cross-entropy:
>>> criterion = torch.nn.CrossEntropyLoss()
>>> labels = torch.tensor([1])
>>> loss = criterion(logits, labels)
```<|endoftext|> |
abab0a15fce11cc954cebdc6734949aa63dad2bf7a3f2bb323b9acba2b65ad6e | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverMaskedLMOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForMaskedLM\n >>> import torch\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")\n\n >>> # training\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")\n >>> # mask " missing."\n >>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id\n >>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids\n\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")\n\n >>> # mask bytes corresponding to " missing.". Note that the model performs much better if the masked span starts with a space.\n >>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id\n\n >>> # forward pass\n >>> with torch.no_grad():\n ... outputs = model(**encoding)\n >>> logits = outputs.logits\n\n >>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()\n >>> tokenizer.decode(masked_tokens_predictions)\n \' missing.\'\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = self.embedding_decoder((outputs.logits if return_dict else outputs[0]), embedding_layer=self.perceiver.input_preprocessor.embeddings)
masked_lm_loss = None
if (labels is not None):
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(logits.view((- 1), self.config.vocab_size), labels.view((- 1)))
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((masked_lm_loss,) + output) if (masked_lm_loss is not None) else output)
return PerceiverMaskedLMOutput(loss=masked_lm_loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
Returns:
Examples:
```python
>>> from transformers import PerceiverTokenizer, PerceiverForMaskedLM
>>> import torch
>>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")
>>> # training
>>> text = "This is an incomplete sentence where some words are missing."
>>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")
>>> # mask " missing."
>>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id
>>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
>>> # inference
>>> text = "This is an incomplete sentence where some words are missing."
>>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")
>>> # mask bytes corresponding to " missing.". Note that the model performs much better if the masked span starts with a space.
>>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id
>>> # forward pass
>>> with torch.no_grad():
... outputs = model(**encoding)
>>> logits = outputs.logits
>>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()
>>> tokenizer.decode(masked_tokens_predictions)
' missing.'
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverMaskedLMOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForMaskedLM\n >>> import torch\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")\n\n >>> # training\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")\n >>> # mask " missing."\n >>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id\n >>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids\n\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")\n\n >>> # mask bytes corresponding to " missing.". Note that the model performs much better if the masked span starts with a space.\n >>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id\n\n >>> # forward pass\n >>> with torch.no_grad():\n ... outputs = model(**encoding)\n >>> logits = outputs.logits\n\n >>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()\n >>> tokenizer.decode(masked_tokens_predictions)\n \' missing.\'\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = self.embedding_decoder((outputs.logits if return_dict else outputs[0]), embedding_layer=self.perceiver.input_preprocessor.embeddings)
masked_lm_loss = None
if (labels is not None):
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(logits.view((- 1), self.config.vocab_size), labels.view((- 1)))
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((masked_lm_loss,) + output) if (masked_lm_loss is not None) else output)
return PerceiverMaskedLMOutput(loss=masked_lm_loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverMaskedLMOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForMaskedLM\n >>> import torch\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")\n\n >>> # training\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")\n >>> # mask " missing."\n >>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id\n >>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids\n\n >>> outputs = model(**inputs, labels=labels)\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n\n >>> # inference\n >>> text = "This is an incomplete sentence where some words are missing."\n >>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")\n\n >>> # mask bytes corresponding to " missing.". Note that the model performs much better if the masked span starts with a space.\n >>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id\n\n >>> # forward pass\n >>> with torch.no_grad():\n ... outputs = model(**encoding)\n >>> logits = outputs.logits\n\n >>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()\n >>> tokenizer.decode(masked_tokens_predictions)\n \' missing.\'\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = self.embedding_decoder((outputs.logits if return_dict else outputs[0]), embedding_layer=self.perceiver.input_preprocessor.embeddings)
masked_lm_loss = None
if (labels is not None):
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(logits.view((- 1), self.config.vocab_size), labels.view((- 1)))
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((masked_lm_loss,) + output) if (masked_lm_loss is not None) else output)
return PerceiverMaskedLMOutput(loss=masked_lm_loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
Returns:
Examples:
```python
>>> from transformers import PerceiverTokenizer, PerceiverForMaskedLM
>>> import torch
>>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")
>>> # training
>>> text = "This is an incomplete sentence where some words are missing."
>>> inputs = tokenizer(text, padding="max_length", return_tensors="pt")
>>> # mask " missing."
>>> inputs["input_ids"][0, 52:61] = tokenizer.mask_token_id
>>> labels = tokenizer(text, padding="max_length", return_tensors="pt").input_ids
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
>>> # inference
>>> text = "This is an incomplete sentence where some words are missing."
>>> encoding = tokenizer(text, padding="max_length", return_tensors="pt")
>>> # mask bytes corresponding to " missing.". Note that the model performs much better if the masked span starts with a space.
>>> encoding["input_ids"][0, 52:61] = tokenizer.mask_token_id
>>> # forward pass
>>> with torch.no_grad():
... outputs = model(**encoding)
>>> logits = outputs.logits
>>> masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()
>>> tokenizer.decode(masked_tokens_predictions)
' missing.'
```<|endoftext|> |
f802a7c04ee432b7b4e5765997cbe5e6728df4deef96da09bed5f475f6703ea7 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the classification/regression loss. Indices should be in `[0, ..., config.num_labels -\n 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels >\n 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForSequenceClassification\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")\n\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the classification/regression loss. Indices should be in `[0, ..., config.num_labels -
1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels >
1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverTokenizer, PerceiverForSequenceClassification
>>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")
>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the classification/regression loss. Indices should be in `[0, ..., config.num_labels -\n 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels >\n 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForSequenceClassification\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")\n\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, input_ids: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the classification/regression loss. Indices should be in `[0, ..., config.num_labels -\n 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels >\n 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverTokenizer, PerceiverForSequenceClassification\n\n >>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")\n >>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")\n\n >>> text = "hello world"\n >>> inputs = tokenizer(text, return_tensors="pt").input_ids\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n ```'
if ((inputs is not None) and (input_ids is not None)):
raise ValueError('You cannot use both `inputs` and `input_ids`')
elif ((inputs is None) and (input_ids is not None)):
inputs = input_ids
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the classification/regression loss. Indices should be in `[0, ..., config.num_labels -
1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels >
1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverTokenizer, PerceiverForSequenceClassification
>>> tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
>>> model = PerceiverForSequenceClassification.from_pretrained("deepmind/language-perceiver")
>>> text = "hello world"
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
```<|endoftext|> |
089df123d277467d3225c47611934232da59953ff7da59e56785f40a0088bdc1 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationLearned\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-learned")\n >>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationLearned
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-learned")
>>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationLearned\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-learned")\n >>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationLearned\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-learned")\n >>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationLearned
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-learned")
>>> model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
```<|endoftext|> |
8739f54dbb4b573b6839b832eb988134133528a047801c8efb11cce3e3052bb6 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationFourier\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-fourier")\n >>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationFourier
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-fourier")
>>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationFourier\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-fourier")\n >>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationFourier\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-fourier")\n >>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationFourier
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-fourier")
>>> model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
```<|endoftext|> |
1d7ec76fd5b971d0d65b36dfaaba9a2793cbd42f3371fba047f0f8148c808402 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv")\n >>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv")
>>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv")\n >>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None, pixel_values: Optional[torch.Tensor]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing\n >>> from PIL import Image\n >>> import requests\n\n >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv")\n >>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")\n\n >>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values\n >>> outputs = model(inputs=inputs)\n >>> logits = outputs.logits\n >>> # model predicts one of the 1000 ImageNet classes\n >>> predicted_class_idx = logits.argmax(-1).item()\n >>> print("Predicted class:", model.config.id2label[predicted_class_idx])\n ```'
if ((inputs is not None) and (pixel_values is not None)):
raise ValueError('You cannot use both `inputs` and `pixel_values`')
elif ((inputs is None) and (pixel_values is not None)):
inputs = pixel_values
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
if (self.config.problem_type is None):
if (self.num_labels == 1):
self.config.problem_type = 'regression'
elif ((self.num_labels > 1) and ((labels.dtype == torch.long) or (labels.dtype == torch.int))):
self.config.problem_type = 'single_label_classification'
else:
self.config.problem_type = 'multi_label_classification'
if (self.config.problem_type == 'regression'):
loss_fct = MSELoss()
if (self.num_labels == 1):
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif (self.config.problem_type == 'single_label_classification'):
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view((- 1), self.num_labels), labels.view((- 1)))
elif (self.config.problem_type == 'multi_label_classification'):
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv")
>>> model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")
>>> inputs = feature_extractor(images=image, return_tensors="pt").pixel_values
>>> outputs = model(inputs=inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
```<|endoftext|> |
0d38d8e0a4695e34d00fba4785b590e85a868ce1c01429fc7aa1cf1c4962e48c | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the optical flow loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForOpticalFlow\n >>> import torch\n\n >>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")\n\n >>> # in the Perceiver IO paper, the authors extract a 3 x 3 patch around each pixel,\n >>> # leading to 3 x 3 x 3 = 27 values for each pixel (as each pixel also has 3 color channels)\n >>> # patches have shape (batch_size, num_frames, num_channels, height, width)\n >>> # the authors train on resolutions of 368 x 496\n >>> patches = torch.randn(1, 2, 27, 368, 496)\n >>> outputs = model(inputs=patches)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Optical flow training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the optical flow loss. Indices should be in `[0, ..., config.num_labels - 1]`.
Returns:
Examples:
```python
>>> from transformers import PerceiverForOpticalFlow
>>> import torch
>>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")
>>> # in the Perceiver IO paper, the authors extract a 3 x 3 patch around each pixel,
>>> # leading to 3 x 3 x 3 = 27 values for each pixel (as each pixel also has 3 color channels)
>>> # patches have shape (batch_size, num_frames, num_channels, height, width)
>>> # the authors train on resolutions of 368 x 496
>>> patches = torch.randn(1, 2, 27, 368, 496)
>>> outputs = model(inputs=patches)
>>> logits = outputs.logits
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the optical flow loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForOpticalFlow\n >>> import torch\n\n >>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")\n\n >>> # in the Perceiver IO paper, the authors extract a 3 x 3 patch around each pixel,\n >>> # leading to 3 x 3 x 3 = 27 values for each pixel (as each pixel also has 3 color channels)\n >>> # patches have shape (batch_size, num_frames, num_channels, height, width)\n >>> # the authors train on resolutions of 368 x 496\n >>> patches = torch.randn(1, 2, 27, 368, 496)\n >>> outputs = model(inputs=patches)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Optical flow training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the optical flow loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForOpticalFlow\n >>> import torch\n\n >>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")\n\n >>> # in the Perceiver IO paper, the authors extract a 3 x 3 patch around each pixel,\n >>> # leading to 3 x 3 x 3 = 27 values for each pixel (as each pixel also has 3 color channels)\n >>> # patches have shape (batch_size, num_frames, num_channels, height, width)\n >>> # the authors train on resolutions of 368 x 496\n >>> patches = torch.randn(1, 2, 27, 368, 496)\n >>> outputs = model(inputs=patches)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Optical flow training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the optical flow loss. Indices should be in `[0, ..., config.num_labels - 1]`.
Returns:
Examples:
```python
>>> from transformers import PerceiverForOpticalFlow
>>> import torch
>>> model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")
>>> # in the Perceiver IO paper, the authors extract a 3 x 3 patch around each pixel,
>>> # leading to 3 x 3 x 3 = 27 values for each pixel (as each pixel also has 3 color channels)
>>> # patches have shape (batch_size, num_frames, num_channels, height, width)
>>> # the authors train on resolutions of 368 x 496
>>> patches = torch.randn(1, 2, 27, 368, 496)
>>> outputs = model(inputs=patches)
>>> logits = outputs.logits
```<|endoftext|> |
0b9f8b3923e78cfbf1c8ad81a689ee23eb8ac0867e86ef9b2ab6d6c86e860be0 | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForMultimodalAutoencoding\n >>> import torch\n >>> import numpy as np\n\n >>> # create multimodal inputs\n >>> images = torch.randn((1, 16, 3, 224, 224))\n >>> audio = torch.randn((1, 30720, 1))\n >>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))\n\n >>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")\n\n >>> # in the Perceiver IO paper, videos are auto-encoded in chunks\n >>> # each chunk subsamples different index dimensions of the image and audio modality decoder queries\n >>> nchunks = 128\n >>> image_chunk_size = np.prod((16, 224, 224)) // nchunks\n >>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks\n >>> # process the first chunk\n >>> chunk_idx = 0\n >>> subsampling = {\n ... "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),\n ... "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),\n ... "label": None,\n ... }\n\n >>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, subsampled_output_points=subsampled_output_points, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Multimodal autoencoding training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverForMultimodalAutoencoding
>>> import torch
>>> import numpy as np
>>> # create multimodal inputs
>>> images = torch.randn((1, 16, 3, 224, 224))
>>> audio = torch.randn((1, 30720, 1))
>>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))
>>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")
>>> # in the Perceiver IO paper, videos are auto-encoded in chunks
>>> # each chunk subsamples different index dimensions of the image and audio modality decoder queries
>>> nchunks = 128
>>> image_chunk_size = np.prod((16, 224, 224)) // nchunks
>>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks
>>> # process the first chunk
>>> chunk_idx = 0
>>> subsampling = {
... "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),
... "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),
... "label": None,
... }
>>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)
>>> logits = outputs.logits
``` | src/transformers/models/perceiver/modeling_perceiver.py | forward | mingboiz/transformers | 8,028 | python | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForMultimodalAutoencoding\n >>> import torch\n >>> import numpy as np\n\n >>> # create multimodal inputs\n >>> images = torch.randn((1, 16, 3, 224, 224))\n >>> audio = torch.randn((1, 30720, 1))\n >>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))\n\n >>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")\n\n >>> # in the Perceiver IO paper, videos are auto-encoded in chunks\n >>> # each chunk subsamples different index dimensions of the image and audio modality decoder queries\n >>> nchunks = 128\n >>> image_chunk_size = np.prod((16, 224, 224)) // nchunks\n >>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks\n >>> # process the first chunk\n >>> chunk_idx = 0\n >>> subsampling = {\n ... "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),\n ... "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),\n ... "label": None,\n ... }\n\n >>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, subsampled_output_points=subsampled_output_points, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Multimodal autoencoding training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions) | @add_start_docstrings_to_model_forward(PERCEIVER_INPUTS_DOCSTRING.format('batch_size, sequence_length'))
@replace_return_docstrings(output_type=PerceiverClassifierOutput, config_class=_CONFIG_FOR_DOC)
def forward(self, inputs: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, subsampled_output_points: Optional[Dict[(str, torch.Tensor)]]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: Optional[torch.Tensor]=None, return_dict: Optional[bool]=None) -> Union[(Tuple, PerceiverClassifierOutput)]:
'\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import PerceiverForMultimodalAutoencoding\n >>> import torch\n >>> import numpy as np\n\n >>> # create multimodal inputs\n >>> images = torch.randn((1, 16, 3, 224, 224))\n >>> audio = torch.randn((1, 30720, 1))\n >>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))\n\n >>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")\n\n >>> # in the Perceiver IO paper, videos are auto-encoded in chunks\n >>> # each chunk subsamples different index dimensions of the image and audio modality decoder queries\n >>> nchunks = 128\n >>> image_chunk_size = np.prod((16, 224, 224)) // nchunks\n >>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks\n >>> # process the first chunk\n >>> chunk_idx = 0\n >>> subsampling = {\n ... "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),\n ... "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),\n ... "label": None,\n ... }\n\n >>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)\n >>> logits = outputs.logits\n ```'
return_dict = (return_dict if (return_dict is not None) else self.config.use_return_dict)
outputs = self.perceiver(inputs=inputs, attention_mask=attention_mask, subsampled_output_points=subsampled_output_points, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
logits = (outputs.logits if return_dict else outputs[0])
loss = None
if (labels is not None):
raise NotImplementedError('Multimodal autoencoding training is not yet supported')
if (not return_dict):
output = ((logits,) + outputs[2:])
return (((loss,) + output) if (loss is not None) else output)
return PerceiverClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)<|docstring|>labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
Returns:
Examples:
```python
>>> from transformers import PerceiverForMultimodalAutoencoding
>>> import torch
>>> import numpy as np
>>> # create multimodal inputs
>>> images = torch.randn((1, 16, 3, 224, 224))
>>> audio = torch.randn((1, 30720, 1))
>>> inputs = dict(image=images, audio=audio, label=torch.zeros((images.shape[0], 700)))
>>> model = PerceiverForMultimodalAutoencoding.from_pretrained("deepmind/multimodal-perceiver")
>>> # in the Perceiver IO paper, videos are auto-encoded in chunks
>>> # each chunk subsamples different index dimensions of the image and audio modality decoder queries
>>> nchunks = 128
>>> image_chunk_size = np.prod((16, 224, 224)) // nchunks
>>> audio_chunk_size = audio.shape[1] // model.config.samples_per_patch // nchunks
>>> # process the first chunk
>>> chunk_idx = 0
>>> subsampling = {
... "image": torch.arange(image_chunk_size * chunk_idx, image_chunk_size * (chunk_idx + 1)),
... "audio": torch.arange(audio_chunk_size * chunk_idx, audio_chunk_size * (chunk_idx + 1)),
... "label": None,
... }
>>> outputs = model(inputs=inputs, subsampled_output_points=subsampling)
>>> logits = outputs.logits
```<|endoftext|> |
0ef534be295384c45e41821798ba17e99303d9ed1ea499e545067df3994c6e38 | def __init__(self, num_layers: int=1, in_channels: int=3, out_channels: int=64, use_batchnorm: bool=True):
'\n Constructs a Conv2DDownsample model.\n\n Args:\n in_channels (`int`, *optional*, defaults to 3):\n The number of input channels.\n out_channels (`int`, *optional*, defaults to 64):\n The number of conv output channels.\n use_batchnorm (`bool`, *optional*, defaults to `True`):\n Whether to use batchnorm.\n '
super().__init__()
self.conv = Conv2dSamePadding(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=2, bias=False)
self.batchnorm = (nn.BatchNorm2d(num_features=out_channels) if use_batchnorm else nn.Identity())
self.relu = nn.ReLU()
self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2) | Constructs a Conv2DDownsample model.
Args:
in_channels (`int`, *optional*, defaults to 3):
The number of input channels.
out_channels (`int`, *optional*, defaults to 64):
The number of conv output channels.
use_batchnorm (`bool`, *optional*, defaults to `True`):
Whether to use batchnorm. | src/transformers/models/perceiver/modeling_perceiver.py | __init__ | mingboiz/transformers | 8,028 | python | def __init__(self, num_layers: int=1, in_channels: int=3, out_channels: int=64, use_batchnorm: bool=True):
'\n Constructs a Conv2DDownsample model.\n\n Args:\n in_channels (`int`, *optional*, defaults to 3):\n The number of input channels.\n out_channels (`int`, *optional*, defaults to 64):\n The number of conv output channels.\n use_batchnorm (`bool`, *optional*, defaults to `True`):\n Whether to use batchnorm.\n '
super().__init__()
self.conv = Conv2dSamePadding(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=2, bias=False)
self.batchnorm = (nn.BatchNorm2d(num_features=out_channels) if use_batchnorm else nn.Identity())
self.relu = nn.ReLU()
self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2) | def __init__(self, num_layers: int=1, in_channels: int=3, out_channels: int=64, use_batchnorm: bool=True):
'\n Constructs a Conv2DDownsample model.\n\n Args:\n in_channels (`int`, *optional*, defaults to 3):\n The number of input channels.\n out_channels (`int`, *optional*, defaults to 64):\n The number of conv output channels.\n use_batchnorm (`bool`, *optional*, defaults to `True`):\n Whether to use batchnorm.\n '
super().__init__()
self.conv = Conv2dSamePadding(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=2, bias=False)
self.batchnorm = (nn.BatchNorm2d(num_features=out_channels) if use_batchnorm else nn.Identity())
self.relu = nn.ReLU()
self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2)<|docstring|>Constructs a Conv2DDownsample model.
Args:
in_channels (`int`, *optional*, defaults to 3):
The number of input channels.
out_channels (`int`, *optional*, defaults to 64):
The number of conv output channels.
use_batchnorm (`bool`, *optional*, defaults to `True`):
Whether to use batchnorm.<|endoftext|> |
7ff22453ca1dddd97db765c5e63206c5b6fe8271f998293489c5cee231cf7b5c | def output_size(self):
'Returns size of positional encodings last dimension.'
num_dims = len(self.max_resolution)
encoding_size = (self.num_bands * num_dims)
if (not self.sine_only):
encoding_size *= 2
if self.concat_pos:
encoding_size += self.num_dimensions
return encoding_size | Returns size of positional encodings last dimension. | src/transformers/models/perceiver/modeling_perceiver.py | output_size | mingboiz/transformers | 8,028 | python | def output_size(self):
num_dims = len(self.max_resolution)
encoding_size = (self.num_bands * num_dims)
if (not self.sine_only):
encoding_size *= 2
if self.concat_pos:
encoding_size += self.num_dimensions
return encoding_size | def output_size(self):
num_dims = len(self.max_resolution)
encoding_size = (self.num_bands * num_dims)
if (not self.sine_only):
encoding_size *= 2
if self.concat_pos:
encoding_size += self.num_dimensions
return encoding_size<|docstring|>Returns size of positional encodings last dimension.<|endoftext|> |
094ad22bf1294415e2ab951a3d31cea14542f156450b2779b06f321ed49bb3e7 | @property
def num_channels(self) -> int:
'Returns size of preprocessor output.'
raise NotImplementedError() | Returns size of preprocessor output. | src/transformers/models/perceiver/modeling_perceiver.py | num_channels | mingboiz/transformers | 8,028 | python | @property
def num_channels(self) -> int:
raise NotImplementedError() | @property
def num_channels(self) -> int:
raise NotImplementedError()<|docstring|>Returns size of preprocessor output.<|endoftext|> |
8c1ff4920f1c4cbb252c33a2af2527cf7733d7e3036f1792e0c2aeed9af88f12 | def _build_network_inputs(self, inputs: torch.Tensor, pos: torch.Tensor, network_input_is_1d: bool=True):
'\n Construct the final input, including position encoding.\n\n This method expects the inputs to always have channels as last dimension.\n\n '
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
indices = np.prod(index_dims)
if ((len(inputs.shape) > 3) and network_input_is_1d):
inputs = torch.reshape(inputs, [batch_size, indices, (- 1)])
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (not network_input_is_1d):
sh = inputs.shape
pos_enc = torch.reshape(pos_enc, (list(sh)[:(- 1)] + [(- 1)]))
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs) | Construct the final input, including position encoding.
This method expects the inputs to always have channels as last dimension. | src/transformers/models/perceiver/modeling_perceiver.py | _build_network_inputs | mingboiz/transformers | 8,028 | python | def _build_network_inputs(self, inputs: torch.Tensor, pos: torch.Tensor, network_input_is_1d: bool=True):
'\n Construct the final input, including position encoding.\n\n This method expects the inputs to always have channels as last dimension.\n\n '
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
indices = np.prod(index_dims)
if ((len(inputs.shape) > 3) and network_input_is_1d):
inputs = torch.reshape(inputs, [batch_size, indices, (- 1)])
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (not network_input_is_1d):
sh = inputs.shape
pos_enc = torch.reshape(pos_enc, (list(sh)[:(- 1)] + [(- 1)]))
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs) | def _build_network_inputs(self, inputs: torch.Tensor, pos: torch.Tensor, network_input_is_1d: bool=True):
'\n Construct the final input, including position encoding.\n\n This method expects the inputs to always have channels as last dimension.\n\n '
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
indices = np.prod(index_dims)
if ((len(inputs.shape) > 3) and network_input_is_1d):
inputs = torch.reshape(inputs, [batch_size, indices, (- 1)])
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (not network_input_is_1d):
sh = inputs.shape
pos_enc = torch.reshape(pos_enc, (list(sh)[:(- 1)] + [(- 1)]))
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs)<|docstring|>Construct the final input, including position encoding.
This method expects the inputs to always have channels as last dimension.<|endoftext|> |
b6f40d39f134f3eb73a21f7e577ce190c13fdf966a91e554c960e6999b8e421d | def _build_network_inputs(self, inputs, pos):
'Construct the final input, including position encoding.'
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs) | Construct the final input, including position encoding. | src/transformers/models/perceiver/modeling_perceiver.py | _build_network_inputs | mingboiz/transformers | 8,028 | python | def _build_network_inputs(self, inputs, pos):
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs) | def _build_network_inputs(self, inputs, pos):
batch_size = inputs.shape[0]
index_dims = inputs.shape[1:(- 1)]
if (self.position_encoding_type == 'trainable'):
pos_enc = self.position_embeddings(batch_size)
elif (self.position_encoding_type == 'fourier'):
pos_enc = self.position_embeddings(index_dims, batch_size, device=inputs.device)
pos_enc = self.positions_projection(pos_enc)
if (self.concat_or_add_pos == 'concat'):
inputs_with_pos = torch.cat([inputs, pos_enc], dim=(- 1))
elif (self.concat_or_add_pos == 'add'):
inputs_with_pos = (inputs + pos_enc)
return (inputs_with_pos, inputs)<|docstring|>Construct the final input, including position encoding.<|endoftext|> |
72e294157470e014d138b29b169aa3bb390d21c058fb0382616998420b5e2765 | def select_all(self, col):
'\n Check/Uncheck items on table_dragdrop\n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 4):
for i in range(parent.rowCount()):
parent.removeRow(0)
else:
return | Check/Uncheck items on table_dragdrop | src/iacs_ipac_reader/_dock_widget.py | select_all | zcqwh/iacs_ipac_reader | 0 | python | def select_all(self, col):
'\n \n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 4):
for i in range(parent.rowCount()):
parent.removeRow(0)
else:
return | def select_all(self, col):
'\n \n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 4):
for i in range(parent.rowCount()):
parent.removeRow(0)
else:
return<|docstring|>Check/Uncheck items on table_dragdrop<|endoftext|> |
a23fb3e669ff02a1bcfc7b8e93824577cbd3ef7a4693db99bbfa94535fd14016 | def delete_item(self, item):
'\n delete table item and corresponding layers\n '
buttonClicked = self.sender()
table = buttonClicked.parent().parent()
index = table.indexAt(buttonClicked.pos())
rowPosition = index.row()
table.removeRow(rowPosition) | delete table item and corresponding layers | src/iacs_ipac_reader/_dock_widget.py | delete_item | zcqwh/iacs_ipac_reader | 0 | python | def delete_item(self, item):
'\n \n '
buttonClicked = self.sender()
table = buttonClicked.parent().parent()
index = table.indexAt(buttonClicked.pos())
rowPosition = index.row()
table.removeRow(rowPosition) | def delete_item(self, item):
'\n \n '
buttonClicked = self.sender()
table = buttonClicked.parent().parent()
index = table.indexAt(buttonClicked.pos())
rowPosition = index.row()
table.removeRow(rowPosition)<|docstring|>delete table item and corresponding layers<|endoftext|> |
51c8db9cccc79f17a0e2767eb8a9cf3f565eec93345722033c622afdf3c7da2d | def select_layers(self):
'select all raw date layer'
layers = []
for layer in self.viewer.layers:
if isinstance(layer, napari.layers.Image):
name = layer.name
if (('stack' in name) or ('tiles' in name)):
pass
else:
layers.append(layer)
return layers | select all raw date layer | src/iacs_ipac_reader/_dock_widget.py | select_layers | zcqwh/iacs_ipac_reader | 0 | python | def select_layers(self):
layers = []
for layer in self.viewer.layers:
if isinstance(layer, napari.layers.Image):
name = layer.name
if (('stack' in name) or ('tiles' in name)):
pass
else:
layers.append(layer)
return layers | def select_layers(self):
layers = []
for layer in self.viewer.layers:
if isinstance(layer, napari.layers.Image):
name = layer.name
if (('stack' in name) or ('tiles' in name)):
pass
else:
layers.append(layer)
return layers<|docstring|>select all raw date layer<|endoftext|> |
c9ee3b73331529e2d8600ab384795467b0ed98f73fb704ce7311ddb3d349de1f | def read_image_iacs_2ch(self, layer_ch0, layer_ch1):
'\n Prepare a set of imges for napari.\n\n Parameters\n ----------\n layer_ch0 : napari.layer\n \n layer_ch1 : napari.layer\n \n\n Returns\n -------\n contours_images_list\n\n '
filter_len = self.checkBox_iacs_cl.isChecked()
len_min = self.spinBox_iacs_ca_min.value()
len_max = self.spinBox_iacs_cl_max.value()
filter_area = self.checkBox_iacs_ca.isChecked()
area_min = self.spinBox_iacs_ca_min.value()
area_max = self.spinBox_iacs_ca_max.value()
filter_n = self.checkBox_iacs_cn.isChecked()
nr_contours = self.spinBox_iacs_cn.value()
cnt_color = image_processing.get_color(self.comboBox_iacs_cnt_color.currentText())
ind_color = image_processing.get_color(self.comboBox_iacs_ind_color.currentText())
ch0_color = self.comboBox_iacs_ch0.currentText()
ch1_color = self.comboBox_iacs_ch1.currentText()
tiled_img_ch0 = layer_ch0.data
images_ch0 = image_processing.tiled_2_list(tiled_img_ch0)
tiled_img_ch1 = layer_ch1.data
images_ch1 = image_processing.tiled_2_list(tiled_img_ch1)
contours_images_list = []
colormap_images_list = []
for i in range(len(images_ch0)):
image_ch0 = images_ch0[i]
image_ch1 = images_ch1[i]
(image_ch0, factor0) = image_processing.uint16_2_unit8(image_ch0)
(image_ch1, factor1) = image_processing.uint16_2_unit8(image_ch1)
image_ch0 = image_processing.vstripes_removal(image_ch0)
image_ch1 = image_processing.vstripes_removal(image_ch1)
img_sup = cv2.add(image_ch0, image_ch1)
(contours_, masks_) = image_processing.get_masks_iacs(img_sup, filter_len, len_min, len_max, filter_area, area_min, area_max, filter_n, nr_contours)
trans_mask = np.zeros((100, 88, 4), dtype=np.uint8)
if self.checkBox_iacs_contour.isChecked():
cv2.drawContours(trans_mask, contours_, (- 1), cnt_color, 1)
if self.checkBox_iacs_index.isChecked():
cv2.rectangle(trans_mask, (0, 0), (87, 99), ind_color, 1)
cv2.putText(trans_mask, str(i), (7, 15), cv2.FONT_HERSHEY_DUPLEX, 0.4, ind_color, 1)
contours_images_list.append(trans_mask)
if self.groupBox_colormap.isChecked():
image_ch0_color = image_processing.add_colormap(image_ch0, ch0_color)
image_ch1_color = image_processing.add_colormap(image_ch1, ch1_color)
img_sup = cv2.add(image_ch0_color, image_ch1_color)
colormap_images_list.append(img_sup)
return (contours_images_list, colormap_images_list) | Prepare a set of imges for napari.
Parameters
----------
layer_ch0 : napari.layer
layer_ch1 : napari.layer
Returns
-------
contours_images_list | src/iacs_ipac_reader/_dock_widget.py | read_image_iacs_2ch | zcqwh/iacs_ipac_reader | 0 | python | def read_image_iacs_2ch(self, layer_ch0, layer_ch1):
'\n Prepare a set of imges for napari.\n\n Parameters\n ----------\n layer_ch0 : napari.layer\n \n layer_ch1 : napari.layer\n \n\n Returns\n -------\n contours_images_list\n\n '
filter_len = self.checkBox_iacs_cl.isChecked()
len_min = self.spinBox_iacs_ca_min.value()
len_max = self.spinBox_iacs_cl_max.value()
filter_area = self.checkBox_iacs_ca.isChecked()
area_min = self.spinBox_iacs_ca_min.value()
area_max = self.spinBox_iacs_ca_max.value()
filter_n = self.checkBox_iacs_cn.isChecked()
nr_contours = self.spinBox_iacs_cn.value()
cnt_color = image_processing.get_color(self.comboBox_iacs_cnt_color.currentText())
ind_color = image_processing.get_color(self.comboBox_iacs_ind_color.currentText())
ch0_color = self.comboBox_iacs_ch0.currentText()
ch1_color = self.comboBox_iacs_ch1.currentText()
tiled_img_ch0 = layer_ch0.data
images_ch0 = image_processing.tiled_2_list(tiled_img_ch0)
tiled_img_ch1 = layer_ch1.data
images_ch1 = image_processing.tiled_2_list(tiled_img_ch1)
contours_images_list = []
colormap_images_list = []
for i in range(len(images_ch0)):
image_ch0 = images_ch0[i]
image_ch1 = images_ch1[i]
(image_ch0, factor0) = image_processing.uint16_2_unit8(image_ch0)
(image_ch1, factor1) = image_processing.uint16_2_unit8(image_ch1)
image_ch0 = image_processing.vstripes_removal(image_ch0)
image_ch1 = image_processing.vstripes_removal(image_ch1)
img_sup = cv2.add(image_ch0, image_ch1)
(contours_, masks_) = image_processing.get_masks_iacs(img_sup, filter_len, len_min, len_max, filter_area, area_min, area_max, filter_n, nr_contours)
trans_mask = np.zeros((100, 88, 4), dtype=np.uint8)
if self.checkBox_iacs_contour.isChecked():
cv2.drawContours(trans_mask, contours_, (- 1), cnt_color, 1)
if self.checkBox_iacs_index.isChecked():
cv2.rectangle(trans_mask, (0, 0), (87, 99), ind_color, 1)
cv2.putText(trans_mask, str(i), (7, 15), cv2.FONT_HERSHEY_DUPLEX, 0.4, ind_color, 1)
contours_images_list.append(trans_mask)
if self.groupBox_colormap.isChecked():
image_ch0_color = image_processing.add_colormap(image_ch0, ch0_color)
image_ch1_color = image_processing.add_colormap(image_ch1, ch1_color)
img_sup = cv2.add(image_ch0_color, image_ch1_color)
colormap_images_list.append(img_sup)
return (contours_images_list, colormap_images_list) | def read_image_iacs_2ch(self, layer_ch0, layer_ch1):
'\n Prepare a set of imges for napari.\n\n Parameters\n ----------\n layer_ch0 : napari.layer\n \n layer_ch1 : napari.layer\n \n\n Returns\n -------\n contours_images_list\n\n '
filter_len = self.checkBox_iacs_cl.isChecked()
len_min = self.spinBox_iacs_ca_min.value()
len_max = self.spinBox_iacs_cl_max.value()
filter_area = self.checkBox_iacs_ca.isChecked()
area_min = self.spinBox_iacs_ca_min.value()
area_max = self.spinBox_iacs_ca_max.value()
filter_n = self.checkBox_iacs_cn.isChecked()
nr_contours = self.spinBox_iacs_cn.value()
cnt_color = image_processing.get_color(self.comboBox_iacs_cnt_color.currentText())
ind_color = image_processing.get_color(self.comboBox_iacs_ind_color.currentText())
ch0_color = self.comboBox_iacs_ch0.currentText()
ch1_color = self.comboBox_iacs_ch1.currentText()
tiled_img_ch0 = layer_ch0.data
images_ch0 = image_processing.tiled_2_list(tiled_img_ch0)
tiled_img_ch1 = layer_ch1.data
images_ch1 = image_processing.tiled_2_list(tiled_img_ch1)
contours_images_list = []
colormap_images_list = []
for i in range(len(images_ch0)):
image_ch0 = images_ch0[i]
image_ch1 = images_ch1[i]
(image_ch0, factor0) = image_processing.uint16_2_unit8(image_ch0)
(image_ch1, factor1) = image_processing.uint16_2_unit8(image_ch1)
image_ch0 = image_processing.vstripes_removal(image_ch0)
image_ch1 = image_processing.vstripes_removal(image_ch1)
img_sup = cv2.add(image_ch0, image_ch1)
(contours_, masks_) = image_processing.get_masks_iacs(img_sup, filter_len, len_min, len_max, filter_area, area_min, area_max, filter_n, nr_contours)
trans_mask = np.zeros((100, 88, 4), dtype=np.uint8)
if self.checkBox_iacs_contour.isChecked():
cv2.drawContours(trans_mask, contours_, (- 1), cnt_color, 1)
if self.checkBox_iacs_index.isChecked():
cv2.rectangle(trans_mask, (0, 0), (87, 99), ind_color, 1)
cv2.putText(trans_mask, str(i), (7, 15), cv2.FONT_HERSHEY_DUPLEX, 0.4, ind_color, 1)
contours_images_list.append(trans_mask)
if self.groupBox_colormap.isChecked():
image_ch0_color = image_processing.add_colormap(image_ch0, ch0_color)
image_ch1_color = image_processing.add_colormap(image_ch1, ch1_color)
img_sup = cv2.add(image_ch0_color, image_ch1_color)
colormap_images_list.append(img_sup)
return (contours_images_list, colormap_images_list)<|docstring|>Prepare a set of imges for napari.
Parameters
----------
layer_ch0 : napari.layer
layer_ch1 : napari.layer
Returns
-------
contours_images_list<|endoftext|> |
eab00de7740779c0f2e0131dd8497ea388e81af15e72b1c02f4da4d28bdcc5b5 | def select_all_aid(self, col):
'\n Check/Uncheck items on table_dragdrop\n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 3):
for i in range(parent.rowCount()):
parent.removeRow(0) | Check/Uncheck items on table_dragdrop | src/iacs_ipac_reader/_dock_widget.py | select_all_aid | zcqwh/iacs_ipac_reader | 0 | python | def select_all_aid(self, col):
'\n \n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 3):
for i in range(parent.rowCount()):
parent.removeRow(0) | def select_all_aid(self, col):
'\n \n '
parent = self.sender().parent()
if (col == 0):
rows = range(parent.rowCount())
tableitems = [parent.item(row, col) for row in rows]
checkStates = [tableitem.checkState() for tableitem in tableitems]
checked = [(state == QtCore.Qt.Checked) for state in checkStates]
if (set(checked) == {True}):
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Unchecked)
else:
for tableitem in tableitems:
tableitem.setCheckState(QtCore.Qt.Checked)
if (col == 1):
children = parent.findChildren(QtWidgets.QPushButton, 'btn_load')
for button in children:
button.click()
if (col == 3):
for i in range(parent.rowCount()):
parent.removeRow(0)<|docstring|>Check/Uncheck items on table_dragdrop<|endoftext|> |
498a024863f31eceac93d07786375661d7a47965bc8e3bb4aabef4e194c4a418 | def getdata3(rtdc_path, userdef0):
'\n Get distributions: \n - area and solidity for platelets\n - area and solidity for clusters\n '
feature_name = ['Area', 'Solidity']
keys = ['area_um', 'area_ratio']
classes = [1, 2]
(NameList, List) = ([], [])
rtdc_ds = h5py.File(rtdc_path, 'r')
for cl in classes:
ind_x = np.where((userdef0 == cl))[0]
for k in range(len(keys)):
values = rtdc_ds['events'][keys[k]][:][ind_x]
ind = np.isnan(values)
ind = np.where((ind == False))[0]
values = values[ind]
ind = np.where((values != 0))[0]
values = values[ind]
if (keys[k] == 'area_ratio'):
values = (1 / values)
NameList.append(((feature_name[k] + '_class') + str(cl)))
if (len(values) == 0):
List.append(np.nan)
else:
List.append(values)
return [List, NameList] | Get distributions:
- area and solidity for platelets
- area and solidity for clusters | src/iacs_ipac_reader/_dock_widget.py | getdata3 | zcqwh/iacs_ipac_reader | 0 | python | def getdata3(rtdc_path, userdef0):
'\n Get distributions: \n - area and solidity for platelets\n - area and solidity for clusters\n '
feature_name = ['Area', 'Solidity']
keys = ['area_um', 'area_ratio']
classes = [1, 2]
(NameList, List) = ([], [])
rtdc_ds = h5py.File(rtdc_path, 'r')
for cl in classes:
ind_x = np.where((userdef0 == cl))[0]
for k in range(len(keys)):
values = rtdc_ds['events'][keys[k]][:][ind_x]
ind = np.isnan(values)
ind = np.where((ind == False))[0]
values = values[ind]
ind = np.where((values != 0))[0]
values = values[ind]
if (keys[k] == 'area_ratio'):
values = (1 / values)
NameList.append(((feature_name[k] + '_class') + str(cl)))
if (len(values) == 0):
List.append(np.nan)
else:
List.append(values)
return [List, NameList] | def getdata3(rtdc_path, userdef0):
'\n Get distributions: \n - area and solidity for platelets\n - area and solidity for clusters\n '
feature_name = ['Area', 'Solidity']
keys = ['area_um', 'area_ratio']
classes = [1, 2]
(NameList, List) = ([], [])
rtdc_ds = h5py.File(rtdc_path, 'r')
for cl in classes:
ind_x = np.where((userdef0 == cl))[0]
for k in range(len(keys)):
values = rtdc_ds['events'][keys[k]][:][ind_x]
ind = np.isnan(values)
ind = np.where((ind == False))[0]
values = values[ind]
ind = np.where((values != 0))[0]
values = values[ind]
if (keys[k] == 'area_ratio'):
values = (1 / values)
NameList.append(((feature_name[k] + '_class') + str(cl)))
if (len(values) == 0):
List.append(np.nan)
else:
List.append(values)
return [List, NameList]<|docstring|>Get distributions:
- area and solidity for platelets
- area and solidity for clusters<|endoftext|> |
4bf309fe9bc1970a111e24596c9aa6de125f1b4647d9934414eb4992624fca4b | def test_query(self):
'\n Test for Query a resource, and decode the return data\n '
with patch.object(salt.utils.http, 'query', return_value='A'):
self.assertEqual(http.query('url'), 'A') | Test for Query a resource, and decode the return data | tests/unit/modules/test_http.py | test_query | Flowdalic/salt | 9,425 | python | def test_query(self):
'\n \n '
with patch.object(salt.utils.http, 'query', return_value='A'):
self.assertEqual(http.query('url'), 'A') | def test_query(self):
'\n \n '
with patch.object(salt.utils.http, 'query', return_value='A'):
self.assertEqual(http.query('url'), 'A')<|docstring|>Test for Query a resource, and decode the return data<|endoftext|> |
aeddddb47c3f0ccdff7b1657394d196f1d732ea21f2eeab8e393089b6517bf44 | def test_wait_for_with_interval(self):
'\n Test for wait_for_successful_query waits for request_interval\n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url', request_interval=1), {})
sleep_mock.assert_called_once_with(1) | Test for wait_for_successful_query waits for request_interval | tests/unit/modules/test_http.py | test_wait_for_with_interval | Flowdalic/salt | 9,425 | python | def test_wait_for_with_interval(self):
'\n \n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url', request_interval=1), {})
sleep_mock.assert_called_once_with(1) | def test_wait_for_with_interval(self):
'\n \n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url', request_interval=1), {})
sleep_mock.assert_called_once_with(1)<|docstring|>Test for wait_for_successful_query waits for request_interval<|endoftext|> |
d2340c25d46760ec79968c79c3e53986161fade2149e628de1c3f8f444867d46 | def test_wait_for_without_interval(self):
'\n Test for wait_for_successful_query waits for request_interval\n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url'), {})
sleep_mock.assert_not_called() | Test for wait_for_successful_query waits for request_interval | tests/unit/modules/test_http.py | test_wait_for_without_interval | Flowdalic/salt | 9,425 | python | def test_wait_for_without_interval(self):
'\n \n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url'), {})
sleep_mock.assert_not_called() | def test_wait_for_without_interval(self):
'\n \n '
query_mock = MagicMock(side_effect=[{'error': 'error'}, {}])
with patch.object(salt.utils.http, 'query', query_mock):
with patch('time.sleep', MagicMock()) as sleep_mock:
self.assertEqual(http.wait_for_successful_query('url'), {})
sleep_mock.assert_not_called()<|docstring|>Test for wait_for_successful_query waits for request_interval<|endoftext|> |
c9fcc899ce320125f5982aed869e9bdd83c9a52e3eb7e1b24d00979854eee31c | def get_all_speak_info(self):
'\n 群总体在线时间分布\n :return:\n '
post = self.db.profile
week_online = numpy.zeros((7, 24), dtype=numpy.int)
for doc in post.find({}, {'week_online': 1}):
week_online += numpy.array(doc['week_online'])
return week_online.tolist() | 群总体在线时间分布
:return: | chatlog/analysis/collectivity.py | get_all_speak_info | 2cracer2/QQchatlog_Analysis | 3 | python | def get_all_speak_info(self):
'\n 群总体在线时间分布\n :return:\n '
post = self.db.profile
week_online = numpy.zeros((7, 24), dtype=numpy.int)
for doc in post.find({}, {'week_online': 1}):
week_online += numpy.array(doc['week_online'])
return week_online.tolist() | def get_all_speak_info(self):
'\n 群总体在线时间分布\n :return:\n '
post = self.db.profile
week_online = numpy.zeros((7, 24), dtype=numpy.int)
for doc in post.find({}, {'week_online': 1}):
week_online += numpy.array(doc['week_online'])
return week_online.tolist()<|docstring|>群总体在线时间分布
:return:<|endoftext|> |
1b1bff3b4e95fe8aa117a619633d14e2415c4b3929a4cfd6d81f50a3bbd54f64 | def remove_num_method1(in_str: str) -> str:
'based on re module'
if (not hasattr(remove_num_method1, '_cache_re')):
cache_re = re.compile('\\d')
remove_num_method1._cache_re = cache_re
return re.sub(remove_num_method1._cache_re, '', in_str) | based on re module | python/re/remove_num.py | remove_num_method1 | colin-zhou/mrfs | 8 | python | def remove_num_method1(in_str: str) -> str:
if (not hasattr(remove_num_method1, '_cache_re')):
cache_re = re.compile('\\d')
remove_num_method1._cache_re = cache_re
return re.sub(remove_num_method1._cache_re, , in_str) | def remove_num_method1(in_str: str) -> str:
if (not hasattr(remove_num_method1, '_cache_re')):
cache_re = re.compile('\\d')
remove_num_method1._cache_re = cache_re
return re.sub(remove_num_method1._cache_re, , in_str)<|docstring|>based on re module<|endoftext|> |
492575d0de655f42a7852a6726d478fe0df883f0a09f31e0dff966f77f386020 | def remove_num_method2(in_str: str) -> str:
'based on translate'
return in_str.translate(str.maketrans('', '', string.digits)) | based on translate | python/re/remove_num.py | remove_num_method2 | colin-zhou/mrfs | 8 | python | def remove_num_method2(in_str: str) -> str:
return in_str.translate(str.maketrans(, , string.digits)) | def remove_num_method2(in_str: str) -> str:
return in_str.translate(str.maketrans(, , string.digits))<|docstring|>based on translate<|endoftext|> |
7c46042a7da61a34f21f8cbcb418be1533fbf0adac1446cebea6ad6c0000c03a | def remove_num_method3(in_str: str) -> str:
'based on replace method'
return ''.join((c for c in in_str if (not c.isdigit()))) | based on replace method | python/re/remove_num.py | remove_num_method3 | colin-zhou/mrfs | 8 | python | def remove_num_method3(in_str: str) -> str:
return .join((c for c in in_str if (not c.isdigit()))) | def remove_num_method3(in_str: str) -> str:
return .join((c for c in in_str if (not c.isdigit())))<|docstring|>based on replace method<|endoftext|> |
73319c4371c8d8eadc9f059ea4b4c1238fa8eb47d4c8f0d69b7a2861164e8b8d | def procedural(it, f):
'Procedural topology.\n\n - it: iterator of node labels\n - f: label -> [label] -- defines the edges\n '
return {i: f(i) for i in it} | Procedural topology.
- it: iterator of node labels
- f: label -> [label] -- defines the edges | topo.py | procedural | AnotherKamila/distributed-algorithms-emulator | 0 | python | def procedural(it, f):
'Procedural topology.\n\n - it: iterator of node labels\n - f: label -> [label] -- defines the edges\n '
return {i: f(i) for i in it} | def procedural(it, f):
'Procedural topology.\n\n - it: iterator of node labels\n - f: label -> [label] -- defines the edges\n '
return {i: f(i) for i in it}<|docstring|>Procedural topology.
- it: iterator of node labels
- f: label -> [label] -- defines the edges<|endoftext|> |
584fcd2e4d9ebbc0790736d05202dcb6a5075c74be3b5a5cf3e01d7b4bf4ff4d | def random(n, mind):
"Does not guarantee that it's connected (TODO)!"
return bidirectional({i: sample(range(n), mind) for i in range(n)}) | Does not guarantee that it's connected (TODO)! | topo.py | random | AnotherKamila/distributed-algorithms-emulator | 0 | python | def random(n, mind):
return bidirectional({i: sample(range(n), mind) for i in range(n)}) | def random(n, mind):
return bidirectional({i: sample(range(n), mind) for i in range(n)})<|docstring|>Does not guarantee that it's connected (TODO)!<|endoftext|> |
ee7a2dfd5cb5fe749e54743c40c31ae660cb16d4e43172cd6f36457feed74448 | @cuda.jit('(float32[:], float32[:])', device=True, inline=True)
def inter(rbbox1, rbbox2):
'Compute intersection of two rotated boxes.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n\n Returns:\n float: Intersection of two rotated boxes.\n '
corners1 = cuda.local.array((8,), dtype=numba.float32)
corners2 = cuda.local.array((8,), dtype=numba.float32)
intersection_corners = cuda.local.array((16,), dtype=numba.float32)
rbbox_to_corners(corners1, rbbox1)
rbbox_to_corners(corners2, rbbox2)
num_intersection = quadrilateral_intersection(corners1, corners2, intersection_corners)
sort_vertex_in_convex_polygon(intersection_corners, num_intersection)
return area(intersection_corners, num_intersection) | Compute intersection of two rotated boxes.
Args:
rbox1 (np.ndarray, shape=[5]): Rotated 2d box.
rbox2 (np.ndarray, shape=[5]): Rotated 2d box.
Returns:
float: Intersection of two rotated boxes. | utils/overlap.py | inter | Sliverk/hybridAveragePrecision | 0 | python | @cuda.jit('(float32[:], float32[:])', device=True, inline=True)
def inter(rbbox1, rbbox2):
'Compute intersection of two rotated boxes.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n\n Returns:\n float: Intersection of two rotated boxes.\n '
corners1 = cuda.local.array((8,), dtype=numba.float32)
corners2 = cuda.local.array((8,), dtype=numba.float32)
intersection_corners = cuda.local.array((16,), dtype=numba.float32)
rbbox_to_corners(corners1, rbbox1)
rbbox_to_corners(corners2, rbbox2)
num_intersection = quadrilateral_intersection(corners1, corners2, intersection_corners)
sort_vertex_in_convex_polygon(intersection_corners, num_intersection)
return area(intersection_corners, num_intersection) | @cuda.jit('(float32[:], float32[:])', device=True, inline=True)
def inter(rbbox1, rbbox2):
'Compute intersection of two rotated boxes.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n\n Returns:\n float: Intersection of two rotated boxes.\n '
corners1 = cuda.local.array((8,), dtype=numba.float32)
corners2 = cuda.local.array((8,), dtype=numba.float32)
intersection_corners = cuda.local.array((16,), dtype=numba.float32)
rbbox_to_corners(corners1, rbbox1)
rbbox_to_corners(corners2, rbbox2)
num_intersection = quadrilateral_intersection(corners1, corners2, intersection_corners)
sort_vertex_in_convex_polygon(intersection_corners, num_intersection)
return area(intersection_corners, num_intersection)<|docstring|>Compute intersection of two rotated boxes.
Args:
rbox1 (np.ndarray, shape=[5]): Rotated 2d box.
rbox2 (np.ndarray, shape=[5]): Rotated 2d box.
Returns:
float: Intersection of two rotated boxes.<|endoftext|> |
6a693b1f3374d642f8bb5495b95aef0abf5af91b790ba4bc090d4514b622b11b | @cuda.jit('(float32[:], float32[:], int32)', device=True, inline=True)
def devRotateIoUEval(rbox1, rbox2, criterion=(- 1)):
'Compute rotated iou on device.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n float: iou between two input boxes.\n '
area1 = (rbox1[2] * rbox1[3])
area2 = (rbox2[2] * rbox2[3])
area_inter = inter(rbox1, rbox2)
if (criterion == (- 1)):
return (area_inter / ((area1 + area2) - area_inter))
elif (criterion == 0):
return (area_inter / area1)
elif (criterion == 1):
return (area_inter / area2)
else:
return area_inter | Compute rotated iou on device.
Args:
rbox1 (np.ndarray, shape=[5]): Rotated 2d box.
rbox2 (np.ndarray, shape=[5]): Rotated 2d box.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`.
Returns:
float: iou between two input boxes. | utils/overlap.py | devRotateIoUEval | Sliverk/hybridAveragePrecision | 0 | python | @cuda.jit('(float32[:], float32[:], int32)', device=True, inline=True)
def devRotateIoUEval(rbox1, rbox2, criterion=(- 1)):
'Compute rotated iou on device.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n float: iou between two input boxes.\n '
area1 = (rbox1[2] * rbox1[3])
area2 = (rbox2[2] * rbox2[3])
area_inter = inter(rbox1, rbox2)
if (criterion == (- 1)):
return (area_inter / ((area1 + area2) - area_inter))
elif (criterion == 0):
return (area_inter / area1)
elif (criterion == 1):
return (area_inter / area2)
else:
return area_inter | @cuda.jit('(float32[:], float32[:], int32)', device=True, inline=True)
def devRotateIoUEval(rbox1, rbox2, criterion=(- 1)):
'Compute rotated iou on device.\n\n Args:\n rbox1 (np.ndarray, shape=[5]): Rotated 2d box.\n rbox2 (np.ndarray, shape=[5]): Rotated 2d box.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n float: iou between two input boxes.\n '
area1 = (rbox1[2] * rbox1[3])
area2 = (rbox2[2] * rbox2[3])
area_inter = inter(rbox1, rbox2)
if (criterion == (- 1)):
return (area_inter / ((area1 + area2) - area_inter))
elif (criterion == 0):
return (area_inter / area1)
elif (criterion == 1):
return (area_inter / area2)
else:
return area_inter<|docstring|>Compute rotated iou on device.
Args:
rbox1 (np.ndarray, shape=[5]): Rotated 2d box.
rbox2 (np.ndarray, shape=[5]): Rotated 2d box.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`.
Returns:
float: iou between two input boxes.<|endoftext|> |
08fa9733c1a4929e1638d1dc3aafae96b6dd5c0e77e9482abf00f4c1222ef2e7 | @cuda.jit('(int64, int64, float32[:], float32[:], float32[:], int32)', fastmath=False)
def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=(- 1)):
'Kernel of computing rotated iou.\n\n Args:\n N (int): The number of boxes.\n K (int): The number of query boxes.\n dev_boxes (np.ndarray): Boxes on device.\n dev_query_boxes (np.ndarray): Query boxes on device.\n dev_iou (np.ndarray): Computed iou to return.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n '
threadsPerBlock = (8 * 8)
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min((N - (row_start * threadsPerBlock)), threadsPerBlock)
col_size = min((K - (col_start * threadsPerBlock)), threadsPerBlock)
block_boxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
block_qboxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
dev_query_box_idx = ((threadsPerBlock * col_start) + tx)
dev_box_idx = ((threadsPerBlock * row_start) + tx)
if (tx < col_size):
block_qboxes[((tx * 5) + 0)] = dev_query_boxes[((dev_query_box_idx * 5) + 0)]
block_qboxes[((tx * 5) + 1)] = dev_query_boxes[((dev_query_box_idx * 5) + 1)]
block_qboxes[((tx * 5) + 2)] = dev_query_boxes[((dev_query_box_idx * 5) + 2)]
block_qboxes[((tx * 5) + 3)] = dev_query_boxes[((dev_query_box_idx * 5) + 3)]
block_qboxes[((tx * 5) + 4)] = dev_query_boxes[((dev_query_box_idx * 5) + 4)]
if (tx < row_size):
block_boxes[((tx * 5) + 0)] = dev_boxes[((dev_box_idx * 5) + 0)]
block_boxes[((tx * 5) + 1)] = dev_boxes[((dev_box_idx * 5) + 1)]
block_boxes[((tx * 5) + 2)] = dev_boxes[((dev_box_idx * 5) + 2)]
block_boxes[((tx * 5) + 3)] = dev_boxes[((dev_box_idx * 5) + 3)]
block_boxes[((tx * 5) + 4)] = dev_boxes[((dev_box_idx * 5) + 4)]
cuda.syncthreads()
if (tx < row_size):
for i in range(col_size):
offset = (((((row_start * threadsPerBlock) * K) + (col_start * threadsPerBlock)) + (tx * K)) + i)
dev_iou[offset] = devRotateIoUEval(block_qboxes[(i * 5):((i * 5) + 5)], block_boxes[(tx * 5):((tx * 5) + 5)], criterion) | Kernel of computing rotated iou.
Args:
N (int): The number of boxes.
K (int): The number of query boxes.
dev_boxes (np.ndarray): Boxes on device.
dev_query_boxes (np.ndarray): Query boxes on device.
dev_iou (np.ndarray): Computed iou to return.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`. | utils/overlap.py | rotate_iou_kernel_eval | Sliverk/hybridAveragePrecision | 0 | python | @cuda.jit('(int64, int64, float32[:], float32[:], float32[:], int32)', fastmath=False)
def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=(- 1)):
'Kernel of computing rotated iou.\n\n Args:\n N (int): The number of boxes.\n K (int): The number of query boxes.\n dev_boxes (np.ndarray): Boxes on device.\n dev_query_boxes (np.ndarray): Query boxes on device.\n dev_iou (np.ndarray): Computed iou to return.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n '
threadsPerBlock = (8 * 8)
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min((N - (row_start * threadsPerBlock)), threadsPerBlock)
col_size = min((K - (col_start * threadsPerBlock)), threadsPerBlock)
block_boxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
block_qboxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
dev_query_box_idx = ((threadsPerBlock * col_start) + tx)
dev_box_idx = ((threadsPerBlock * row_start) + tx)
if (tx < col_size):
block_qboxes[((tx * 5) + 0)] = dev_query_boxes[((dev_query_box_idx * 5) + 0)]
block_qboxes[((tx * 5) + 1)] = dev_query_boxes[((dev_query_box_idx * 5) + 1)]
block_qboxes[((tx * 5) + 2)] = dev_query_boxes[((dev_query_box_idx * 5) + 2)]
block_qboxes[((tx * 5) + 3)] = dev_query_boxes[((dev_query_box_idx * 5) + 3)]
block_qboxes[((tx * 5) + 4)] = dev_query_boxes[((dev_query_box_idx * 5) + 4)]
if (tx < row_size):
block_boxes[((tx * 5) + 0)] = dev_boxes[((dev_box_idx * 5) + 0)]
block_boxes[((tx * 5) + 1)] = dev_boxes[((dev_box_idx * 5) + 1)]
block_boxes[((tx * 5) + 2)] = dev_boxes[((dev_box_idx * 5) + 2)]
block_boxes[((tx * 5) + 3)] = dev_boxes[((dev_box_idx * 5) + 3)]
block_boxes[((tx * 5) + 4)] = dev_boxes[((dev_box_idx * 5) + 4)]
cuda.syncthreads()
if (tx < row_size):
for i in range(col_size):
offset = (((((row_start * threadsPerBlock) * K) + (col_start * threadsPerBlock)) + (tx * K)) + i)
dev_iou[offset] = devRotateIoUEval(block_qboxes[(i * 5):((i * 5) + 5)], block_boxes[(tx * 5):((tx * 5) + 5)], criterion) | @cuda.jit('(int64, int64, float32[:], float32[:], float32[:], int32)', fastmath=False)
def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=(- 1)):
'Kernel of computing rotated iou.\n\n Args:\n N (int): The number of boxes.\n K (int): The number of query boxes.\n dev_boxes (np.ndarray): Boxes on device.\n dev_query_boxes (np.ndarray): Query boxes on device.\n dev_iou (np.ndarray): Computed iou to return.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n '
threadsPerBlock = (8 * 8)
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min((N - (row_start * threadsPerBlock)), threadsPerBlock)
col_size = min((K - (col_start * threadsPerBlock)), threadsPerBlock)
block_boxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
block_qboxes = cuda.shared.array(shape=((64 * 5),), dtype=numba.float32)
dev_query_box_idx = ((threadsPerBlock * col_start) + tx)
dev_box_idx = ((threadsPerBlock * row_start) + tx)
if (tx < col_size):
block_qboxes[((tx * 5) + 0)] = dev_query_boxes[((dev_query_box_idx * 5) + 0)]
block_qboxes[((tx * 5) + 1)] = dev_query_boxes[((dev_query_box_idx * 5) + 1)]
block_qboxes[((tx * 5) + 2)] = dev_query_boxes[((dev_query_box_idx * 5) + 2)]
block_qboxes[((tx * 5) + 3)] = dev_query_boxes[((dev_query_box_idx * 5) + 3)]
block_qboxes[((tx * 5) + 4)] = dev_query_boxes[((dev_query_box_idx * 5) + 4)]
if (tx < row_size):
block_boxes[((tx * 5) + 0)] = dev_boxes[((dev_box_idx * 5) + 0)]
block_boxes[((tx * 5) + 1)] = dev_boxes[((dev_box_idx * 5) + 1)]
block_boxes[((tx * 5) + 2)] = dev_boxes[((dev_box_idx * 5) + 2)]
block_boxes[((tx * 5) + 3)] = dev_boxes[((dev_box_idx * 5) + 3)]
block_boxes[((tx * 5) + 4)] = dev_boxes[((dev_box_idx * 5) + 4)]
cuda.syncthreads()
if (tx < row_size):
for i in range(col_size):
offset = (((((row_start * threadsPerBlock) * K) + (col_start * threadsPerBlock)) + (tx * K)) + i)
dev_iou[offset] = devRotateIoUEval(block_qboxes[(i * 5):((i * 5) + 5)], block_boxes[(tx * 5):((tx * 5) + 5)], criterion)<|docstring|>Kernel of computing rotated iou.
Args:
N (int): The number of boxes.
K (int): The number of query boxes.
dev_boxes (np.ndarray): Boxes on device.
dev_query_boxes (np.ndarray): Query boxes on device.
dev_iou (np.ndarray): Computed iou to return.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`.<|endoftext|> |
163b0c6e71f6ec54e515961ec594ca72445b7051e23976fc72f4ed4a2b94e925 | def rotate_iou_gpu_eval(boxes, query_boxes, criterion=(- 1), device_id=0):
'Rotated box iou running in gpu. 500x faster than cpu version (take 5ms\n in one example with numba.cuda code). convert from [this project](\n https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).\n\n Args:\n boxes (torch.Tensor): rbboxes. format: centers, dims,\n angles(clockwise when positive) with the shape of [N, 5].\n query_boxes (float tensor: [K, 5]): rbboxes to compute iou with boxes.\n device_id (int, optional): Defaults to 0. Device to use.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n np.ndarray: IoU results.\n '
boxes = boxes.astype(np.float32)
query_boxes = query_boxes.astype(np.float32)
N = boxes.shape[0]
K = query_boxes.shape[0]
iou = np.zeros((N, K), dtype=np.float32)
if ((N == 0) or (K == 0)):
return iou
threadsPerBlock = (8 * 8)
cuda.select_device(device_id)
blockspergrid = (div_up(N, threadsPerBlock), div_up(K, threadsPerBlock))
stream = cuda.stream()
with stream.auto_synchronize():
boxes_dev = cuda.to_device(boxes.reshape([(- 1)]), stream)
query_boxes_dev = cuda.to_device(query_boxes.reshape([(- 1)]), stream)
iou_dev = cuda.to_device(iou.reshape([(- 1)]), stream)
rotate_iou_kernel_eval[(blockspergrid, threadsPerBlock, stream)](N, K, boxes_dev, query_boxes_dev, iou_dev, criterion)
iou_dev.copy_to_host(iou.reshape([(- 1)]), stream=stream)
return iou.astype(boxes.dtype) | Rotated box iou running in gpu. 500x faster than cpu version (take 5ms
in one example with numba.cuda code). convert from [this project](
https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).
Args:
boxes (torch.Tensor): rbboxes. format: centers, dims,
angles(clockwise when positive) with the shape of [N, 5].
query_boxes (float tensor: [K, 5]): rbboxes to compute iou with boxes.
device_id (int, optional): Defaults to 0. Device to use.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`.
Returns:
np.ndarray: IoU results. | utils/overlap.py | rotate_iou_gpu_eval | Sliverk/hybridAveragePrecision | 0 | python | def rotate_iou_gpu_eval(boxes, query_boxes, criterion=(- 1), device_id=0):
'Rotated box iou running in gpu. 500x faster than cpu version (take 5ms\n in one example with numba.cuda code). convert from [this project](\n https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).\n\n Args:\n boxes (torch.Tensor): rbboxes. format: centers, dims,\n angles(clockwise when positive) with the shape of [N, 5].\n query_boxes (float tensor: [K, 5]): rbboxes to compute iou with boxes.\n device_id (int, optional): Defaults to 0. Device to use.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n np.ndarray: IoU results.\n '
boxes = boxes.astype(np.float32)
query_boxes = query_boxes.astype(np.float32)
N = boxes.shape[0]
K = query_boxes.shape[0]
iou = np.zeros((N, K), dtype=np.float32)
if ((N == 0) or (K == 0)):
return iou
threadsPerBlock = (8 * 8)
cuda.select_device(device_id)
blockspergrid = (div_up(N, threadsPerBlock), div_up(K, threadsPerBlock))
stream = cuda.stream()
with stream.auto_synchronize():
boxes_dev = cuda.to_device(boxes.reshape([(- 1)]), stream)
query_boxes_dev = cuda.to_device(query_boxes.reshape([(- 1)]), stream)
iou_dev = cuda.to_device(iou.reshape([(- 1)]), stream)
rotate_iou_kernel_eval[(blockspergrid, threadsPerBlock, stream)](N, K, boxes_dev, query_boxes_dev, iou_dev, criterion)
iou_dev.copy_to_host(iou.reshape([(- 1)]), stream=stream)
return iou.astype(boxes.dtype) | def rotate_iou_gpu_eval(boxes, query_boxes, criterion=(- 1), device_id=0):
'Rotated box iou running in gpu. 500x faster than cpu version (take 5ms\n in one example with numba.cuda code). convert from [this project](\n https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).\n\n Args:\n boxes (torch.Tensor): rbboxes. format: centers, dims,\n angles(clockwise when positive) with the shape of [N, 5].\n query_boxes (float tensor: [K, 5]): rbboxes to compute iou with boxes.\n device_id (int, optional): Defaults to 0. Device to use.\n criterion (int, optional): Indicate different type of iou.\n -1 indicate `area_inter / (area1 + area2 - area_inter)`,\n 0 indicate `area_inter / area1`,\n 1 indicate `area_inter / area2`.\n\n Returns:\n np.ndarray: IoU results.\n '
boxes = boxes.astype(np.float32)
query_boxes = query_boxes.astype(np.float32)
N = boxes.shape[0]
K = query_boxes.shape[0]
iou = np.zeros((N, K), dtype=np.float32)
if ((N == 0) or (K == 0)):
return iou
threadsPerBlock = (8 * 8)
cuda.select_device(device_id)
blockspergrid = (div_up(N, threadsPerBlock), div_up(K, threadsPerBlock))
stream = cuda.stream()
with stream.auto_synchronize():
boxes_dev = cuda.to_device(boxes.reshape([(- 1)]), stream)
query_boxes_dev = cuda.to_device(query_boxes.reshape([(- 1)]), stream)
iou_dev = cuda.to_device(iou.reshape([(- 1)]), stream)
rotate_iou_kernel_eval[(blockspergrid, threadsPerBlock, stream)](N, K, boxes_dev, query_boxes_dev, iou_dev, criterion)
iou_dev.copy_to_host(iou.reshape([(- 1)]), stream=stream)
return iou.astype(boxes.dtype)<|docstring|>Rotated box iou running in gpu. 500x faster than cpu version (take 5ms
in one example with numba.cuda code). convert from [this project](
https://github.com/hongzhenwang/RRPN-revise/tree/master/lib/rotation).
Args:
boxes (torch.Tensor): rbboxes. format: centers, dims,
angles(clockwise when positive) with the shape of [N, 5].
query_boxes (float tensor: [K, 5]): rbboxes to compute iou with boxes.
device_id (int, optional): Defaults to 0. Device to use.
criterion (int, optional): Indicate different type of iou.
-1 indicate `area_inter / (area1 + area2 - area_inter)`,
0 indicate `area_inter / area1`,
1 indicate `area_inter / area2`.
Returns:
np.ndarray: IoU results.<|endoftext|> |
2dec860b995f1224f5fa8585578b230e03c9dbcf98c89e095133b8bcdcd2c290 | def calculate_iou_partly(gt_annos, dt_annos, metric, num_parts=200):
'Fast iou algorithm. this function can be used independently to do result\n analysis. Must be used in CAMERA coordinate system.\n\n Args:\n gt_annos (dict): Must from get_label_annos() in kitti_common.py.\n dt_annos (dict): Must from get_label_annos() in kitti_common.py.\n metric (int): Eval type. 0: bbox, 1: bev, 2: 3d.\n num_parts (int): A parameter for fast calculate algorithm.\n '
assert (len(gt_annos) == len(dt_annos))
total_dt_num = np.stack([len(a['name']) for a in dt_annos], 0)
total_gt_num = np.stack([len(a['name']) for a in gt_annos], 0)
num_examples = len(gt_annos)
split_parts = get_split_parts(num_examples, num_parts)
parted_overlaps = []
example_idx = 0
for num_part in split_parts:
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
if (metric == 0):
gt_boxes = np.concatenate([a['bbox'] for a in gt_annos_part], 0)
dt_boxes = np.concatenate([a['bbox'] for a in dt_annos_part], 0)
overlap_part = image_box_overlap(gt_boxes, dt_boxes)
elif (metric == 1):
loc = np.concatenate([a['location'][(:, [0, 2])] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'][(:, [0, 2])] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = bev_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
elif (metric == 2):
loc = np.concatenate([a['location'] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = d3_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
else:
raise ValueError('unknown metric')
parted_overlaps.append(overlap_part)
example_idx += num_part
overlaps = []
example_idx = 0
for (j, num_part) in enumerate(split_parts):
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
(gt_num_idx, dt_num_idx) = (0, 0)
for i in range(num_part):
gt_box_num = total_gt_num[(example_idx + i)]
dt_box_num = total_dt_num[(example_idx + i)]
overlaps.append(parted_overlaps[j][(gt_num_idx:(gt_num_idx + gt_box_num), dt_num_idx:(dt_num_idx + dt_box_num))])
gt_num_idx += gt_box_num
dt_num_idx += dt_box_num
example_idx += num_part
return (overlaps, total_gt_num, total_dt_num) | Fast iou algorithm. this function can be used independently to do result
analysis. Must be used in CAMERA coordinate system.
Args:
gt_annos (dict): Must from get_label_annos() in kitti_common.py.
dt_annos (dict): Must from get_label_annos() in kitti_common.py.
metric (int): Eval type. 0: bbox, 1: bev, 2: 3d.
num_parts (int): A parameter for fast calculate algorithm. | utils/overlap.py | calculate_iou_partly | Sliverk/hybridAveragePrecision | 0 | python | def calculate_iou_partly(gt_annos, dt_annos, metric, num_parts=200):
'Fast iou algorithm. this function can be used independently to do result\n analysis. Must be used in CAMERA coordinate system.\n\n Args:\n gt_annos (dict): Must from get_label_annos() in kitti_common.py.\n dt_annos (dict): Must from get_label_annos() in kitti_common.py.\n metric (int): Eval type. 0: bbox, 1: bev, 2: 3d.\n num_parts (int): A parameter for fast calculate algorithm.\n '
assert (len(gt_annos) == len(dt_annos))
total_dt_num = np.stack([len(a['name']) for a in dt_annos], 0)
total_gt_num = np.stack([len(a['name']) for a in gt_annos], 0)
num_examples = len(gt_annos)
split_parts = get_split_parts(num_examples, num_parts)
parted_overlaps = []
example_idx = 0
for num_part in split_parts:
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
if (metric == 0):
gt_boxes = np.concatenate([a['bbox'] for a in gt_annos_part], 0)
dt_boxes = np.concatenate([a['bbox'] for a in dt_annos_part], 0)
overlap_part = image_box_overlap(gt_boxes, dt_boxes)
elif (metric == 1):
loc = np.concatenate([a['location'][(:, [0, 2])] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'][(:, [0, 2])] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = bev_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
elif (metric == 2):
loc = np.concatenate([a['location'] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = d3_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
else:
raise ValueError('unknown metric')
parted_overlaps.append(overlap_part)
example_idx += num_part
overlaps = []
example_idx = 0
for (j, num_part) in enumerate(split_parts):
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
(gt_num_idx, dt_num_idx) = (0, 0)
for i in range(num_part):
gt_box_num = total_gt_num[(example_idx + i)]
dt_box_num = total_dt_num[(example_idx + i)]
overlaps.append(parted_overlaps[j][(gt_num_idx:(gt_num_idx + gt_box_num), dt_num_idx:(dt_num_idx + dt_box_num))])
gt_num_idx += gt_box_num
dt_num_idx += dt_box_num
example_idx += num_part
return (overlaps, total_gt_num, total_dt_num) | def calculate_iou_partly(gt_annos, dt_annos, metric, num_parts=200):
'Fast iou algorithm. this function can be used independently to do result\n analysis. Must be used in CAMERA coordinate system.\n\n Args:\n gt_annos (dict): Must from get_label_annos() in kitti_common.py.\n dt_annos (dict): Must from get_label_annos() in kitti_common.py.\n metric (int): Eval type. 0: bbox, 1: bev, 2: 3d.\n num_parts (int): A parameter for fast calculate algorithm.\n '
assert (len(gt_annos) == len(dt_annos))
total_dt_num = np.stack([len(a['name']) for a in dt_annos], 0)
total_gt_num = np.stack([len(a['name']) for a in gt_annos], 0)
num_examples = len(gt_annos)
split_parts = get_split_parts(num_examples, num_parts)
parted_overlaps = []
example_idx = 0
for num_part in split_parts:
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
if (metric == 0):
gt_boxes = np.concatenate([a['bbox'] for a in gt_annos_part], 0)
dt_boxes = np.concatenate([a['bbox'] for a in dt_annos_part], 0)
overlap_part = image_box_overlap(gt_boxes, dt_boxes)
elif (metric == 1):
loc = np.concatenate([a['location'][(:, [0, 2])] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'][(:, [0, 2])] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'][(:, [0, 2])] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = bev_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
elif (metric == 2):
loc = np.concatenate([a['location'] for a in gt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in gt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in gt_annos_part], 0)
gt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
loc = np.concatenate([a['location'] for a in dt_annos_part], 0)
dims = np.concatenate([a['dimensions'] for a in dt_annos_part], 0)
rots = np.concatenate([a['rotation_y'] for a in dt_annos_part], 0)
dt_boxes = np.concatenate([loc, dims, rots[(..., np.newaxis)]], axis=1)
overlap_part = d3_box_overlap(gt_boxes, dt_boxes).astype(np.float64)
else:
raise ValueError('unknown metric')
parted_overlaps.append(overlap_part)
example_idx += num_part
overlaps = []
example_idx = 0
for (j, num_part) in enumerate(split_parts):
gt_annos_part = gt_annos[example_idx:(example_idx + num_part)]
dt_annos_part = dt_annos[example_idx:(example_idx + num_part)]
(gt_num_idx, dt_num_idx) = (0, 0)
for i in range(num_part):
gt_box_num = total_gt_num[(example_idx + i)]
dt_box_num = total_dt_num[(example_idx + i)]
overlaps.append(parted_overlaps[j][(gt_num_idx:(gt_num_idx + gt_box_num), dt_num_idx:(dt_num_idx + dt_box_num))])
gt_num_idx += gt_box_num
dt_num_idx += dt_box_num
example_idx += num_part
return (overlaps, total_gt_num, total_dt_num)<|docstring|>Fast iou algorithm. this function can be used independently to do result
analysis. Must be used in CAMERA coordinate system.
Args:
gt_annos (dict): Must from get_label_annos() in kitti_common.py.
dt_annos (dict): Must from get_label_annos() in kitti_common.py.
metric (int): Eval type. 0: bbox, 1: bev, 2: 3d.
num_parts (int): A parameter for fast calculate algorithm.<|endoftext|> |
521b6cd073fd0450fb67e75597069ad621509e445d10039992dd9c529df74f8f | async def update(self, extend_query: dict={}, include_deleted: bool=False, only_fields: Optional[List['str']]=None):
' Saves only the changed fields leaving other fields alone '
iii = self.execute_hooks('pre_save', self.instance, created=False)
dd = convert_decimal(iii.dict(exclude_unset=True, by_alias=True))
if ('_id' not in dd):
raise AttributeError('Can not update document without _id')
dd_id = dd['_id']
if isinstance(dd_id, str):
dd_id = ObjectId(dd_id)
del dd['_id']
if (only_fields and (len(only_fields) > 0)):
dd = dict([(key, val) for (key, val) in dd.items() if (key in only_fields)])
softdel = ({self.softdelete(): False} if (self.softdelete() and (not include_deleted)) else {})
db = (await self.__mongo)
ret = db.find_one_and_update({'_id': dd_id, **softdel, **self.get_parsed_query(extend_query)}, {'$set': dd})
iii = self.execute_hooks('post_save', iii, created=False)
return ret | Saves only the changed fields leaving other fields alone | odim/mongo.py | update | jhuseinovic/odim | 0 | python | async def update(self, extend_query: dict={}, include_deleted: bool=False, only_fields: Optional[List['str']]=None):
' '
iii = self.execute_hooks('pre_save', self.instance, created=False)
dd = convert_decimal(iii.dict(exclude_unset=True, by_alias=True))
if ('_id' not in dd):
raise AttributeError('Can not update document without _id')
dd_id = dd['_id']
if isinstance(dd_id, str):
dd_id = ObjectId(dd_id)
del dd['_id']
if (only_fields and (len(only_fields) > 0)):
dd = dict([(key, val) for (key, val) in dd.items() if (key in only_fields)])
softdel = ({self.softdelete(): False} if (self.softdelete() and (not include_deleted)) else {})
db = (await self.__mongo)
ret = db.find_one_and_update({'_id': dd_id, **softdel, **self.get_parsed_query(extend_query)}, {'$set': dd})
iii = self.execute_hooks('post_save', iii, created=False)
return ret | async def update(self, extend_query: dict={}, include_deleted: bool=False, only_fields: Optional[List['str']]=None):
' '
iii = self.execute_hooks('pre_save', self.instance, created=False)
dd = convert_decimal(iii.dict(exclude_unset=True, by_alias=True))
if ('_id' not in dd):
raise AttributeError('Can not update document without _id')
dd_id = dd['_id']
if isinstance(dd_id, str):
dd_id = ObjectId(dd_id)
del dd['_id']
if (only_fields and (len(only_fields) > 0)):
dd = dict([(key, val) for (key, val) in dd.items() if (key in only_fields)])
softdel = ({self.softdelete(): False} if (self.softdelete() and (not include_deleted)) else {})
db = (await self.__mongo)
ret = db.find_one_and_update({'_id': dd_id, **softdel, **self.get_parsed_query(extend_query)}, {'$set': dd})
iii = self.execute_hooks('post_save', iii, created=False)
return ret<|docstring|>Saves only the changed fields leaving other fields alone<|endoftext|> |
313b7329012cff25d7a2472e26f2c800dfb47344083691eb696214e4e9d2633b | def combine_metadata(dataset_metadata: List[Dict], append_to_list: bool=True) -> Dict:
'\n Merge a list of dictionaries\n\n The merge is performed in such a way, that only keys which\n are present in **all** dictionaries are kept in the final result.\n\n If lists are encountered, the values of the result will be the\n concatenation of all list values in the order of the supplied dictionary list.\n This behaviour may be changed by using append_to_list\n\n Parameters\n ----------\n dataset_metadata\n The list of dictionaries (usually metadata) to be combined.\n append_to_list\n If True, all values are concatenated. If False, only unique values are kept\n '
meta = _combine_metadata(dataset_metadata, append_to_list)
return _remove_invalids(meta) | Merge a list of dictionaries
The merge is performed in such a way, that only keys which
are present in **all** dictionaries are kept in the final result.
If lists are encountered, the values of the result will be the
concatenation of all list values in the order of the supplied dictionary list.
This behaviour may be changed by using append_to_list
Parameters
----------
dataset_metadata
The list of dictionaries (usually metadata) to be combined.
append_to_list
If True, all values are concatenated. If False, only unique values are kept | kartothek/io_components/utils.py | combine_metadata | martin-haffner-by/kartothek | 171 | python | def combine_metadata(dataset_metadata: List[Dict], append_to_list: bool=True) -> Dict:
'\n Merge a list of dictionaries\n\n The merge is performed in such a way, that only keys which\n are present in **all** dictionaries are kept in the final result.\n\n If lists are encountered, the values of the result will be the\n concatenation of all list values in the order of the supplied dictionary list.\n This behaviour may be changed by using append_to_list\n\n Parameters\n ----------\n dataset_metadata\n The list of dictionaries (usually metadata) to be combined.\n append_to_list\n If True, all values are concatenated. If False, only unique values are kept\n '
meta = _combine_metadata(dataset_metadata, append_to_list)
return _remove_invalids(meta) | def combine_metadata(dataset_metadata: List[Dict], append_to_list: bool=True) -> Dict:
'\n Merge a list of dictionaries\n\n The merge is performed in such a way, that only keys which\n are present in **all** dictionaries are kept in the final result.\n\n If lists are encountered, the values of the result will be the\n concatenation of all list values in the order of the supplied dictionary list.\n This behaviour may be changed by using append_to_list\n\n Parameters\n ----------\n dataset_metadata\n The list of dictionaries (usually metadata) to be combined.\n append_to_list\n If True, all values are concatenated. If False, only unique values are kept\n '
meta = _combine_metadata(dataset_metadata, append_to_list)
return _remove_invalids(meta)<|docstring|>Merge a list of dictionaries
The merge is performed in such a way, that only keys which
are present in **all** dictionaries are kept in the final result.
If lists are encountered, the values of the result will be the
concatenation of all list values in the order of the supplied dictionary list.
This behaviour may be changed by using append_to_list
Parameters
----------
dataset_metadata
The list of dictionaries (usually metadata) to be combined.
append_to_list
If True, all values are concatenated. If False, only unique values are kept<|endoftext|> |
694b13883b80535199559e34e9555022405f9fa15ea17f2f9f5287b40c07662f | def normalize_arg(arg_name, old_value):
'\n Normalizes an argument according to pre-defined types\n\n Type A:\n\n * "partition_on"\n * "delete_scope"\n * "secondary_indices"\n * "dispatch_by"\n\n will be converted to a list. If it is None, an empty list will be created\n\n Type B:\n * "store"\n\n Will be converted to a callable returning\n\n :meta private:\n '
def _make_list(_args):
if isinstance(_args, (str, bytes, int, float)):
return [_args]
if (_args is None):
return []
if isinstance(_args, (set, frozenset, dict)):
raise ValueError('{} is incompatible for normalisation.'.format(type(_args)))
return list(_args)
if (arg_name in _NORMALIZE_ARGS_LIST):
if (old_value is None):
return []
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif (arg_name == 'dispatch_by'):
if (old_value is None):
return old_value
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif ((arg_name == 'store') and (old_value is not None)):
return lazy_store(old_value)
return old_value | Normalizes an argument according to pre-defined types
Type A:
* "partition_on"
* "delete_scope"
* "secondary_indices"
* "dispatch_by"
will be converted to a list. If it is None, an empty list will be created
Type B:
* "store"
Will be converted to a callable returning
:meta private: | kartothek/io_components/utils.py | normalize_arg | martin-haffner-by/kartothek | 171 | python | def normalize_arg(arg_name, old_value):
'\n Normalizes an argument according to pre-defined types\n\n Type A:\n\n * "partition_on"\n * "delete_scope"\n * "secondary_indices"\n * "dispatch_by"\n\n will be converted to a list. If it is None, an empty list will be created\n\n Type B:\n * "store"\n\n Will be converted to a callable returning\n\n :meta private:\n '
def _make_list(_args):
if isinstance(_args, (str, bytes, int, float)):
return [_args]
if (_args is None):
return []
if isinstance(_args, (set, frozenset, dict)):
raise ValueError('{} is incompatible for normalisation.'.format(type(_args)))
return list(_args)
if (arg_name in _NORMALIZE_ARGS_LIST):
if (old_value is None):
return []
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif (arg_name == 'dispatch_by'):
if (old_value is None):
return old_value
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif ((arg_name == 'store') and (old_value is not None)):
return lazy_store(old_value)
return old_value | def normalize_arg(arg_name, old_value):
'\n Normalizes an argument according to pre-defined types\n\n Type A:\n\n * "partition_on"\n * "delete_scope"\n * "secondary_indices"\n * "dispatch_by"\n\n will be converted to a list. If it is None, an empty list will be created\n\n Type B:\n * "store"\n\n Will be converted to a callable returning\n\n :meta private:\n '
def _make_list(_args):
if isinstance(_args, (str, bytes, int, float)):
return [_args]
if (_args is None):
return []
if isinstance(_args, (set, frozenset, dict)):
raise ValueError('{} is incompatible for normalisation.'.format(type(_args)))
return list(_args)
if (arg_name in _NORMALIZE_ARGS_LIST):
if (old_value is None):
return []
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif (arg_name == 'dispatch_by'):
if (old_value is None):
return old_value
elif isinstance(old_value, list):
return old_value
else:
return _make_list(old_value)
elif ((arg_name == 'store') and (old_value is not None)):
return lazy_store(old_value)
return old_value<|docstring|>Normalizes an argument according to pre-defined types
Type A:
* "partition_on"
* "delete_scope"
* "secondary_indices"
* "dispatch_by"
will be converted to a list. If it is None, an empty list will be created
Type B:
* "store"
Will be converted to a callable returning
:meta private:<|endoftext|> |
3c3134328d35cfd9558799db72ccd6f9a99f6ca06e86ad11ab7ff37968bf08a1 | def extract_duplicates(lst):
'\n Return all items of a list that occur more than once.\n\n Parameters\n ----------\n lst: List[Any]\n\n Returns\n -------\n lst: List[Any]\n '
return [item for (item, count) in collections.Counter(lst).items() if (count > 1)] | Return all items of a list that occur more than once.
Parameters
----------
lst: List[Any]
Returns
-------
lst: List[Any] | kartothek/io_components/utils.py | extract_duplicates | martin-haffner-by/kartothek | 171 | python | def extract_duplicates(lst):
'\n Return all items of a list that occur more than once.\n\n Parameters\n ----------\n lst: List[Any]\n\n Returns\n -------\n lst: List[Any]\n '
return [item for (item, count) in collections.Counter(lst).items() if (count > 1)] | def extract_duplicates(lst):
'\n Return all items of a list that occur more than once.\n\n Parameters\n ----------\n lst: List[Any]\n\n Returns\n -------\n lst: List[Any]\n '
return [item for (item, count) in collections.Counter(lst).items() if (count > 1)]<|docstring|>Return all items of a list that occur more than once.
Parameters
----------
lst: List[Any]
Returns
-------
lst: List[Any]<|endoftext|> |
29a3887cdde192efd57e8358709104a681de47c460f85d4e61dacf596171a042 | def align_categories(dfs, categoricals):
'\n Takes a list of dataframes with categorical columns and determines the superset\n of categories. All specified columns will then be cast to the same `pd.CategoricalDtype`\n\n Parameters\n ----------\n dfs: List[pd.DataFrame]\n A list of dataframes for which the categoricals should be aligned\n categoricals: List[str]\n Columns holding categoricals which should be aligned\n\n Returns\n -------\n List[pd.DataFrame]\n A list with aligned dataframes\n '
if (len(categoricals) == 0):
return dfs
col_dtype = {}
for column in categoricals:
position_largest_df = None
categories = set()
largest_df_categories = set()
for (ix, df) in enumerate(dfs):
ser = df[column]
if (not pd.api.types.is_categorical_dtype(ser)):
cats = ser.dropna().unique()
LOGGER.info('Encountered non-categorical type where categorical was expected\nFound at index position {ix} for column {col}\nDtypes: {dtypes}'.format(ix=ix, col=column, dtypes=df.dtypes))
else:
cats = ser.cat.categories
length = len(df)
if ((position_largest_df is None) or (length > position_largest_df[0])):
position_largest_df = (length, ix)
if (position_largest_df[1] == ix):
largest_df_categories = cats
categories.update(cats)
categories = (list(largest_df_categories) + sorted((set(categories) - set(largest_df_categories))))
cat_dtype = pd.api.types.CategoricalDtype(categories, ordered=False)
col_dtype[column] = cat_dtype
return_dfs = []
for df in dfs:
try:
new_df = df.astype(col_dtype, copy=False)
except ValueError as verr:
cat_types = {col: dtype.categories.dtype for (col, dtype) in col_dtype.items()}
if ('buffer source array is read-only' in str(verr)):
new_df = df.astype(cat_types)
new_df = new_df.astype(col_dtype)
else:
raise verr
return_dfs.append(new_df)
return return_dfs | Takes a list of dataframes with categorical columns and determines the superset
of categories. All specified columns will then be cast to the same `pd.CategoricalDtype`
Parameters
----------
dfs: List[pd.DataFrame]
A list of dataframes for which the categoricals should be aligned
categoricals: List[str]
Columns holding categoricals which should be aligned
Returns
-------
List[pd.DataFrame]
A list with aligned dataframes | kartothek/io_components/utils.py | align_categories | martin-haffner-by/kartothek | 171 | python | def align_categories(dfs, categoricals):
'\n Takes a list of dataframes with categorical columns and determines the superset\n of categories. All specified columns will then be cast to the same `pd.CategoricalDtype`\n\n Parameters\n ----------\n dfs: List[pd.DataFrame]\n A list of dataframes for which the categoricals should be aligned\n categoricals: List[str]\n Columns holding categoricals which should be aligned\n\n Returns\n -------\n List[pd.DataFrame]\n A list with aligned dataframes\n '
if (len(categoricals) == 0):
return dfs
col_dtype = {}
for column in categoricals:
position_largest_df = None
categories = set()
largest_df_categories = set()
for (ix, df) in enumerate(dfs):
ser = df[column]
if (not pd.api.types.is_categorical_dtype(ser)):
cats = ser.dropna().unique()
LOGGER.info('Encountered non-categorical type where categorical was expected\nFound at index position {ix} for column {col}\nDtypes: {dtypes}'.format(ix=ix, col=column, dtypes=df.dtypes))
else:
cats = ser.cat.categories
length = len(df)
if ((position_largest_df is None) or (length > position_largest_df[0])):
position_largest_df = (length, ix)
if (position_largest_df[1] == ix):
largest_df_categories = cats
categories.update(cats)
categories = (list(largest_df_categories) + sorted((set(categories) - set(largest_df_categories))))
cat_dtype = pd.api.types.CategoricalDtype(categories, ordered=False)
col_dtype[column] = cat_dtype
return_dfs = []
for df in dfs:
try:
new_df = df.astype(col_dtype, copy=False)
except ValueError as verr:
cat_types = {col: dtype.categories.dtype for (col, dtype) in col_dtype.items()}
if ('buffer source array is read-only' in str(verr)):
new_df = df.astype(cat_types)
new_df = new_df.astype(col_dtype)
else:
raise verr
return_dfs.append(new_df)
return return_dfs | def align_categories(dfs, categoricals):
'\n Takes a list of dataframes with categorical columns and determines the superset\n of categories. All specified columns will then be cast to the same `pd.CategoricalDtype`\n\n Parameters\n ----------\n dfs: List[pd.DataFrame]\n A list of dataframes for which the categoricals should be aligned\n categoricals: List[str]\n Columns holding categoricals which should be aligned\n\n Returns\n -------\n List[pd.DataFrame]\n A list with aligned dataframes\n '
if (len(categoricals) == 0):
return dfs
col_dtype = {}
for column in categoricals:
position_largest_df = None
categories = set()
largest_df_categories = set()
for (ix, df) in enumerate(dfs):
ser = df[column]
if (not pd.api.types.is_categorical_dtype(ser)):
cats = ser.dropna().unique()
LOGGER.info('Encountered non-categorical type where categorical was expected\nFound at index position {ix} for column {col}\nDtypes: {dtypes}'.format(ix=ix, col=column, dtypes=df.dtypes))
else:
cats = ser.cat.categories
length = len(df)
if ((position_largest_df is None) or (length > position_largest_df[0])):
position_largest_df = (length, ix)
if (position_largest_df[1] == ix):
largest_df_categories = cats
categories.update(cats)
categories = (list(largest_df_categories) + sorted((set(categories) - set(largest_df_categories))))
cat_dtype = pd.api.types.CategoricalDtype(categories, ordered=False)
col_dtype[column] = cat_dtype
return_dfs = []
for df in dfs:
try:
new_df = df.astype(col_dtype, copy=False)
except ValueError as verr:
cat_types = {col: dtype.categories.dtype for (col, dtype) in col_dtype.items()}
if ('buffer source array is read-only' in str(verr)):
new_df = df.astype(cat_types)
new_df = new_df.astype(col_dtype)
else:
raise verr
return_dfs.append(new_df)
return return_dfs<|docstring|>Takes a list of dataframes with categorical columns and determines the superset
of categories. All specified columns will then be cast to the same `pd.CategoricalDtype`
Parameters
----------
dfs: List[pd.DataFrame]
A list of dataframes for which the categoricals should be aligned
categoricals: List[str]
Columns holding categoricals which should be aligned
Returns
-------
List[pd.DataFrame]
A list with aligned dataframes<|endoftext|> |
b5237bf30c0a6d07edb24bc37c88b39ccac1083534be535dcadcc1921d97feb9 | def sort_values_categorical(df: pd.DataFrame, columns: Union[(List[str], str)]) -> pd.DataFrame:
'\n Sort a dataframe lexicographically by the categories of column `column`\n '
if (not isinstance(columns, list)):
columns = [columns]
for col in columns:
if pd.api.types.is_categorical_dtype(df[col]):
cat_accesor = df[col].cat
df[col] = cat_accesor.reorder_categories(sorted(cat_accesor.categories), ordered=True)
return df.sort_values(by=columns).reset_index(drop=True) | Sort a dataframe lexicographically by the categories of column `column` | kartothek/io_components/utils.py | sort_values_categorical | martin-haffner-by/kartothek | 171 | python | def sort_values_categorical(df: pd.DataFrame, columns: Union[(List[str], str)]) -> pd.DataFrame:
'\n \n '
if (not isinstance(columns, list)):
columns = [columns]
for col in columns:
if pd.api.types.is_categorical_dtype(df[col]):
cat_accesor = df[col].cat
df[col] = cat_accesor.reorder_categories(sorted(cat_accesor.categories), ordered=True)
return df.sort_values(by=columns).reset_index(drop=True) | def sort_values_categorical(df: pd.DataFrame, columns: Union[(List[str], str)]) -> pd.DataFrame:
'\n \n '
if (not isinstance(columns, list)):
columns = [columns]
for col in columns:
if pd.api.types.is_categorical_dtype(df[col]):
cat_accesor = df[col].cat
df[col] = cat_accesor.reorder_categories(sorted(cat_accesor.categories), ordered=True)
return df.sort_values(by=columns).reset_index(drop=True)<|docstring|>Sort a dataframe lexicographically by the categories of column `column`<|endoftext|> |
9201ea38e2342d98164d71ee4c03d4bd32ab63ecc977d0606cffbd4f20b66db5 | def check_single_table_dataset(dataset, expected_table=None):
'\n Raise if the given dataset is not a single-table dataset.\n\n Parameters\n ----------\n dataset: kartothek.core.dataset.DatasetMetadata\n The dataset to be validated\n expected_table: Optional[str]\n Ensure that the table in the dataset is the same as the given one.\n '
if (len(dataset.tables) > 1):
raise TypeError('Expected single table dataset but found dataset with tables: `{}`'.format(dataset.tables))
if (expected_table and (dataset.tables != [expected_table])):
raise TypeError('Unexpected table in dataset:\nFound:\t{}\nExpected:\t{}'.format(dataset.tables, expected_table)) | Raise if the given dataset is not a single-table dataset.
Parameters
----------
dataset: kartothek.core.dataset.DatasetMetadata
The dataset to be validated
expected_table: Optional[str]
Ensure that the table in the dataset is the same as the given one. | kartothek/io_components/utils.py | check_single_table_dataset | martin-haffner-by/kartothek | 171 | python | def check_single_table_dataset(dataset, expected_table=None):
'\n Raise if the given dataset is not a single-table dataset.\n\n Parameters\n ----------\n dataset: kartothek.core.dataset.DatasetMetadata\n The dataset to be validated\n expected_table: Optional[str]\n Ensure that the table in the dataset is the same as the given one.\n '
if (len(dataset.tables) > 1):
raise TypeError('Expected single table dataset but found dataset with tables: `{}`'.format(dataset.tables))
if (expected_table and (dataset.tables != [expected_table])):
raise TypeError('Unexpected table in dataset:\nFound:\t{}\nExpected:\t{}'.format(dataset.tables, expected_table)) | def check_single_table_dataset(dataset, expected_table=None):
'\n Raise if the given dataset is not a single-table dataset.\n\n Parameters\n ----------\n dataset: kartothek.core.dataset.DatasetMetadata\n The dataset to be validated\n expected_table: Optional[str]\n Ensure that the table in the dataset is the same as the given one.\n '
if (len(dataset.tables) > 1):
raise TypeError('Expected single table dataset but found dataset with tables: `{}`'.format(dataset.tables))
if (expected_table and (dataset.tables != [expected_table])):
raise TypeError('Unexpected table in dataset:\nFound:\t{}\nExpected:\t{}'.format(dataset.tables, expected_table))<|docstring|>Raise if the given dataset is not a single-table dataset.
Parameters
----------
dataset: kartothek.core.dataset.DatasetMetadata
The dataset to be validated
expected_table: Optional[str]
Ensure that the table in the dataset is the same as the given one.<|endoftext|> |
713847a6105d36e249ac4379b874f8b5167bdc2cb6ec5da4d45740f567e7ab54 | @pytest.fixture
async def session(hass):
'Return aioclient session.'
return hass.helpers.aiohttp_client.async_get_clientsession() | Return aioclient session. | tests/util/test_location.py | session | uSpike/home-assistant | 23 | python | @pytest.fixture
async def session(hass):
return hass.helpers.aiohttp_client.async_get_clientsession() | @pytest.fixture
async def session(hass):
return hass.helpers.aiohttp_client.async_get_clientsession()<|docstring|>Return aioclient session.<|endoftext|> |
adb94dd8c7ba26da37f92404884112cf2efd66737e1ebfc48e46a8829999a369 | @pytest.fixture
async def raising_session(loop):
'Return an aioclient session that only fails.'
return Mock(get=Mock(side_effect=aiohttp.ClientError)) | Return an aioclient session that only fails. | tests/util/test_location.py | raising_session | uSpike/home-assistant | 23 | python | @pytest.fixture
async def raising_session(loop):
return Mock(get=Mock(side_effect=aiohttp.ClientError)) | @pytest.fixture
async def raising_session(loop):
return Mock(get=Mock(side_effect=aiohttp.ClientError))<|docstring|>Return an aioclient session that only fails.<|endoftext|> |
dd28ef357cc97c0d416161378bccb125f2e975e49019314c4b5c98ab8d72789b | def test_get_distance_to_same_place():
'Test getting the distance.'
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_PARIS[0], COORDINATES_PARIS[1])
assert (meters == 0) | Test getting the distance. | tests/util/test_location.py | test_get_distance_to_same_place | uSpike/home-assistant | 23 | python | def test_get_distance_to_same_place():
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_PARIS[0], COORDINATES_PARIS[1])
assert (meters == 0) | def test_get_distance_to_same_place():
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_PARIS[0], COORDINATES_PARIS[1])
assert (meters == 0)<|docstring|>Test getting the distance.<|endoftext|> |
ebe5e590f0c290358a24814f16ad165778a2bae0cd06b0735ea1217a24bdf4c9 | def test_get_distance():
'Test getting the distance.'
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_NEW_YORK[0], COORDINATES_NEW_YORK[1])
assert (((meters / 1000) - DISTANCE_KM) < 0.01) | Test getting the distance. | tests/util/test_location.py | test_get_distance | uSpike/home-assistant | 23 | python | def test_get_distance():
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_NEW_YORK[0], COORDINATES_NEW_YORK[1])
assert (((meters / 1000) - DISTANCE_KM) < 0.01) | def test_get_distance():
meters = location_util.distance(COORDINATES_PARIS[0], COORDINATES_PARIS[1], COORDINATES_NEW_YORK[0], COORDINATES_NEW_YORK[1])
assert (((meters / 1000) - DISTANCE_KM) < 0.01)<|docstring|>Test getting the distance.<|endoftext|> |
8c92ec285bf3b984e7f469964ae2873cce6dd02b91f30a86893648e0f1461857 | def test_get_kilometers():
'Test getting the distance between given coordinates in km.'
kilometers = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK)
assert (round(kilometers, 2) == DISTANCE_KM) | Test getting the distance between given coordinates in km. | tests/util/test_location.py | test_get_kilometers | uSpike/home-assistant | 23 | python | def test_get_kilometers():
kilometers = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK)
assert (round(kilometers, 2) == DISTANCE_KM) | def test_get_kilometers():
kilometers = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK)
assert (round(kilometers, 2) == DISTANCE_KM)<|docstring|>Test getting the distance between given coordinates in km.<|endoftext|> |
1f3a9ea8d61df3b4dbdcd3492b5cd00b5d9ca14ae4f03e23a8373d13558a918a | def test_get_miles():
'Test getting the distance between given coordinates in miles.'
miles = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
assert (round(miles, 2) == DISTANCE_MILES) | Test getting the distance between given coordinates in miles. | tests/util/test_location.py | test_get_miles | uSpike/home-assistant | 23 | python | def test_get_miles():
miles = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
assert (round(miles, 2) == DISTANCE_MILES) | def test_get_miles():
miles = location_util.vincenty(COORDINATES_PARIS, COORDINATES_NEW_YORK, miles=True)
assert (round(miles, 2) == DISTANCE_MILES)<|docstring|>Test getting the distance between given coordinates in miles.<|endoftext|> |
ce5c31e26a377783a4dda3e872145d8592c4c194a1af1c364c5b13cdd0de2b29 | async def test_detect_location_info_ipapi(aioclient_mock, session):
'Test detect location info using ipapi.co.'
aioclient_mock.get(location_util.IPAPI, text=load_fixture('ipapi.co.json'))
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'CH')
assert (info.country_name == 'Switzerland')
assert (info.region_code == 'BE')
assert (info.region_name == 'Bern')
assert (info.city == 'Bern')
assert (info.zip_code == '3000')
assert (info.time_zone == 'Europe/Zurich')
assert (info.latitude == 46.9480278)
assert (info.longitude == 7.4490812)
assert info.use_metric | Test detect location info using ipapi.co. | tests/util/test_location.py | test_detect_location_info_ipapi | uSpike/home-assistant | 23 | python | async def test_detect_location_info_ipapi(aioclient_mock, session):
aioclient_mock.get(location_util.IPAPI, text=load_fixture('ipapi.co.json'))
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'CH')
assert (info.country_name == 'Switzerland')
assert (info.region_code == 'BE')
assert (info.region_name == 'Bern')
assert (info.city == 'Bern')
assert (info.zip_code == '3000')
assert (info.time_zone == 'Europe/Zurich')
assert (info.latitude == 46.9480278)
assert (info.longitude == 7.4490812)
assert info.use_metric | async def test_detect_location_info_ipapi(aioclient_mock, session):
aioclient_mock.get(location_util.IPAPI, text=load_fixture('ipapi.co.json'))
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'CH')
assert (info.country_name == 'Switzerland')
assert (info.region_code == 'BE')
assert (info.region_name == 'Bern')
assert (info.city == 'Bern')
assert (info.zip_code == '3000')
assert (info.time_zone == 'Europe/Zurich')
assert (info.latitude == 46.9480278)
assert (info.longitude == 7.4490812)
assert info.use_metric<|docstring|>Test detect location info using ipapi.co.<|endoftext|> |
f59ca60d1394d1588071254f38aa59581002cb7572a37cfe6a335134e2a03278 | async def test_detect_location_info_ip_api(aioclient_mock, session):
'Test detect location info using ip-api.com.'
aioclient_mock.get(location_util.IP_API, text=load_fixture('ip-api.com.json'))
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'US')
assert (info.country_name == 'United States')
assert (info.region_code == 'CA')
assert (info.region_name == 'California')
assert (info.city == 'San Diego')
assert (info.zip_code == '92122')
assert (info.time_zone == 'America/Los_Angeles')
assert (info.latitude == 32.8594)
assert (info.longitude == (- 117.2073))
assert (not info.use_metric) | Test detect location info using ip-api.com. | tests/util/test_location.py | test_detect_location_info_ip_api | uSpike/home-assistant | 23 | python | async def test_detect_location_info_ip_api(aioclient_mock, session):
aioclient_mock.get(location_util.IP_API, text=load_fixture('ip-api.com.json'))
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'US')
assert (info.country_name == 'United States')
assert (info.region_code == 'CA')
assert (info.region_name == 'California')
assert (info.city == 'San Diego')
assert (info.zip_code == '92122')
assert (info.time_zone == 'America/Los_Angeles')
assert (info.latitude == 32.8594)
assert (info.longitude == (- 117.2073))
assert (not info.use_metric) | async def test_detect_location_info_ip_api(aioclient_mock, session):
aioclient_mock.get(location_util.IP_API, text=load_fixture('ip-api.com.json'))
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is not None)
assert (info.ip == '1.2.3.4')
assert (info.country_code == 'US')
assert (info.country_name == 'United States')
assert (info.region_code == 'CA')
assert (info.region_name == 'California')
assert (info.city == 'San Diego')
assert (info.zip_code == '92122')
assert (info.time_zone == 'America/Los_Angeles')
assert (info.latitude == 32.8594)
assert (info.longitude == (- 117.2073))
assert (not info.use_metric)<|docstring|>Test detect location info using ip-api.com.<|endoftext|> |
7c3f701bc4059f522e5b0f530c8e6a693bf70caf8f49830ce858d27ebb92bace | async def test_detect_location_info_both_queries_fail(session):
'Ensure we return None if both queries fail.'
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)), patch('homeassistant.util.location._get_ip_api', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is None) | Ensure we return None if both queries fail. | tests/util/test_location.py | test_detect_location_info_both_queries_fail | uSpike/home-assistant | 23 | python | async def test_detect_location_info_both_queries_fail(session):
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)), patch('homeassistant.util.location._get_ip_api', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is None) | async def test_detect_location_info_both_queries_fail(session):
with patch('homeassistant.util.location._get_ipapi', return_value=mock_coro(None)), patch('homeassistant.util.location._get_ip_api', return_value=mock_coro(None)):
info = (await location_util.async_detect_location_info(session, _test_real=True))
assert (info is None)<|docstring|>Ensure we return None if both queries fail.<|endoftext|> |
490a3cdef4d8b37446382c19afbccbf456505c62c4f84a1282026d791068bd9c | async def test_freegeoip_query_raises(raising_session):
'Test ipapi.co query when the request to API fails.'
info = (await location_util._get_ipapi(raising_session))
assert (info is None) | Test ipapi.co query when the request to API fails. | tests/util/test_location.py | test_freegeoip_query_raises | uSpike/home-assistant | 23 | python | async def test_freegeoip_query_raises(raising_session):
info = (await location_util._get_ipapi(raising_session))
assert (info is None) | async def test_freegeoip_query_raises(raising_session):
info = (await location_util._get_ipapi(raising_session))
assert (info is None)<|docstring|>Test ipapi.co query when the request to API fails.<|endoftext|> |
ab4f1ff92805c3f2696baaa61ab5037400e8bf2cdb34cdf614bdfa6a81014532 | async def test_ip_api_query_raises(raising_session):
'Test ip api query when the request to API fails.'
info = (await location_util._get_ip_api(raising_session))
assert (info is None) | Test ip api query when the request to API fails. | tests/util/test_location.py | test_ip_api_query_raises | uSpike/home-assistant | 23 | python | async def test_ip_api_query_raises(raising_session):
info = (await location_util._get_ip_api(raising_session))
assert (info is None) | async def test_ip_api_query_raises(raising_session):
info = (await location_util._get_ip_api(raising_session))
assert (info is None)<|docstring|>Test ip api query when the request to API fails.<|endoftext|> |
66261da416a89010c554306e1a2c4da1c48c51c03eb7e77be77040dc8cf4f60b | def security(db, **kw):
' See the configuration and customisation document for information\n about security setup.\n '
roles = [('Controlling', 'Controlling')]
classes = [('organisation', ['User'], ['Controlling'])]
prop_perms = []
schemadef.register_roles(db, roles)
schemadef.register_class_permissions(db, classes, prop_perms) | See the configuration and customisation document for information
about security setup. | lib/schemacfg/company.py | security | time-track-tool/time-track-tool | 0 | python | def security(db, **kw):
' See the configuration and customisation document for information\n about security setup.\n '
roles = [('Controlling', 'Controlling')]
classes = [('organisation', ['User'], ['Controlling'])]
prop_perms = []
schemadef.register_roles(db, roles)
schemadef.register_class_permissions(db, classes, prop_perms) | def security(db, **kw):
' See the configuration and customisation document for information\n about security setup.\n '
roles = [('Controlling', 'Controlling')]
classes = [('organisation', ['User'], ['Controlling'])]
prop_perms = []
schemadef.register_roles(db, roles)
schemadef.register_class_permissions(db, classes, prop_perms)<|docstring|>See the configuration and customisation document for information
about security setup.<|endoftext|> |
0ea77e2cf7551761ab6355a6aae837430a450d32ac782dda3599443029511648 | def test__init__i(self):
'Test the __init__ method of the http_request behaviour.'
assert (self.http_handler.faber_identity == FABER_ACA_IDENTITY)
assert (self.http_handler.seed[:(- 6)] == 'd_000000000000000000000000')
assert (self.http_handler.did is None)
assert (self.http_handler._schema_id is None)
assert (self.http_handler.credential_definition_id is None)
assert (self.http_handler.connection_id is None)
assert (self.http_handler.is_connected_to_Alice is False) | Test the __init__ method of the http_request behaviour. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test__init__i | bryanchriswhite/agents-aea | 126 | python | def test__init__i(self):
assert (self.http_handler.faber_identity == FABER_ACA_IDENTITY)
assert (self.http_handler.seed[:(- 6)] == 'd_000000000000000000000000')
assert (self.http_handler.did is None)
assert (self.http_handler._schema_id is None)
assert (self.http_handler.credential_definition_id is None)
assert (self.http_handler.connection_id is None)
assert (self.http_handler.is_connected_to_Alice is False) | def test__init__i(self):
assert (self.http_handler.faber_identity == FABER_ACA_IDENTITY)
assert (self.http_handler.seed[:(- 6)] == 'd_000000000000000000000000')
assert (self.http_handler.did is None)
assert (self.http_handler._schema_id is None)
assert (self.http_handler.credential_definition_id is None)
assert (self.http_handler.connection_id is None)
assert (self.http_handler.is_connected_to_Alice is False)<|docstring|>Test the __init__ method of the http_request behaviour.<|endoftext|> |
52dffc1e5537543c250ce4e4fc55c8fd2ffb74e7b932f4f64b2419ad5026b057 | def test_setup(self):
'Test the setup method of the http_handler handler.'
assert (self.http_handler.setup() is None)
self.assert_quantity_in_outbox(0) | Test the setup method of the http_handler handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_setup | bryanchriswhite/agents-aea | 126 | python | def test_setup(self):
assert (self.http_handler.setup() is None)
self.assert_quantity_in_outbox(0) | def test_setup(self):
assert (self.http_handler.setup() is None)
self.assert_quantity_in_outbox(0)<|docstring|>Test the setup method of the http_handler handler.<|endoftext|> |
d315ac282a367ccd385b8393d13309ec101dcf435b3d439d42e5a7f1dd2cf230 | def test_properties(self):
'Test the properties of the http_handler handler.'
self.http_handler._schema_id = None
with pytest.raises(ValueError, match='schema_id not set'):
assert (self.http_handler.schema_id is None)
self.http_handler._schema_id = 'some_schema_id'
assert (self.http_handler.schema_id == 'some_schema_id') | Test the properties of the http_handler handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_properties | bryanchriswhite/agents-aea | 126 | python | def test_properties(self):
self.http_handler._schema_id = None
with pytest.raises(ValueError, match='schema_id not set'):
assert (self.http_handler.schema_id is None)
self.http_handler._schema_id = 'some_schema_id'
assert (self.http_handler.schema_id == 'some_schema_id') | def test_properties(self):
self.http_handler._schema_id = None
with pytest.raises(ValueError, match='schema_id not set'):
assert (self.http_handler.schema_id is None)
self.http_handler._schema_id = 'some_schema_id'
assert (self.http_handler.schema_id == 'some_schema_id')<|docstring|>Test the properties of the http_handler handler.<|endoftext|> |
8d2963135d73207e468156f71a9ea577c22909c8a48de4fa1ab1c6bd473ea4e7 | def test_handle_unidentified_dialogue(self):
'Test the handle method of the http handler where incoming message is invalid.'
incorrect_dialogue_reference = ('', '')
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, dialogue_reference=incorrect_dialogue_reference, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=self.mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.ERROR, 'something went wrong when adding the incoming HTTP message to the dialogue.') | Test the handle method of the http handler where incoming message is invalid. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_unidentified_dialogue | bryanchriswhite/agents-aea | 126 | python | def test_handle_unidentified_dialogue(self):
incorrect_dialogue_reference = (, )
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, dialogue_reference=incorrect_dialogue_reference, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=self.mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.ERROR, 'something went wrong when adding the incoming HTTP message to the dialogue.') | def test_handle_unidentified_dialogue(self):
incorrect_dialogue_reference = (, )
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, dialogue_reference=incorrect_dialogue_reference, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=self.mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.ERROR, 'something went wrong when adding the incoming HTTP message to the dialogue.')<|docstring|>Test the handle method of the http handler where incoming message is invalid.<|endoftext|> |
b900088cb83848ac8d76e510f1adf103264551276ca89ba93afa331e726677cb | def test_handle_request(self):
'Test the handle method of the http handler where performative is REQUEST.'
self.http_handler.connection_id = 123
self.http_handler.is_connected_to_Faber = False
body = {'connection_id': 123, 'state': 'active'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received webhook message content:{str(body)}')
mock_logger.assert_any_call(logging.INFO, 'Connected to Alice')
assert (self.http_handler.is_connected_to_Alice is True) | Test the handle method of the http handler where performative is REQUEST. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_request | bryanchriswhite/agents-aea | 126 | python | def test_handle_request(self):
self.http_handler.connection_id = 123
self.http_handler.is_connected_to_Faber = False
body = {'connection_id': 123, 'state': 'active'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received webhook message content:{str(body)}')
mock_logger.assert_any_call(logging.INFO, 'Connected to Alice')
assert (self.http_handler.is_connected_to_Alice is True) | def test_handle_request(self):
self.http_handler.connection_id = 123
self.http_handler.is_connected_to_Faber = False
body = {'connection_id': 123, 'state': 'active'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message(message_type=HttpMessage, performative=HttpMessage.Performative.REQUEST, method=self.mocked_method, url=self.mocked_url, headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received webhook message content:{str(body)}')
mock_logger.assert_any_call(logging.INFO, 'Connected to Alice')
assert (self.http_handler.is_connected_to_Alice is True)<|docstring|>Test the handle method of the http handler where performative is REQUEST.<|endoftext|> |
700338d3256a56d809e310bc42b8e8e19b9378ff7db7bcd12fca2a4213d0442a | def test_handle_response_i(self):
'Test the handle method of the http handler where performative is RESPONSE and content has version.'
data = {'alias': self.http_handler.faber_identity, 'seed': self.http_handler.seed, 'role': 'TRUST_ANCHOR'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'version': 'some_version'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering Faber_ACA with seed {str(self.http_handler.seed)}')
mock_http_req.assert_any_call(method='POST', url=(self.strategy.ledger_url + LEDGER_COMMAND_REGISTER_DID), content=data) | Test the handle method of the http handler where performative is RESPONSE and content has version. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_response_i | bryanchriswhite/agents-aea | 126 | python | def test_handle_response_i(self):
data = {'alias': self.http_handler.faber_identity, 'seed': self.http_handler.seed, 'role': 'TRUST_ANCHOR'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'version': 'some_version'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering Faber_ACA with seed {str(self.http_handler.seed)}')
mock_http_req.assert_any_call(method='POST', url=(self.strategy.ledger_url + LEDGER_COMMAND_REGISTER_DID), content=data) | def test_handle_response_i(self):
data = {'alias': self.http_handler.faber_identity, 'seed': self.http_handler.seed, 'role': 'TRUST_ANCHOR'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'version': 'some_version'}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering Faber_ACA with seed {str(self.http_handler.seed)}')
mock_http_req.assert_any_call(method='POST', url=(self.strategy.ledger_url + LEDGER_COMMAND_REGISTER_DID), content=data)<|docstring|>Test the handle method of the http handler where performative is RESPONSE and content has version.<|endoftext|> |
30e592990fd98c82ec646448ce42eabb7339ea87ff31e7f515e7f4900231824d | def test_handle_response_ii(self):
'Test the handle method of the http handler where performative is RESPONSE and content has did.'
did = 'some_did'
schema_body = {'schema_name': 'degree schema', 'schema_version': '0.0.1', 'attributes': ['name', 'date', 'degree', 'age', 'timestamp']}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'did': did}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering schema {str(schema_body)}')
assert (self.http_handler.did == did)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_SCEHMAS), content=schema_body) | Test the handle method of the http handler where performative is RESPONSE and content has did. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_response_ii | bryanchriswhite/agents-aea | 126 | python | def test_handle_response_ii(self):
did = 'some_did'
schema_body = {'schema_name': 'degree schema', 'schema_version': '0.0.1', 'attributes': ['name', 'date', 'degree', 'age', 'timestamp']}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'did': did}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering schema {str(schema_body)}')
assert (self.http_handler.did == did)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_SCEHMAS), content=schema_body) | def test_handle_response_ii(self):
did = 'some_did'
schema_body = {'schema_name': 'degree schema', 'schema_version': '0.0.1', 'attributes': ['name', 'date', 'degree', 'age', 'timestamp']}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'did': did}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'Registering schema {str(schema_body)}')
assert (self.http_handler.did == did)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_SCEHMAS), content=schema_body)<|docstring|>Test the handle method of the http handler where performative is RESPONSE and content has did.<|endoftext|> |
101443eeaa20dbfa4aa00f450ada980da823a6d5743474eeedfc76001d815b23 | def test_handle_response_iii(self):
'Test the handle method of the http handler where performative is RESPONSE and content has schema_id.'
schema_id = 'some_schema_id'
credential_definition_body = {'schema_id': schema_id, 'support_revocation': SUPPORT_REVOCATION}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'schema_id': schema_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.schema_id == schema_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREDDEF), content=credential_definition_body) | Test the handle method of the http handler where performative is RESPONSE and content has schema_id. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_response_iii | bryanchriswhite/agents-aea | 126 | python | def test_handle_response_iii(self):
schema_id = 'some_schema_id'
credential_definition_body = {'schema_id': schema_id, 'support_revocation': SUPPORT_REVOCATION}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'schema_id': schema_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.schema_id == schema_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREDDEF), content=credential_definition_body) | def test_handle_response_iii(self):
schema_id = 'some_schema_id'
credential_definition_body = {'schema_id': schema_id, 'support_revocation': SUPPORT_REVOCATION}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'schema_id': schema_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.schema_id == schema_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREDDEF), content=credential_definition_body)<|docstring|>Test the handle method of the http handler where performative is RESPONSE and content has schema_id.<|endoftext|> |
02c53057e26ef599cfbf5d93b84a62999912599fda171384b2c65321e4dca9e8 | def test_handle_response_iv(self):
'Test the handle method of the http handler where performative is RESPONSE and content has credential_definition_id.'
credential_definition_id = 'some_credential_definition_id'
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'credential_definition_id': credential_definition_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.credential_definition_id == credential_definition_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREATE_INVITATION)) | Test the handle method of the http handler where performative is RESPONSE and content has credential_definition_id. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_response_iv | bryanchriswhite/agents-aea | 126 | python | def test_handle_response_iv(self):
credential_definition_id = 'some_credential_definition_id'
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'credential_definition_id': credential_definition_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.credential_definition_id == credential_definition_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREATE_INVITATION)) | def test_handle_response_iv(self):
credential_definition_id = 'some_credential_definition_id'
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'credential_definition_id': credential_definition_id}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.credential_definition_id == credential_definition_id)
mock_http_req.assert_any_call(method='POST', url=(self.strategy.admin_url + ADMIN_COMMAND_CREATE_INVITATION))<|docstring|>Test the handle method of the http handler where performative is RESPONSE and content has credential_definition_id.<|endoftext|> |
6f8468df0ae2fa76c9bed83f5fd87ec4835380cb9dbee974163d4190f1738b54 | def test_handle_response_v(self):
'Test the handle method of the http handler where performative is RESPONSE and content has connection_id.'
connection_id = 2342
invitation = {'some_key': 'some_value'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'connection_id': connection_id, 'invitation': invitation}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
self.assert_quantity_in_outbox(1)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.connection_id == connection_id)
mock_logger.assert_any_call(logging.INFO, f'connection: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'connection id: {connection_id}')
mock_logger.assert_any_call(logging.INFO, f'invitation: {str(invitation)}')
mock_logger.assert_any_call(logging.INFO, 'Sent invitation to Alice. Waiting for the invitation from Alice to finalise the connection...')
message = self.get_message_from_outbox()
(has_attributes, error_str) = self.message_has_attributes(actual_message=message, message_type=DefaultMessage, performative=DefaultMessage.Performative.BYTES, to=self.strategy.alice_aea_address, sender=self.skill.skill_context.agent_address, content=json.dumps(invitation).encode('utf-8'))
assert has_attributes, error_str | Test the handle method of the http handler where performative is RESPONSE and content has connection_id. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_response_v | bryanchriswhite/agents-aea | 126 | python | def test_handle_response_v(self):
connection_id = 2342
invitation = {'some_key': 'some_value'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'connection_id': connection_id, 'invitation': invitation}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
self.assert_quantity_in_outbox(1)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.connection_id == connection_id)
mock_logger.assert_any_call(logging.INFO, f'connection: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'connection id: {connection_id}')
mock_logger.assert_any_call(logging.INFO, f'invitation: {str(invitation)}')
mock_logger.assert_any_call(logging.INFO, 'Sent invitation to Alice. Waiting for the invitation from Alice to finalise the connection...')
message = self.get_message_from_outbox()
(has_attributes, error_str) = self.message_has_attributes(actual_message=message, message_type=DefaultMessage, performative=DefaultMessage.Performative.BYTES, to=self.strategy.alice_aea_address, sender=self.skill.skill_context.agent_address, content=json.dumps(invitation).encode('utf-8'))
assert has_attributes, error_str | def test_handle_response_v(self):
connection_id = 2342
invitation = {'some_key': 'some_value'}
http_dialogue = cast(HttpDialogue, self.prepare_skill_dialogue(dialogues=self.http_dialogues, messages=self.list_of_http_messages[:1]))
body = {'connection_id': connection_id, 'invitation': invitation}
mocked_body_bytes = json.dumps(body).encode('utf-8')
incoming_message = cast(HttpMessage, self.build_incoming_message_for_skill_dialogue(dialogue=http_dialogue, performative=HttpMessage.Performative.RESPONSE, status_code=200, status_text='some_status_code', headers=self.mocked_headers, version=self.mocked_version, body=mocked_body_bytes))
with patch.object(self.logger, 'log') as mock_logger:
self.http_handler.handle(incoming_message)
self.assert_quantity_in_outbox(1)
mock_logger.assert_any_call(logging.INFO, f'Received message: {str(body)}')
assert (self.http_handler.connection_id == connection_id)
mock_logger.assert_any_call(logging.INFO, f'connection: {str(body)}')
mock_logger.assert_any_call(logging.INFO, f'connection id: {connection_id}')
mock_logger.assert_any_call(logging.INFO, f'invitation: {str(invitation)}')
mock_logger.assert_any_call(logging.INFO, 'Sent invitation to Alice. Waiting for the invitation from Alice to finalise the connection...')
message = self.get_message_from_outbox()
(has_attributes, error_str) = self.message_has_attributes(actual_message=message, message_type=DefaultMessage, performative=DefaultMessage.Performative.BYTES, to=self.strategy.alice_aea_address, sender=self.skill.skill_context.agent_address, content=json.dumps(invitation).encode('utf-8'))
assert has_attributes, error_str<|docstring|>Test the handle method of the http handler where performative is RESPONSE and content has connection_id.<|endoftext|> |
96c4062636e3e7c6fe455632e7875ac5012e537ea2ae4988682b01d8399953c2 | def test_teardown(self):
'Test the teardown method of the http handler.'
assert (self.http_handler.teardown() is None)
self.assert_quantity_in_outbox(0) | Test the teardown method of the http handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_teardown | bryanchriswhite/agents-aea | 126 | python | def test_teardown(self):
assert (self.http_handler.teardown() is None)
self.assert_quantity_in_outbox(0) | def test_teardown(self):
assert (self.http_handler.teardown() is None)
self.assert_quantity_in_outbox(0)<|docstring|>Test the teardown method of the http handler.<|endoftext|> |
d693224372b33952643622257c792beb33345d60489ca9901c428a702b9a40fd | def test_setup(self):
'Test the setup method of the oef_search handler.'
assert (self.oef_search_handler.setup() is None)
self.assert_quantity_in_outbox(0) | Test the setup method of the oef_search handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_setup | bryanchriswhite/agents-aea | 126 | python | def test_setup(self):
assert (self.oef_search_handler.setup() is None)
self.assert_quantity_in_outbox(0) | def test_setup(self):
assert (self.oef_search_handler.setup() is None)
self.assert_quantity_in_outbox(0)<|docstring|>Test the setup method of the oef_search handler.<|endoftext|> |
787a8904a7239d4f389700ce0ee983938816669aace87a5e968177c6bf8bf8af | def test_handle_unidentified_dialogue(self):
'Test the _handle_unidentified_dialogue method of the oef_search handler.'
incorrect_dialogue_reference = ('', '')
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, dialogue_reference=incorrect_dialogue_reference, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received invalid oef_search message={incoming_message}, unidentified dialogue.') | Test the _handle_unidentified_dialogue method of the oef_search handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_unidentified_dialogue | bryanchriswhite/agents-aea | 126 | python | def test_handle_unidentified_dialogue(self):
incorrect_dialogue_reference = (, )
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, dialogue_reference=incorrect_dialogue_reference, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received invalid oef_search message={incoming_message}, unidentified dialogue.') | def test_handle_unidentified_dialogue(self):
incorrect_dialogue_reference = (, )
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, dialogue_reference=incorrect_dialogue_reference, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received invalid oef_search message={incoming_message}, unidentified dialogue.')<|docstring|>Test the _handle_unidentified_dialogue method of the oef_search handler.<|endoftext|> |
4a24d81ebadcc7beefe222c87f0f24fa8b39d9e83ddd65f661bdbdb693eddb0b | def test_handle_error(self):
'Test the _handle_error method of the oef_search handler.'
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received oef_search error message={incoming_message} in dialogue={oef_search_dialogue}.') | Test the _handle_error method of the oef_search handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_error | bryanchriswhite/agents-aea | 126 | python | def test_handle_error(self):
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received oef_search error message={incoming_message} in dialogue={oef_search_dialogue}.') | def test_handle_error(self):
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.OEF_ERROR, oef_error_operation=OefSearchMessage.OefErrorOperation.REGISTER_SERVICE))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'received oef_search error message={incoming_message} in dialogue={oef_search_dialogue}.')<|docstring|>Test the _handle_error method of the oef_search handler.<|endoftext|> |
a7bbdb8e54e97f9d6e57274d884ac3e39e20da9fd691be9b7b333a5a57e5d0c2 | def test_handle_search_i(self):
'Test the _handle_search method of the oef_search handler where the number of agents found is NOT 0.'
alice_address = 'alice'
agents = (alice_address,)
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({'agent_1': {'key_1': 'value_1', 'key_2': 'value_2'}, 'agent_2': {'key_3': 'value_3', 'key_4': 'value_4'}})))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'found Alice with address {alice_address}, stopping search.')
assert (self.strategy.is_searching is False)
assert (self.strategy.alice_aea_address is alice_address)
mock_http_req.assert_any_call('GET', (self.strategy.admin_url + ADMIN_COMMAND_STATUS)) | Test the _handle_search method of the oef_search handler where the number of agents found is NOT 0. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_search_i | bryanchriswhite/agents-aea | 126 | python | def test_handle_search_i(self):
alice_address = 'alice'
agents = (alice_address,)
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({'agent_1': {'key_1': 'value_1', 'key_2': 'value_2'}, 'agent_2': {'key_3': 'value_3', 'key_4': 'value_4'}})))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'found Alice with address {alice_address}, stopping search.')
assert (self.strategy.is_searching is False)
assert (self.strategy.alice_aea_address is alice_address)
mock_http_req.assert_any_call('GET', (self.strategy.admin_url + ADMIN_COMMAND_STATUS)) | def test_handle_search_i(self):
alice_address = 'alice'
agents = (alice_address,)
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({'agent_1': {'key_1': 'value_1', 'key_2': 'value_2'}, 'agent_2': {'key_3': 'value_3', 'key_4': 'value_4'}})))
with patch.object(self.faber_behaviour, 'send_http_request_message') as mock_http_req:
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, f'found Alice with address {alice_address}, stopping search.')
assert (self.strategy.is_searching is False)
assert (self.strategy.alice_aea_address is alice_address)
mock_http_req.assert_any_call('GET', (self.strategy.admin_url + ADMIN_COMMAND_STATUS))<|docstring|>Test the _handle_search method of the oef_search handler where the number of agents found is NOT 0.<|endoftext|> |
5d95e97f715db77bc38a777893ecb464e87f50a663b3e78b7a627eb83d5c4e11 | def test_handle_search_ii(self):
'Test the _handle_search method of the oef_search handler where the number of agents found is 0.'
agents = tuple()
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({})))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, 'did not find Alice. found 0 agents. continue searching.') | Test the _handle_search method of the oef_search handler where the number of agents found is 0. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_search_ii | bryanchriswhite/agents-aea | 126 | python | def test_handle_search_ii(self):
agents = tuple()
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({})))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, 'did not find Alice. found 0 agents. continue searching.') | def test_handle_search_ii(self):
agents = tuple()
oef_search_dialogue = cast(OefSearchDialogue, self.prepare_skill_dialogue(dialogues=self.oef_search_dialogues, messages=self.list_of_oef_search_messages[:1]))
incoming_message = cast(OefSearchMessage, self.build_incoming_message_for_skill_dialogue(dialogue=oef_search_dialogue, performative=OefSearchMessage.Performative.SEARCH_RESULT, agents=agents, agents_info=OefSearchMessage.AgentsInfo({})))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.INFO, 'did not find Alice. found 0 agents. continue searching.')<|docstring|>Test the _handle_search method of the oef_search handler where the number of agents found is 0.<|endoftext|> |
02fcfdc095a0b2c59bbd8375e9b9bcaab2847aee4fd697ba24e68b8ca64633d4 | def test_handle_invalid(self):
'Test the _handle_invalid method of the oef_search handler.'
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=self.mocked_proposal))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.WARNING, f'cannot handle oef_search message of performative={incoming_message.performative} in dialogue={self.oef_search_dialogues.get_dialogue(incoming_message)}.') | Test the _handle_invalid method of the oef_search handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_handle_invalid | bryanchriswhite/agents-aea | 126 | python | def test_handle_invalid(self):
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=self.mocked_proposal))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.WARNING, f'cannot handle oef_search message of performative={incoming_message.performative} in dialogue={self.oef_search_dialogues.get_dialogue(incoming_message)}.') | def test_handle_invalid(self):
incoming_message = cast(OefSearchMessage, self.build_incoming_message(message_type=OefSearchMessage, performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=self.mocked_proposal))
with patch.object(self.logger, 'log') as mock_logger:
self.oef_search_handler.handle(incoming_message)
mock_logger.assert_any_call(logging.WARNING, f'cannot handle oef_search message of performative={incoming_message.performative} in dialogue={self.oef_search_dialogues.get_dialogue(incoming_message)}.')<|docstring|>Test the _handle_invalid method of the oef_search handler.<|endoftext|> |
a9c8b4a1bb9333cf577feb7a6afa666fd6c9bb022445b5bf1963f9d2b995713b | def test_teardown(self):
'Test the teardown method of the oef_search handler.'
assert (self.oef_search_handler.teardown() is None)
self.assert_quantity_in_outbox(0) | Test the teardown method of the oef_search handler. | tests/test_packages/test_skills/test_aries_faber/test_handlers.py | test_teardown | bryanchriswhite/agents-aea | 126 | python | def test_teardown(self):
assert (self.oef_search_handler.teardown() is None)
self.assert_quantity_in_outbox(0) | def test_teardown(self):
assert (self.oef_search_handler.teardown() is None)
self.assert_quantity_in_outbox(0)<|docstring|>Test the teardown method of the oef_search handler.<|endoftext|> |
d843736245e335c0f9f9c3e2087ae35ba8528f71f74a9d1d0ba50db0c998357e | def _getLoggingLevel(name):
'Gets the logging level value from its name'
level = config().get('Logging', 'default')
try:
level = config().get('Logging', name)
except:
pass
value = logging.INFO
try:
value = getattr(logging, level)
except AttributeError:
print_(((('WARNING: Wrong specification of debug level ' + level) + ' for log ') + name))
return value | Gets the logging level value from its name | StoveOpt/Infrastructure/Logging.py | _getLoggingLevel | Liam-Cassidy/StoveOpt | 0 | python | def _getLoggingLevel(name):
level = config().get('Logging', 'default')
try:
level = config().get('Logging', name)
except:
pass
value = logging.INFO
try:
value = getattr(logging, level)
except AttributeError:
print_(((('WARNING: Wrong specification of debug level ' + level) + ' for log ') + name))
return value | def _getLoggingLevel(name):
level = config().get('Logging', 'default')
try:
level = config().get('Logging', name)
except:
pass
value = logging.INFO
try:
value = getattr(logging, level)
except AttributeError:
print_(((('WARNING: Wrong specification of debug level ' + level) + ' for log ') + name))
return value<|docstring|>Gets the logging level value from its name<|endoftext|> |
27625ffa79a5ff48b9347b1052638aff527730934c41457951e456926e226d43 | def foamLogger(name='general'):
'\n :param name: name of the logfile\n :return: a logger that is correctly set up for pyFoam\n '
if (not hasLogging):
return DummyLogger()
log = logging.getLogger(name)
if (not (name in _definedLoggers)):
assertDirectory(logDirectory())
lname = path.join(logDirectory(), name)
rot = logging.FileHandler(lname)
machine = uname()[1].split('.')[0]
rot.setFormatter(logging.Formatter(fmt=(('%(asctime)s ' + ('%15s' % machine)) + ':%(process)-6d %(levelname)-8s %(message)s - in %(filename)s:%(lineno)d')))
log.addHandler(rot)
log.setLevel(_getLoggingLevel(name))
_definedLoggers.append(name)
return log | :param name: name of the logfile
:return: a logger that is correctly set up for pyFoam | StoveOpt/Infrastructure/Logging.py | foamLogger | Liam-Cassidy/StoveOpt | 0 | python | def foamLogger(name='general'):
'\n :param name: name of the logfile\n :return: a logger that is correctly set up for pyFoam\n '
if (not hasLogging):
return DummyLogger()
log = logging.getLogger(name)
if (not (name in _definedLoggers)):
assertDirectory(logDirectory())
lname = path.join(logDirectory(), name)
rot = logging.FileHandler(lname)
machine = uname()[1].split('.')[0]
rot.setFormatter(logging.Formatter(fmt=(('%(asctime)s ' + ('%15s' % machine)) + ':%(process)-6d %(levelname)-8s %(message)s - in %(filename)s:%(lineno)d')))
log.addHandler(rot)
log.setLevel(_getLoggingLevel(name))
_definedLoggers.append(name)
return log | def foamLogger(name='general'):
'\n :param name: name of the logfile\n :return: a logger that is correctly set up for pyFoam\n '
if (not hasLogging):
return DummyLogger()
log = logging.getLogger(name)
if (not (name in _definedLoggers)):
assertDirectory(logDirectory())
lname = path.join(logDirectory(), name)
rot = logging.FileHandler(lname)
machine = uname()[1].split('.')[0]
rot.setFormatter(logging.Formatter(fmt=(('%(asctime)s ' + ('%15s' % machine)) + ':%(process)-6d %(levelname)-8s %(message)s - in %(filename)s:%(lineno)d')))
log.addHandler(rot)
log.setLevel(_getLoggingLevel(name))
_definedLoggers.append(name)
return log<|docstring|>:param name: name of the logfile
:return: a logger that is correctly set up for pyFoam<|endoftext|> |
34907fbd4ee0c91accbc0056915d4a2b52119dfa2901953b2039f12bd85831be | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.List = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/List', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysResponse.FromString)
self.Get = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Get', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.GetApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__pb2.ApiKey.FromString)
self.Create = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Create', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyResponse.FromString)
self.Update = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Update', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.UpdateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.Delete = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Delete', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.DeleteApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.ListOperations = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/ListOperations', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsResponse.FromString) | Constructor.
Args:
channel: A grpc.Channel. | yandex/cloud/iam/v1/api_key_service_pb2_grpc.py | __init__ | kbespalov/python-sdk | 0 | python | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.List = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/List', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysResponse.FromString)
self.Get = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Get', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.GetApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__pb2.ApiKey.FromString)
self.Create = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Create', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyResponse.FromString)
self.Update = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Update', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.UpdateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.Delete = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Delete', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.DeleteApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.ListOperations = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/ListOperations', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsResponse.FromString) | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.List = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/List', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeysResponse.FromString)
self.Get = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Get', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.GetApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__pb2.ApiKey.FromString)
self.Create = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Create', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.CreateApiKeyResponse.FromString)
self.Update = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Update', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.UpdateApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.Delete = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/Delete', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.DeleteApiKeyRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation_dot_operation__pb2.Operation.FromString)
self.ListOperations = channel.unary_unary('/yandex.cloud.iam.v1.ApiKeyService/ListOperations', request_serializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_iam_dot_v1_dot_api__key__service__pb2.ListApiKeyOperationsResponse.FromString)<|docstring|>Constructor.
Args:
channel: A grpc.Channel.<|endoftext|> |
d25edc7c7c8783187623060210823631686b559f4f8fec87250ca64df243daaf | def List(self, request, context):
'Retrieves the list of API keys for the specified service account.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Retrieves the list of API keys for the specified service account. | yandex/cloud/iam/v1/api_key_service_pb2_grpc.py | List | kbespalov/python-sdk | 0 | python | def List(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | def List(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')<|docstring|>Retrieves the list of API keys for the specified service account.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.