repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
falkr/stmpy | stmpy/__init__.py | _parse_action_list_attribute | def _parse_action_list_attribute(attribute):
"""
Parses a list of actions, as found in the effect attribute of
transitions, and the enry and exit actions of states.
Actions are separated by a semicolon, surrounded by any amount of
whitespace. A action can have the following form:
m; m(); m(True); m(*)
The asterisk that the state machine should provide the args and
kwargs from the incoming event.
"""
actions = []
for action_call in attribute.split(';'):
action_call = action_call.strip()
if action_call: # string is not empty
actions.append(_parse_action(action_call))
return actions | python | def _parse_action_list_attribute(attribute):
"""
Parses a list of actions, as found in the effect attribute of
transitions, and the enry and exit actions of states.
Actions are separated by a semicolon, surrounded by any amount of
whitespace. A action can have the following form:
m; m(); m(True); m(*)
The asterisk that the state machine should provide the args and
kwargs from the incoming event.
"""
actions = []
for action_call in attribute.split(';'):
action_call = action_call.strip()
if action_call: # string is not empty
actions.append(_parse_action(action_call))
return actions | [
"def",
"_parse_action_list_attribute",
"(",
"attribute",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"action_call",
"in",
"attribute",
".",
"split",
"(",
"';'",
")",
":",
"action_call",
"=",
"action_call",
".",
"strip",
"(",
")",
"if",
"action_call",
":",
"... | Parses a list of actions, as found in the effect attribute of
transitions, and the enry and exit actions of states.
Actions are separated by a semicolon, surrounded by any amount of
whitespace. A action can have the following form:
m; m(); m(True); m(*)
The asterisk that the state machine should provide the args and
kwargs from the incoming event. | [
"Parses",
"a",
"list",
"of",
"actions",
"as",
"found",
"in",
"the",
"effect",
"attribute",
"of",
"transitions",
"and",
"the",
"enry",
"and",
"exit",
"actions",
"of",
"states",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L180-L198 | train | 35,400 |
falkr/stmpy | stmpy/__init__.py | Driver.print_status | def print_status(self):
"""Provide a snapshot of the current status."""
s = []
s.append('=== State Machines: ===\n')
for stm_id in Driver._stms_by_id:
stm = Driver._stms_by_id[stm_id]
s.append(' - {} in state {}\n'.format(stm.id, stm.state))
s.append('=== Events in Queue: ===\n')
for event in self._event_queue.queue:
if event is not None:
s.append(' - {} for {} with args:{} kwargs:{}\n'.format(
event['id'], event['stm'].id,
event['args'], event['kwargs']))
s.append('=== Active Timers: {} ===\n'.format(len(self._timer_queue)))
for timer in self._timer_queue:
s.append(' - {} for {} with timeout {}\n'.format(
timer['id'], timer['stm'].id, timer['timeout']))
s.append('=== ================ ===\n')
return ''.join(s) | python | def print_status(self):
"""Provide a snapshot of the current status."""
s = []
s.append('=== State Machines: ===\n')
for stm_id in Driver._stms_by_id:
stm = Driver._stms_by_id[stm_id]
s.append(' - {} in state {}\n'.format(stm.id, stm.state))
s.append('=== Events in Queue: ===\n')
for event in self._event_queue.queue:
if event is not None:
s.append(' - {} for {} with args:{} kwargs:{}\n'.format(
event['id'], event['stm'].id,
event['args'], event['kwargs']))
s.append('=== Active Timers: {} ===\n'.format(len(self._timer_queue)))
for timer in self._timer_queue:
s.append(' - {} for {} with timeout {}\n'.format(
timer['id'], timer['stm'].id, timer['timeout']))
s.append('=== ================ ===\n')
return ''.join(s) | [
"def",
"print_status",
"(",
"self",
")",
":",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"'=== State Machines: ===\\n'",
")",
"for",
"stm_id",
"in",
"Driver",
".",
"_stms_by_id",
":",
"stm",
"=",
"Driver",
".",
"_stms_by_id",
"[",
"stm_id",
"]",
"s",
... | Provide a snapshot of the current status. | [
"Provide",
"a",
"snapshot",
"of",
"the",
"current",
"status",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L242-L260 | train | 35,401 |
falkr/stmpy | stmpy/__init__.py | Driver.add_machine | def add_machine(self, machine):
"""Add the state machine to this driver."""
self._logger.debug('Adding machine {} to driver'.format(machine.id))
machine._driver = self
machine._reset()
if machine.id is not None:
# TODO warning when STM already registered
Driver._stms_by_id[machine.id] = machine
self._add_event(event_id=None, args=[], kwargs={}, stm=machine) | python | def add_machine(self, machine):
"""Add the state machine to this driver."""
self._logger.debug('Adding machine {} to driver'.format(machine.id))
machine._driver = self
machine._reset()
if machine.id is not None:
# TODO warning when STM already registered
Driver._stms_by_id[machine.id] = machine
self._add_event(event_id=None, args=[], kwargs={}, stm=machine) | [
"def",
"add_machine",
"(",
"self",
",",
"machine",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Adding machine {} to driver'",
".",
"format",
"(",
"machine",
".",
"id",
")",
")",
"machine",
".",
"_driver",
"=",
"self",
"machine",
".",
"_reset",
... | Add the state machine to this driver. | [
"Add",
"the",
"state",
"machine",
"to",
"this",
"driver",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L262-L270 | train | 35,402 |
falkr/stmpy | stmpy/__init__.py | Driver.start | def start(self, max_transitions=None, keep_active=False):
"""
Start the driver.
This method creates a thread which runs the event loop.
The method returns immediately. To wait until the driver
finishes, use `stmpy.Driver.wait_until_finished`.
`max_transitions`: execute only this number of transitions, then stop
`keep_active`: When true, keep the driver running even when all state
machines terminated
"""
self._active = True
self._max_transitions = max_transitions
self._keep_active = keep_active
self.thread = Thread(target=self._start_loop)
self.thread.start() | python | def start(self, max_transitions=None, keep_active=False):
"""
Start the driver.
This method creates a thread which runs the event loop.
The method returns immediately. To wait until the driver
finishes, use `stmpy.Driver.wait_until_finished`.
`max_transitions`: execute only this number of transitions, then stop
`keep_active`: When true, keep the driver running even when all state
machines terminated
"""
self._active = True
self._max_transitions = max_transitions
self._keep_active = keep_active
self.thread = Thread(target=self._start_loop)
self.thread.start() | [
"def",
"start",
"(",
"self",
",",
"max_transitions",
"=",
"None",
",",
"keep_active",
"=",
"False",
")",
":",
"self",
".",
"_active",
"=",
"True",
"self",
".",
"_max_transitions",
"=",
"max_transitions",
"self",
".",
"_keep_active",
"=",
"keep_active",
"self... | Start the driver.
This method creates a thread which runs the event loop.
The method returns immediately. To wait until the driver
finishes, use `stmpy.Driver.wait_until_finished`.
`max_transitions`: execute only this number of transitions, then stop
`keep_active`: When true, keep the driver running even when all state
machines terminated | [
"Start",
"the",
"driver",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L272-L288 | train | 35,403 |
falkr/stmpy | stmpy/__init__.py | Driver.wait_until_finished | def wait_until_finished(self):
"""Blocking method to wait until the driver finished its execution."""
try:
self.thread.join()
except KeyboardInterrupt:
self._logger.debug('Keyboard interrupt detected, stopping driver.')
self._active = False
self._wake_queue() | python | def wait_until_finished(self):
"""Blocking method to wait until the driver finished its execution."""
try:
self.thread.join()
except KeyboardInterrupt:
self._logger.debug('Keyboard interrupt detected, stopping driver.')
self._active = False
self._wake_queue() | [
"def",
"wait_until_finished",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"thread",
".",
"join",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Keyboard interrupt detected, stopping driver.'",
")",
"self",
".",
"... | Blocking method to wait until the driver finished its execution. | [
"Blocking",
"method",
"to",
"wait",
"until",
"the",
"driver",
"finished",
"its",
"execution",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L300-L307 | train | 35,404 |
falkr/stmpy | stmpy/__init__.py | Driver._check_timers | def _check_timers(self):
"""
Check for expired timers.
If there are any timers that expired, place them in the event
queue.
"""
if self._timer_queue:
timer = self._timer_queue[0]
if timer['timeout_abs'] < _current_time_millis():
# the timer is expired, remove first element in queue
self._timer_queue.pop(0)
# put into the event queue
self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))
self._add_event(timer['id'], [], {}, timer['stm'], front=True)
# not necessary to set next timeout,
# complete check timers will be called again
else:
self._next_timeout = (
timer['timeout_abs'] - _current_time_millis()) / 1000
if self._next_timeout < 0:
self._next_timeout = 0
else:
self._next_timeout = None | python | def _check_timers(self):
"""
Check for expired timers.
If there are any timers that expired, place them in the event
queue.
"""
if self._timer_queue:
timer = self._timer_queue[0]
if timer['timeout_abs'] < _current_time_millis():
# the timer is expired, remove first element in queue
self._timer_queue.pop(0)
# put into the event queue
self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))
self._add_event(timer['id'], [], {}, timer['stm'], front=True)
# not necessary to set next timeout,
# complete check timers will be called again
else:
self._next_timeout = (
timer['timeout_abs'] - _current_time_millis()) / 1000
if self._next_timeout < 0:
self._next_timeout = 0
else:
self._next_timeout = None | [
"def",
"_check_timers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timer_queue",
":",
"timer",
"=",
"self",
".",
"_timer_queue",
"[",
"0",
"]",
"if",
"timer",
"[",
"'timeout_abs'",
"]",
"<",
"_current_time_millis",
"(",
")",
":",
"# the timer is expired, re... | Check for expired timers.
If there are any timers that expired, place them in the event
queue. | [
"Check",
"for",
"expired",
"timers",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L344-L367 | train | 35,405 |
falkr/stmpy | stmpy/__init__.py | Driver.send | def send(self, message_id, stm_id, args=[], kwargs={}):
"""
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier added to the driver.
"""
if stm_id not in Driver._stms_by_id:
self._logger.warn('Machine with name {} cannot be found. '
'Ignoring message {}.'.format(stm_id, message_id))
else:
stm = Driver._stms_by_id[stm_id]
self._add_event(message_id, args, kwargs, stm) | python | def send(self, message_id, stm_id, args=[], kwargs={}):
"""
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier added to the driver.
"""
if stm_id not in Driver._stms_by_id:
self._logger.warn('Machine with name {} cannot be found. '
'Ignoring message {}.'.format(stm_id, message_id))
else:
stm = Driver._stms_by_id[stm_id]
self._add_event(message_id, args, kwargs, stm) | [
"def",
"send",
"(",
"self",
",",
"message_id",
",",
"stm_id",
",",
"args",
"=",
"[",
"]",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"if",
"stm_id",
"not",
"in",
"Driver",
".",
"_stms_by_id",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Machine wi... | Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier added to the driver. | [
"Send",
"a",
"message",
"to",
"a",
"state",
"machine",
"handled",
"by",
"this",
"driver",
"."
] | 78b016f7bf6fa7b6eba8dae58997fb99f7215bf7 | https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L375-L389 | train | 35,406 |
jhuapl-boss/intern | intern/service/boss/project.py | ProjectService.get_group | def get_group(self, name, user_name=None):
"""Get owner of group and the resources it's attached to.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in determining if user is a member of the given group.
Returns:
(dict): Keys include 'owner', 'name', 'resources'.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_group(
name, user_name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | python | def get_group(self, name, user_name=None):
"""Get owner of group and the resources it's attached to.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in determining if user is a member of the given group.
Returns:
(dict): Keys include 'owner', 'name', 'resources'.
Raises:
requests.HTTPError on failure.
"""
return self.service.get_group(
name, user_name, self.url_prefix, self.auth, self.session,
self.session_send_opts) | [
"def",
"get_group",
"(",
"self",
",",
"name",
",",
"user_name",
"=",
"None",
")",
":",
"return",
"self",
".",
"service",
".",
"get_group",
"(",
"name",
",",
"user_name",
",",
"self",
".",
"url_prefix",
",",
"self",
".",
"auth",
",",
"self",
".",
"ses... | Get owner of group and the resources it's attached to.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in determining if user is a member of the given group.
Returns:
(dict): Keys include 'owner', 'name', 'resources'.
Raises:
requests.HTTPError on failure. | [
"Get",
"owner",
"of",
"group",
"and",
"the",
"resources",
"it",
"s",
"attached",
"to",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/project.py#L57-L72 | train | 35,407 |
jhuapl-boss/intern | intern/service/boss/project.py | ProjectService.add_permissions | def add_permissions(self, grp_name, resource, permissions):
""" Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failure.
"""
self.service.add_permissions(
grp_name, resource, permissions,
self.url_prefix, self.auth, self.session, self.session_send_opts) | python | def add_permissions(self, grp_name, resource, permissions):
""" Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failure.
"""
self.service.add_permissions(
grp_name, resource, permissions,
self.url_prefix, self.auth, self.session, self.session_send_opts) | [
"def",
"add_permissions",
"(",
"self",
",",
"grp_name",
",",
"resource",
",",
"permissions",
")",
":",
"self",
".",
"service",
".",
"add_permissions",
"(",
"grp_name",
",",
"resource",
",",
"permissions",
",",
"self",
".",
"url_prefix",
",",
"self",
".",
"... | Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
Raises:
requests.HTTPError on failure. | [
"Add",
"additional",
"permissions",
"for",
"the",
"group",
"associated",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/project.py#L257-L270 | train | 35,408 |
jhuapl-boss/intern | intern/service/boss/project.py | ProjectService.create | def create(self, resource):
"""Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
"""
return self.service.create(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | python | def create(self, resource):
"""Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure.
"""
return self.service.create(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | [
"def",
"create",
"(",
"self",
",",
"resource",
")",
":",
"return",
"self",
".",
"service",
".",
"create",
"(",
"resource",
",",
"self",
".",
"url_prefix",
",",
"self",
".",
"auth",
",",
"self",
".",
"session",
",",
"self",
".",
"session_send_opts",
")"... | Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
requests.HTTPError on failure. | [
"Create",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/service/boss/project.py#L404-L418 | train | 35,409 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote._init_project_service | def _init_project_service(self, version):
"""
Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)
self._token_project = project_cfg[CONFIG_TOKEN]
proto = project_cfg[CONFIG_PROTOCOL]
host = project_cfg[CONFIG_HOST]
self._project = ProjectService(host, version)
self._project.base_protocol = proto
self._project.set_auth(self._token_project) | python | def _init_project_service(self, version):
"""
Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)
self._token_project = project_cfg[CONFIG_TOKEN]
proto = project_cfg[CONFIG_PROTOCOL]
host = project_cfg[CONFIG_HOST]
self._project = ProjectService(host, version)
self._project.base_protocol = proto
self._project.set_auth(self._token_project) | [
"def",
"_init_project_service",
"(",
"self",
",",
"version",
")",
":",
"project_cfg",
"=",
"self",
".",
"_load_config_section",
"(",
"CONFIG_PROJECT_SECTION",
")",
"self",
".",
"_token_project",
"=",
"project_cfg",
"[",
"CONFIG_TOKEN",
"]",
"proto",
"=",
"project_... | Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | [
"Method",
"to",
"initialize",
"the",
"Project",
"Service",
"from",
"the",
"config",
"data"
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L83-L103 | train | 35,410 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote._init_metadata_service | def _init_metadata_service(self, version):
"""
Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
metadata_cfg = self._load_config_section(CONFIG_METADATA_SECTION)
self._token_metadata = metadata_cfg[CONFIG_TOKEN]
proto = metadata_cfg[CONFIG_PROTOCOL]
host = metadata_cfg[CONFIG_HOST]
self._metadata = MetadataService(host, version)
self._metadata.base_protocol = proto
self._metadata.set_auth(self._token_metadata) | python | def _init_metadata_service(self, version):
"""
Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
metadata_cfg = self._load_config_section(CONFIG_METADATA_SECTION)
self._token_metadata = metadata_cfg[CONFIG_TOKEN]
proto = metadata_cfg[CONFIG_PROTOCOL]
host = metadata_cfg[CONFIG_HOST]
self._metadata = MetadataService(host, version)
self._metadata.base_protocol = proto
self._metadata.set_auth(self._token_metadata) | [
"def",
"_init_metadata_service",
"(",
"self",
",",
"version",
")",
":",
"metadata_cfg",
"=",
"self",
".",
"_load_config_section",
"(",
"CONFIG_METADATA_SECTION",
")",
"self",
".",
"_token_metadata",
"=",
"metadata_cfg",
"[",
"CONFIG_TOKEN",
"]",
"proto",
"=",
"met... | Method to initialize the Metadata Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | [
"Method",
"to",
"initialize",
"the",
"Metadata",
"Service",
"from",
"the",
"config",
"data"
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L105-L125 | train | 35,411 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote._init_volume_service | def _init_volume_service(self, version):
"""
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
volume_cfg = self._load_config_section(CONFIG_VOLUME_SECTION)
self._token_volume = volume_cfg[CONFIG_TOKEN]
proto = volume_cfg[CONFIG_PROTOCOL]
host = volume_cfg[CONFIG_HOST]
self._volume = VolumeService(host, version)
self._volume.base_protocol = proto
self._volume.set_auth(self._token_volume) | python | def _init_volume_service(self, version):
"""
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
volume_cfg = self._load_config_section(CONFIG_VOLUME_SECTION)
self._token_volume = volume_cfg[CONFIG_TOKEN]
proto = volume_cfg[CONFIG_PROTOCOL]
host = volume_cfg[CONFIG_HOST]
self._volume = VolumeService(host, version)
self._volume.base_protocol = proto
self._volume.set_auth(self._token_volume) | [
"def",
"_init_volume_service",
"(",
"self",
",",
"version",
")",
":",
"volume_cfg",
"=",
"self",
".",
"_load_config_section",
"(",
"CONFIG_VOLUME_SECTION",
")",
"self",
".",
"_token_volume",
"=",
"volume_cfg",
"[",
"CONFIG_TOKEN",
"]",
"proto",
"=",
"volume_cfg",
... | Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | [
"Method",
"to",
"initialize",
"the",
"Volume",
"Service",
"from",
"the",
"config",
"data"
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L127-L147 | train | 35,412 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote._load_config_section | def _load_config_section(self, section_name):
"""
Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters
"""
if self._config.has_section(section_name):
# Load specific section
section = dict(self._config.items(section_name))
elif self._config.has_section("Default"):
# Load Default section
section = dict(self._config.items("Default"))
else:
raise KeyError((
"'{}' was not found in the configuration file and no default " +
"configuration was provided."
).format(section_name))
# Make sure section is valid
if "protocol" in section and "host" in section and "token" in section:
return section
else:
raise KeyError(
"Missing values in configuration data. " +
"Must contain: protocol, host, token"
) | python | def _load_config_section(self, section_name):
"""
Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters
"""
if self._config.has_section(section_name):
# Load specific section
section = dict(self._config.items(section_name))
elif self._config.has_section("Default"):
# Load Default section
section = dict(self._config.items("Default"))
else:
raise KeyError((
"'{}' was not found in the configuration file and no default " +
"configuration was provided."
).format(section_name))
# Make sure section is valid
if "protocol" in section and "host" in section and "token" in section:
return section
else:
raise KeyError(
"Missing values in configuration data. " +
"Must contain: protocol, host, token"
) | [
"def",
"_load_config_section",
"(",
"self",
",",
"section_name",
")",
":",
"if",
"self",
".",
"_config",
".",
"has_section",
"(",
"section_name",
")",
":",
"# Load specific section",
"section",
"=",
"dict",
"(",
"self",
".",
"_config",
".",
"items",
"(",
"se... | Method to load the specific Service section from the config file if it
exists, or fall back to the default
Args:
section_name (str): The desired service section name
Returns:
(dict): the section parameters | [
"Method",
"to",
"load",
"the",
"specific",
"Service",
"section",
"from",
"the",
"config",
"file",
"if",
"it",
"exists",
"or",
"fall",
"back",
"to",
"the",
"default"
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L149-L179 | train | 35,413 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.get_group | def get_group(self, name, user_name=None):
"""
Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determining if user is a member of the given group.
Returns:
(mixed): Dictionary if getting group information or bool if a user
name is supplied.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_group(name, user_name) | python | def get_group(self, name, user_name=None):
"""
Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determining if user is a member of the given group.
Returns:
(mixed): Dictionary if getting group information or bool if a user
name is supplied.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_group(name, user_name) | [
"def",
"get_group",
"(",
"self",
",",
"name",
",",
"user_name",
"=",
"None",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"get_group",
"(",
"name",
",",
... | Get information on the given group or whether or not a user is a member
of the group.
Args:
name (string): Name of group to query.
user_name (optional[string]): Supply None if not interested in
determining if user is a member of the given group.
Returns:
(mixed): Dictionary if getting group information or bool if a user
name is supplied.
Raises:
requests.HTTPError on failure. | [
"Get",
"information",
"on",
"the",
"given",
"group",
"or",
"whether",
"or",
"not",
"a",
"user",
"is",
"a",
"member",
"of",
"the",
"group",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L235-L253 | train | 35,414 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.list_group_members | def list_group_members(self, name):
"""
Get the members of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_members(name) | python | def list_group_members(self, name):
"""
Get the members of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.list_group_members(name) | [
"def",
"list_group_members",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"list_group_members",
"(",
"name",
")"
] | Get the members of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of member names.
Raises:
requests.HTTPError on failure. | [
"Get",
"the",
"members",
"of",
"a",
"group",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L287-L301 | train | 35,415 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.get_permissions | def get_permissions(self, grp_name, resource):
"""
Get permissions associated the group has with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_permissions(grp_name, resource) | python | def get_permissions(self, grp_name, resource):
"""
Get permissions associated the group has with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_permissions(grp_name, resource) | [
"def",
"get_permissions",
"(",
"self",
",",
"grp_name",
",",
"resource",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"get_permissions",
"(",
"grp_name",
",",... | Get permissions associated the group has with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
Raises:
requests.HTTPError on failure. | [
"Get",
"permissions",
"associated",
"the",
"group",
"has",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L432-L448 | train | 35,416 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.add_permissions | def add_permissions(self, grp_name, resource, permissions):
"""
Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_permissions(grp_name, resource, permissions) | python | def add_permissions(self, grp_name, resource, permissions):
"""
Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.add_permissions(grp_name, resource, permissions) | [
"def",
"add_permissions",
"(",
"self",
",",
"grp_name",
",",
"resource",
",",
"permissions",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"self",
".",
"project_service",
".",
"add_permissions",
"(",
"grp_n... | Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure. | [
"Add",
"additional",
"permissions",
"for",
"the",
"group",
"associated",
"with",
"the",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L450-L464 | train | 35,417 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.update_permissions | def update_permissions(self, grp_name, resource, permissions):
"""
Update permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.update_permissions(grp_name, resource, permissions) | python | def update_permissions(self, grp_name, resource, permissions):
"""
Update permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.update_permissions(grp_name, resource, permissions) | [
"def",
"update_permissions",
"(",
"self",
",",
"grp_name",
",",
"resource",
",",
"permissions",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"self",
".",
"project_service",
".",
"update_permissions",
"(",
... | Update permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on
permissions (list): List of permissions to add to the given resource
Raises:
requests.HTTPError on failure. | [
"Update",
"permissions",
"for",
"the",
"group",
"associated",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L466-L480 | train | 35,418 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.delete_user_role | def delete_user_role(self, user, role):
"""
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_user_role(user, role) | python | def delete_user_role(self, user, role):
"""
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_user_role(user, role) | [
"def",
"delete_user_role",
"(",
"self",
",",
"user",
",",
"role",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"self",
".",
"project_service",
".",
"delete_user_role",
"(",
"user",
",",
"role",
")"
] | Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure. | [
"Remove",
"role",
"from",
"given",
"user",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L527-L539 | train | 35,419 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.get_user_groups | def get_user_groups(self, user):
"""
Get user's group memberships.
Args:
user (string): User name.
Returns:
(list): User's groups.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_groups(user) | python | def get_user_groups(self, user):
"""
Get user's group memberships.
Args:
user (string): User name.
Returns:
(list): User's groups.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.get_user_groups(user) | [
"def",
"get_user_groups",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"get_user_groups",
"(",
"user",
")"
] | Get user's group memberships.
Args:
user (string): User name.
Returns:
(list): User's groups.
Raises:
requests.HTTPError on failure. | [
"Get",
"user",
"s",
"group",
"memberships",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L557-L571 | train | 35,420 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote._list_resource | def _list_resource(self, resource):
"""
List all instances of the given resource type.
Use the specific list_<resource>() methods instead:
list_collections()
list_experiments()
list_channels()
list_coordinate_frames()
Args:
resource (intern.resource.boss.BossResource): resource.name may be
an empty string.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return super(BossRemote, self).list_project(resource=resource) | python | def _list_resource(self, resource):
"""
List all instances of the given resource type.
Use the specific list_<resource>() methods instead:
list_collections()
list_experiments()
list_channels()
list_coordinate_frames()
Args:
resource (intern.resource.boss.BossResource): resource.name may be
an empty string.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return super(BossRemote, self).list_project(resource=resource) | [
"def",
"_list_resource",
"(",
"self",
",",
"resource",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"super",
"(",
"BossRemote",
",",
"self",
")",
".",
"list_project",
"(",
"resource",
"=",
"r... | List all instances of the given resource type.
Use the specific list_<resource>() methods instead:
list_collections()
list_experiments()
list_channels()
list_coordinate_frames()
Args:
resource (intern.resource.boss.BossResource): resource.name may be
an empty string.
Returns:
(list)
Raises:
requests.HTTPError on failure. | [
"List",
"all",
"instances",
"of",
"the",
"given",
"resource",
"type",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L608-L629 | train | 35,421 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.list_experiments | def list_experiments(self, collection_name):
"""
List all experiments that belong to a collection.
Args:
collection_name (string): Name of the parent collection.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
exp = ExperimentResource(
name='', collection_name=collection_name, coord_frame='foo')
return self._list_resource(exp) | python | def list_experiments(self, collection_name):
"""
List all experiments that belong to a collection.
Args:
collection_name (string): Name of the parent collection.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
exp = ExperimentResource(
name='', collection_name=collection_name, coord_frame='foo')
return self._list_resource(exp) | [
"def",
"list_experiments",
"(",
"self",
",",
"collection_name",
")",
":",
"exp",
"=",
"ExperimentResource",
"(",
"name",
"=",
"''",
",",
"collection_name",
"=",
"collection_name",
",",
"coord_frame",
"=",
"'foo'",
")",
"return",
"self",
".",
"_list_resource",
... | List all experiments that belong to a collection.
Args:
collection_name (string): Name of the parent collection.
Returns:
(list)
Raises:
requests.HTTPError on failure. | [
"List",
"all",
"experiments",
"that",
"belong",
"to",
"a",
"collection",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L644-L659 | train | 35,422 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.list_channels | def list_channels(self, collection_name, experiment_name):
"""
List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
dont_care = 'image'
chan = ChannelResource(
name='', collection_name=collection_name,
experiment_name=experiment_name, type=dont_care)
return self._list_resource(chan) | python | def list_channels(self, collection_name, experiment_name):
"""
List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
requests.HTTPError on failure.
"""
dont_care = 'image'
chan = ChannelResource(
name='', collection_name=collection_name,
experiment_name=experiment_name, type=dont_care)
return self._list_resource(chan) | [
"def",
"list_channels",
"(",
"self",
",",
"collection_name",
",",
"experiment_name",
")",
":",
"dont_care",
"=",
"'image'",
"chan",
"=",
"ChannelResource",
"(",
"name",
"=",
"''",
",",
"collection_name",
"=",
"collection_name",
",",
"experiment_name",
"=",
"expe... | List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
requests.HTTPError on failure. | [
"List",
"all",
"channels",
"belonging",
"to",
"the",
"named",
"experiment",
"that",
"is",
"part",
"of",
"the",
"named",
"collection",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L661-L680 | train | 35,423 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.create_project | def create_project(self, resource):
"""
Create the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.create(resource) | python | def create_project(self, resource):
"""
Create the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
return self.project_service.create(resource) | [
"def",
"create_project",
"(",
"self",
",",
"resource",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"create",
"(",
"resource",
")"
] | Create the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(intern.resource.boss.BossResource): Returns resource of type
requested on success.
Raises:
requests.HTTPError on failure. | [
"Create",
"the",
"entity",
"described",
"by",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L710-L725 | train | 35,424 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.list_metadata | def list_metadata(self, resource):
"""
List all keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(list)
Raises:
requests.HTTPError on a failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.list(resource) | python | def list_metadata(self, resource):
"""
List all keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(list)
Raises:
requests.HTTPError on a failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.list(resource) | [
"def",
"list_metadata",
"(",
"self",
",",
"resource",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"return",
"self",
".",
"metadata_service",
".",
"list",
"(",
"resource",
")"
] | List all keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
Returns:
(list)
Raises:
requests.HTTPError on a failure. | [
"List",
"all",
"keys",
"associated",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L778-L792 | train | 35,425 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.create_metadata | def create_metadata(self, resource, keys_vals):
"""
Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.create(resource, keys_vals) | python | def create_metadata(self, resource, keys_vals):
"""
Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.create(resource, keys_vals) | [
"def",
"create_metadata",
"(",
"self",
",",
"resource",
",",
"keys_vals",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"self",
".",
"metadata_service",
".",
"create",
"(",
"resource",
",",
"keys_vals",
... | Associates new key-value pairs with the given resource.
Will attempt to add all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to assign to
given resource.
Raises:
HTTPErrorList on failure. | [
"Associates",
"new",
"key",
"-",
"value",
"pairs",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L794-L809 | train | 35,426 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.get_metadata | def get_metadata(self, resource, keys):
"""
Gets the values for given keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Returns:
(dictionary)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.get(resource, keys) | python | def get_metadata(self, resource, keys):
"""
Gets the values for given keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Returns:
(dictionary)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
return self.metadata_service.get(resource, keys) | [
"def",
"get_metadata",
"(",
"self",
",",
"resource",
",",
"keys",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"return",
"self",
".",
"metadata_service",
".",
"get",
"(",
"resource",
",",
"keys",
")"... | Gets the values for given keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Returns:
(dictionary)
Raises:
HTTPErrorList on failure. | [
"Gets",
"the",
"values",
"for",
"given",
"keys",
"associated",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L811-L826 | train | 35,427 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.update_metadata | def update_metadata(self, resource, keys_vals):
"""
Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.update(resource, keys_vals) | python | def update_metadata(self, resource, keys_vals):
"""
Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.update(resource, keys_vals) | [
"def",
"update_metadata",
"(",
"self",
",",
"resource",
",",
"keys_vals",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"self",
".",
"metadata_service",
".",
"update",
"(",
"resource",
",",
"keys_vals",
... | Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
the given resource.
Raises:
HTTPErrorList on failure. | [
"Updates",
"key",
"-",
"value",
"pairs",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L828-L844 | train | 35,428 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.delete_metadata | def delete_metadata(self, resource, keys):
"""
Deletes the given key-value pairs associated with the given resource.
Will attempt to delete all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.delete(resource, keys) | python | def delete_metadata(self, resource, keys):
"""
Deletes the given key-value pairs associated with the given resource.
Will attempt to delete all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Raises:
HTTPErrorList on failure.
"""
self.metadata_service.set_auth(self._token_metadata)
self.metadata_service.delete(resource, keys) | [
"def",
"delete_metadata",
"(",
"self",
",",
"resource",
",",
"keys",
")",
":",
"self",
".",
"metadata_service",
".",
"set_auth",
"(",
"self",
".",
"_token_metadata",
")",
"self",
".",
"metadata_service",
".",
"delete",
"(",
"resource",
",",
"keys",
")"
] | Deletes the given key-value pairs associated with the given resource.
Will attempt to delete all key-value pairs even if some fail.
Args:
resource (intern.resource.boss.BossResource)
keys (list)
Raises:
HTTPErrorList on failure. | [
"Deletes",
"the",
"given",
"key",
"-",
"value",
"pairs",
"associated",
"with",
"the",
"given",
"resource",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L846-L860 | train | 35,429 |
jhuapl-boss/intern | intern/remote/boss/remote.py | BossRemote.parse_bossURI | def parse_bossURI(self, uri): # type: (str) -> Resource
"""
Parse a bossDB URI and handle malform errors.
Arguments:
uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
Returns:
Resource
"""
t = uri.split("://")[1].split("/")
if len(t) is 3:
return self.get_channel(t[2], t[0], t[1])
raise ValueError("Cannot parse URI " + uri + ".") | python | def parse_bossURI(self, uri): # type: (str) -> Resource
"""
Parse a bossDB URI and handle malform errors.
Arguments:
uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
Returns:
Resource
"""
t = uri.split("://")[1].split("/")
if len(t) is 3:
return self.get_channel(t[2], t[0], t[1])
raise ValueError("Cannot parse URI " + uri + ".") | [
"def",
"parse_bossURI",
"(",
"self",
",",
"uri",
")",
":",
"# type: (str) -> Resource",
"t",
"=",
"uri",
".",
"split",
"(",
"\"://\"",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\"/\"",
")",
"if",
"len",
"(",
"t",
")",
"is",
"3",
":",
"return",
"self"... | Parse a bossDB URI and handle malform errors.
Arguments:
uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
Returns:
Resource | [
"Parse",
"a",
"bossDB",
"URI",
"and",
"handle",
"malform",
"errors",
"."
] | d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L862-L876 | train | 35,430 |
rmorshea/spectate | spectate/mvc/base.py | views | def views(model: "Model") -> list:
"""Return a model's views keyed on what events they respond to.
Model views are added by calling :func:`view` on a model.
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
return model._model_views[:] | python | def views(model: "Model") -> list:
"""Return a model's views keyed on what events they respond to.
Model views are added by calling :func:`view` on a model.
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
return model._model_views[:] | [
"def",
"views",
"(",
"model",
":",
"\"Model\"",
")",
"->",
"list",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a Model, not %r.\"",
"%",
"model",
")",
"return",
"model",
".",
"_model_views",
... | Return a model's views keyed on what events they respond to.
Model views are added by calling :func:`view` on a model. | [
"Return",
"a",
"model",
"s",
"views",
"keyed",
"on",
"what",
"events",
"they",
"respond",
"to",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L14-L21 | train | 35,431 |
rmorshea/spectate | spectate/mvc/base.py | view | def view(model: "Model", *functions: Callable) -> Optional[Callable]:
"""A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items, events):
for e in events:
print(e)
items.append(1)
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
def setup(function: Callable):
model._model_views.append(function)
return function
if functions:
for f in functions:
setup(f)
else:
return setup | python | def view(model: "Model", *functions: Callable) -> Optional[Callable]:
"""A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items, events):
for e in events:
print(e)
items.append(1)
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
def setup(function: Callable):
model._model_views.append(function)
return function
if functions:
for f in functions:
setup(f)
else:
return setup | [
"def",
"view",
"(",
"model",
":",
"\"Model\"",
",",
"*",
"functions",
":",
"Callable",
")",
"->",
"Optional",
"[",
"Callable",
"]",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a Model, not %r... | A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items, events):
for e in events:
print(e)
items.append(1) | [
"A",
"decorator",
"for",
"registering",
"a",
"callback",
"to",
"a",
"model"
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L24-L55 | train | 35,432 |
rmorshea/spectate | spectate/mvc/base.py | Control.before | def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._before
self._before = callback
return self | python | def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._before
self._before = callback
return self | [
"def",
"before",
"(",
"self",
",",
"callback",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
")",
"->",
"\"Control\"",
":",
"if",
"isinstance",
"(",
"callback",
",",
"Control",
")",
":",
"callback",
"=",
"callback",
".",
"_before",
"self",
".",
"_bef... | Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing). | [
"Register",
"a",
"control",
"method",
"that",
"reacts",
"before",
"the",
"trigger",
"method",
"is",
"called",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L137-L149 | train | 35,433 |
rmorshea/spectate | spectate/mvc/base.py | Control.after | def after(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._after
self._after = callback
return self | python | def after(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing).
"""
if isinstance(callback, Control):
callback = callback._after
self._after = callback
return self | [
"def",
"after",
"(",
"self",
",",
"callback",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
")",
"->",
"\"Control\"",
":",
"if",
"isinstance",
"(",
"callback",
",",
"Control",
")",
":",
"callback",
"=",
"callback",
".",
"_after",
"self",
".",
"_after... | Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method with that name when reacting (useful when subclassing). | [
"Register",
"a",
"control",
"method",
"that",
"reacts",
"after",
"the",
"trigger",
"method",
"is",
"called",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L151-L163 | train | 35,434 |
witchard/grole | grole.py | serve_static | def serve_static(app, base_url, base_path, index=False):
"""
Serve a directory statically
Parameters:
* app: Grole application object
* base_url: Base URL to serve from, e.g. /static
* base_path: Base path to look for files in
* index: Provide simple directory indexes if True
"""
@app.route(base_url + '/(.*)')
def serve(env, req):
"""
Static files
"""
try:
base = pathlib.Path(base_path).resolve()
path = (base / req.match.group(1)).resolve()
except FileNotFoundError:
return Response(None, 404, 'Not Found')
# Don't let bad paths through
if base == path or base in path.parents:
if path.is_file():
return ResponseFile(str(path))
if index and path.is_dir():
if base == path:
ret = ''
else:
ret = '<a href="../">../</a><br/>\r\n'
for item in path.iterdir():
name = item.parts[-1]
if item.is_dir():
name += '/'
ret += '<a href="{}">{}</a><br/>\r\n'.format(urllib.parse.quote(name), html.escape(name))
ret = ResponseString(ret, 'text/html')
return ret
return Response(None, 404, 'Not Found') | python | def serve_static(app, base_url, base_path, index=False):
"""
Serve a directory statically
Parameters:
* app: Grole application object
* base_url: Base URL to serve from, e.g. /static
* base_path: Base path to look for files in
* index: Provide simple directory indexes if True
"""
@app.route(base_url + '/(.*)')
def serve(env, req):
"""
Static files
"""
try:
base = pathlib.Path(base_path).resolve()
path = (base / req.match.group(1)).resolve()
except FileNotFoundError:
return Response(None, 404, 'Not Found')
# Don't let bad paths through
if base == path or base in path.parents:
if path.is_file():
return ResponseFile(str(path))
if index and path.is_dir():
if base == path:
ret = ''
else:
ret = '<a href="../">../</a><br/>\r\n'
for item in path.iterdir():
name = item.parts[-1]
if item.is_dir():
name += '/'
ret += '<a href="{}">{}</a><br/>\r\n'.format(urllib.parse.quote(name), html.escape(name))
ret = ResponseString(ret, 'text/html')
return ret
return Response(None, 404, 'Not Found') | [
"def",
"serve_static",
"(",
"app",
",",
"base_url",
",",
"base_path",
",",
"index",
"=",
"False",
")",
":",
"@",
"app",
".",
"route",
"(",
"base_url",
"+",
"'/(.*)'",
")",
"def",
"serve",
"(",
"env",
",",
"req",
")",
":",
"\"\"\"\n Static files\n ... | Serve a directory statically
Parameters:
* app: Grole application object
* base_url: Base URL to serve from, e.g. /static
* base_path: Base path to look for files in
* index: Provide simple directory indexes if True | [
"Serve",
"a",
"directory",
"statically"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L242-L282 | train | 35,435 |
witchard/grole | grole.py | serve_doc | def serve_doc(app, url):
"""
Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at
"""
@app.route(url, doc=False)
def index(env, req):
ret = ''
for d in env['doc']:
ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d)
return ret | python | def serve_doc(app, url):
"""
Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at
"""
@app.route(url, doc=False)
def index(env, req):
ret = ''
for d in env['doc']:
ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d)
return ret | [
"def",
"serve_doc",
"(",
"app",
",",
"url",
")",
":",
"@",
"app",
".",
"route",
"(",
"url",
",",
"doc",
"=",
"False",
")",
"def",
"index",
"(",
"env",
",",
"req",
")",
":",
"ret",
"=",
"''",
"for",
"d",
"in",
"env",
"[",
"'doc'",
"]",
":",
... | Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at | [
"Serve",
"API",
"documentation",
"extracted",
"from",
"request",
"handler",
"docstrings"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L284-L297 | train | 35,436 |
witchard/grole | grole.py | parse_args | def parse_args(args=sys.argv[1:]):
"""
Parse command line arguments for Grole server running as static file server
"""
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help='address to listen on, default localhost',
default='localhost')
parser.add_argument('-p', '--port', help='port to listen on, default 1234',
default=1234, type=int)
parser.add_argument('-d', '--directory', help='directory to serve, default .',
default='.')
parser.add_argument('-n', '--noindex', help='do not show directory indexes',
default=False, action='store_true')
loglevel = parser.add_mutually_exclusive_group()
loglevel.add_argument('-v', '--verbose', help='verbose logging',
default=False, action='store_true')
loglevel.add_argument('-q', '--quiet', help='quiet logging',
default=False, action='store_true')
return parser.parse_args(args) | python | def parse_args(args=sys.argv[1:]):
"""
Parse command line arguments for Grole server running as static file server
"""
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help='address to listen on, default localhost',
default='localhost')
parser.add_argument('-p', '--port', help='port to listen on, default 1234',
default=1234, type=int)
parser.add_argument('-d', '--directory', help='directory to serve, default .',
default='.')
parser.add_argument('-n', '--noindex', help='do not show directory indexes',
default=False, action='store_true')
loglevel = parser.add_mutually_exclusive_group()
loglevel.add_argument('-v', '--verbose', help='verbose logging',
default=False, action='store_true')
loglevel.add_argument('-q', '--quiet', help='quiet logging',
default=False, action='store_true')
return parser.parse_args(args) | [
"def",
"parse_args",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--address'",
",",
"help",
"=",
"'address to listen on,... | Parse command line arguments for Grole server running as static file server | [
"Parse",
"command",
"line",
"arguments",
"for",
"Grole",
"server",
"running",
"as",
"static",
"file",
"server"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L413-L431 | train | 35,437 |
witchard/grole | grole.py | main | def main(args=sys.argv[1:]):
"""
Run Grole static file server
"""
args = parse_args(args)
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
elif args.quiet:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO)
app = Grole()
serve_static(app, '', args.directory, not args.noindex)
app.run(args.address, args.port) | python | def main(args=sys.argv[1:]):
"""
Run Grole static file server
"""
args = parse_args(args)
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
elif args.quiet:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO)
app = Grole()
serve_static(app, '', args.directory, not args.noindex)
app.run(args.address, args.port) | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"args",
"=",
"parse_args",
"(",
"args",
")",
"if",
"args",
".",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"el... | Run Grole static file server | [
"Run",
"Grole",
"static",
"file",
"server"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L433-L446 | train | 35,438 |
witchard/grole | grole.py | Request._read | async def _read(self, reader):
"""
Parses HTTP request into member variables
"""
start_line = await self._readline(reader)
self.method, self.location, self.version = start_line.decode().split()
path_query = urllib.parse.unquote(self.location).split('?', 1)
self.path = path_query[0]
self.query = {}
if len(path_query) > 1:
for q in path_query[1].split('&'):
try:
k, v = q.split('=', 1)
self.query[k] = v
except ValueError:
self.query[q] = None
self.headers = {}
while True:
header_raw = await self._readline(reader)
if header_raw.strip() == b'':
break
header = header_raw.decode().split(':', 1)
self.headers[header[0]] = header[1].strip()
# TODO implement chunked handling
self.data = b''
await self._buffer_body(reader) | python | async def _read(self, reader):
"""
Parses HTTP request into member variables
"""
start_line = await self._readline(reader)
self.method, self.location, self.version = start_line.decode().split()
path_query = urllib.parse.unquote(self.location).split('?', 1)
self.path = path_query[0]
self.query = {}
if len(path_query) > 1:
for q in path_query[1].split('&'):
try:
k, v = q.split('=', 1)
self.query[k] = v
except ValueError:
self.query[q] = None
self.headers = {}
while True:
header_raw = await self._readline(reader)
if header_raw.strip() == b'':
break
header = header_raw.decode().split(':', 1)
self.headers[header[0]] = header[1].strip()
# TODO implement chunked handling
self.data = b''
await self._buffer_body(reader) | [
"async",
"def",
"_read",
"(",
"self",
",",
"reader",
")",
":",
"start_line",
"=",
"await",
"self",
".",
"_readline",
"(",
"reader",
")",
"self",
".",
"method",
",",
"self",
".",
"location",
",",
"self",
".",
"version",
"=",
"start_line",
".",
"decode",... | Parses HTTP request into member variables | [
"Parses",
"HTTP",
"request",
"into",
"member",
"variables"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L40-L66 | train | 35,439 |
witchard/grole | grole.py | Request._buffer_body | async def _buffer_body(self, reader):
"""
Buffers the body of the request
"""
remaining = int(self.headers.get('Content-Length', 0))
if remaining > 0:
try:
self.data = await reader.readexactly(remaining)
except asyncio.IncompleteReadError:
raise EOFError() | python | async def _buffer_body(self, reader):
"""
Buffers the body of the request
"""
remaining = int(self.headers.get('Content-Length', 0))
if remaining > 0:
try:
self.data = await reader.readexactly(remaining)
except asyncio.IncompleteReadError:
raise EOFError() | [
"async",
"def",
"_buffer_body",
"(",
"self",
",",
"reader",
")",
":",
"remaining",
"=",
"int",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'Content-Length'",
",",
"0",
")",
")",
"if",
"remaining",
">",
"0",
":",
"try",
":",
"self",
".",
"data",
... | Buffers the body of the request | [
"Buffers",
"the",
"body",
"of",
"the",
"request"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L77-L86 | train | 35,440 |
witchard/grole | grole.py | Grole.route | def route(self, path_regex, methods=['GET'], doc=True):
"""
Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc structure
"""
def register_func(func):
"""
Decorator implementation
"""
if doc:
self.env['doc'].append({'url': path_regex, 'methods': ', '.join(methods), 'doc': func.__doc__})
for method in methods:
self._handlers[method].append((re.compile(path_regex), func))
return func # Return the original function
return register_func | python | def route(self, path_regex, methods=['GET'], doc=True):
"""
Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc structure
"""
def register_func(func):
"""
Decorator implementation
"""
if doc:
self.env['doc'].append({'url': path_regex, 'methods': ', '.join(methods), 'doc': func.__doc__})
for method in methods:
self._handlers[method].append((re.compile(path_regex), func))
return func # Return the original function
return register_func | [
"def",
"route",
"(",
"self",
",",
"path_regex",
",",
"methods",
"=",
"[",
"'GET'",
"]",
",",
"doc",
"=",
"True",
")",
":",
"def",
"register_func",
"(",
"func",
")",
":",
"\"\"\"\n Decorator implementation\n \"\"\"",
"if",
"doc",
":",
"sel... | Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc structure | [
"Decorator",
"to",
"register",
"a",
"handler"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L316-L334 | train | 35,441 |
witchard/grole | grole.py | Grole._handle | async def _handle(self, reader, writer):
"""
Handle a single TCP connection
Parses requests, finds appropriate handlers and returns responses
"""
peer = writer.get_extra_info('peername')
self._logger.debug('New connection from {}'.format(peer))
try:
# Loop handling requests
while True:
# Read the request
req = Request()
await req._read(reader)
# Find and execute handler
res = None
for path_regex, handler in self._handlers.get(req.method, []):
match = path_regex.fullmatch(req.path)
if match:
req.match = match
try:
if inspect.iscoroutinefunction(handler):
res = await handler(self.env, req)
else:
res = handler(self.env, req)
if not isinstance(res, Response):
res = Response(data=res)
except:
# Error - log it and return 500
self._logger.error(traceback.format_exc())
res = Response(code=500, reason='Internal Server Error')
break
# No handler - send 404
if res == None:
res = Response(code=404, reason='Not Found')
# Respond
await res._write(writer)
self._logger.info('{}: {} -> {}'.format(peer, req.path, res.code))
except EOFError:
self._logger.debug('Connection closed from {}'.format(peer))
except Exception as e:
self._logger.error('Connection error ({}) from {}'.format(e, peer))
writer.close() | python | async def _handle(self, reader, writer):
"""
Handle a single TCP connection
Parses requests, finds appropriate handlers and returns responses
"""
peer = writer.get_extra_info('peername')
self._logger.debug('New connection from {}'.format(peer))
try:
# Loop handling requests
while True:
# Read the request
req = Request()
await req._read(reader)
# Find and execute handler
res = None
for path_regex, handler in self._handlers.get(req.method, []):
match = path_regex.fullmatch(req.path)
if match:
req.match = match
try:
if inspect.iscoroutinefunction(handler):
res = await handler(self.env, req)
else:
res = handler(self.env, req)
if not isinstance(res, Response):
res = Response(data=res)
except:
# Error - log it and return 500
self._logger.error(traceback.format_exc())
res = Response(code=500, reason='Internal Server Error')
break
# No handler - send 404
if res == None:
res = Response(code=404, reason='Not Found')
# Respond
await res._write(writer)
self._logger.info('{}: {} -> {}'.format(peer, req.path, res.code))
except EOFError:
self._logger.debug('Connection closed from {}'.format(peer))
except Exception as e:
self._logger.error('Connection error ({}) from {}'.format(e, peer))
writer.close() | [
"async",
"def",
"_handle",
"(",
"self",
",",
"reader",
",",
"writer",
")",
":",
"peer",
"=",
"writer",
".",
"get_extra_info",
"(",
"'peername'",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'New connection from {}'",
".",
"format",
"(",
"peer",
")",
... | Handle a single TCP connection
Parses requests, finds appropriate handlers and returns responses | [
"Handle",
"a",
"single",
"TCP",
"connection"
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L336-L381 | train | 35,442 |
witchard/grole | grole.py | Grole.run | def run(self, host='localhost', port=1234):
"""
Launch the server. Will run forever accepting connections until interrupted.
Parameters:
* host: The host to listen on
* port: The port to listen on
"""
# Setup loop
loop = asyncio.get_event_loop()
coro = asyncio.start_server(self._handle, host, port, loop=loop)
try:
server = loop.run_until_complete(coro)
except Exception as e:
self._logger.error('Could not launch server: {}'.format(e))
return
# Run the server
self._logger.info('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close() | python | def run(self, host='localhost', port=1234):
"""
Launch the server. Will run forever accepting connections until interrupted.
Parameters:
* host: The host to listen on
* port: The port to listen on
"""
# Setup loop
loop = asyncio.get_event_loop()
coro = asyncio.start_server(self._handle, host, port, loop=loop)
try:
server = loop.run_until_complete(coro)
except Exception as e:
self._logger.error('Could not launch server: {}'.format(e))
return
# Run the server
self._logger.info('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close() | [
"def",
"run",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"1234",
")",
":",
"# Setup loop",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"coro",
"=",
"asyncio",
".",
"start_server",
"(",
"self",
".",
"_handle",
",",
"hos... | Launch the server. Will run forever accepting connections until interrupted.
Parameters:
* host: The host to listen on
* port: The port to listen on | [
"Launch",
"the",
"server",
".",
"Will",
"run",
"forever",
"accepting",
"connections",
"until",
"interrupted",
"."
] | 54c0bd13e4d4c74a2997ec4254527d937d6e0565 | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L383-L411 | train | 35,443 |
rmorshea/spectate | spectate/mvc/events.py | hold | def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]:
"""Temporarilly withold change events in a modifiable list.
All changes that are captured within a "hold" context are forwarded to a list
which is yielded to the user before being sent to views of the given ``model``.
If desired, the user may modify the list of events before the context is left in
order to change the events that are ultimately sent to the model's views.
Parameters:
model:
The model object whose change events will be temporarilly witheld.
reducer:
A function for modifying the events list at the end of the context.
Its signature is ``(model, events) -> new_events`` where ``model`` is the
given model, ``events`` is the complete list of events produced in the
context, and the returned ``new_events`` is a list of events that will
actuall be distributed to views.
Notes:
All changes witheld from views will be sent as a single notification. For
example if you view a :class:`specate.mvc.models.List` and its ``append()``
method is called three times within a :func:`hold` context,
Examples:
Note how the event from ``l.append(1)`` is omitted from the printed statements.
.. code-block:: python
from spectate import mvc
l = mvc.List()
mvc.view(d, lambda d, e: list(map(print, e)))
with mvc.hold(l) as events:
l.append(1)
l.append(2)
del events[0]
.. code-block:: text
{'index': 1, 'old': Undefined, 'new': 2}
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
events = []
restore = model.__dict__.get("_notify_model_views")
model._notify_model_views = lambda e: events.extend(e)
try:
yield events
finally:
if restore is None:
del model._notify_model_views
else:
model._notify_model_views = restore
events = tuple(events)
if reducer is not None:
events = tuple(map(Data, reducer(model, events)))
model._notify_model_views(events) | python | def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]:
"""Temporarilly withold change events in a modifiable list.
All changes that are captured within a "hold" context are forwarded to a list
which is yielded to the user before being sent to views of the given ``model``.
If desired, the user may modify the list of events before the context is left in
order to change the events that are ultimately sent to the model's views.
Parameters:
model:
The model object whose change events will be temporarilly witheld.
reducer:
A function for modifying the events list at the end of the context.
Its signature is ``(model, events) -> new_events`` where ``model`` is the
given model, ``events`` is the complete list of events produced in the
context, and the returned ``new_events`` is a list of events that will
actuall be distributed to views.
Notes:
All changes witheld from views will be sent as a single notification. For
example if you view a :class:`specate.mvc.models.List` and its ``append()``
method is called three times within a :func:`hold` context,
Examples:
Note how the event from ``l.append(1)`` is omitted from the printed statements.
.. code-block:: python
from spectate import mvc
l = mvc.List()
mvc.view(d, lambda d, e: list(map(print, e)))
with mvc.hold(l) as events:
l.append(1)
l.append(2)
del events[0]
.. code-block:: text
{'index': 1, 'old': Undefined, 'new': 2}
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
events = []
restore = model.__dict__.get("_notify_model_views")
model._notify_model_views = lambda e: events.extend(e)
try:
yield events
finally:
if restore is None:
del model._notify_model_views
else:
model._notify_model_views = restore
events = tuple(events)
if reducer is not None:
events = tuple(map(Data, reducer(model, events)))
model._notify_model_views(events) | [
"def",
"hold",
"(",
"model",
":",
"Model",
",",
"reducer",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
")",
"->",
"Iterator",
"[",
"list",
"]",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
... | Temporarilly withold change events in a modifiable list.
All changes that are captured within a "hold" context are forwarded to a list
which is yielded to the user before being sent to views of the given ``model``.
If desired, the user may modify the list of events before the context is left in
order to change the events that are ultimately sent to the model's views.
Parameters:
model:
The model object whose change events will be temporarilly witheld.
reducer:
A function for modifying the events list at the end of the context.
Its signature is ``(model, events) -> new_events`` where ``model`` is the
given model, ``events`` is the complete list of events produced in the
context, and the returned ``new_events`` is a list of events that will
actuall be distributed to views.
Notes:
All changes witheld from views will be sent as a single notification. For
example if you view a :class:`specate.mvc.models.List` and its ``append()``
method is called three times within a :func:`hold` context,
Examples:
Note how the event from ``l.append(1)`` is omitted from the printed statements.
.. code-block:: python
from spectate import mvc
l = mvc.List()
mvc.view(d, lambda d, e: list(map(print, e)))
with mvc.hold(l) as events:
l.append(1)
l.append(2)
del events[0]
.. code-block:: text
{'index': 1, 'old': Undefined, 'new': 2} | [
"Temporarilly",
"withold",
"change",
"events",
"in",
"a",
"modifiable",
"list",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L12-L76 | train | 35,444 |
rmorshea/spectate | spectate/mvc/events.py | rollback | def rollback(
model: Model, undo: Optional[Callable] = None, *args, **kwargs
) -> Iterator[list]:
"""Withold events if an error occurs.
Generall operate
Parameters:
model:
The model object whose change events may be witheld.
undo:
An optional function for reversing any changes that may have taken place.
Its signature is ``(model, events, error)`` where ``model`` is the given
model, ``event`` is a tuple of all the events that took place, and ``error``
is the exception that was riased. Any changes that you make to the model
within this function will not produce events.
Examples:
Simple supression of events:
.. code-block:: python
from spectate import mvc
d = mvc.Dict()
@mvc.view(d)
def should_not_be_called(d, events):
# we never call this view
assert False
try:
with mvc.rollback(d):
d["a"] = 1
d["b"] # key doesn't exist
except KeyError:
pass
Undo changes for a dictionary:
.. code-block:: python
from spectate import mvc
def undo_dict_changes(model, events, error):
seen = set()
for e in reversed(events):
if e.old is mvc.Undefined:
del model[e.key]
else:
model[e.key] = e.old
try:
with mvc.rollback(d, undo=undo_dict_changes):
d["a"] = 1
d["b"] = 2
print(d)
d["c"]
except KeyError:
pass
print(d)
.. code-block:: python
{'a': 1, 'b': 2}
{}
"""
with hold(model, *args, **kwargs) as events:
try:
yield events
except Exception as error:
if undo is not None:
with mute(model):
undo(model, tuple(events), error)
events.clear()
raise | python | def rollback(
model: Model, undo: Optional[Callable] = None, *args, **kwargs
) -> Iterator[list]:
"""Withold events if an error occurs.
Generall operate
Parameters:
model:
The model object whose change events may be witheld.
undo:
An optional function for reversing any changes that may have taken place.
Its signature is ``(model, events, error)`` where ``model`` is the given
model, ``event`` is a tuple of all the events that took place, and ``error``
is the exception that was riased. Any changes that you make to the model
within this function will not produce events.
Examples:
Simple supression of events:
.. code-block:: python
from spectate import mvc
d = mvc.Dict()
@mvc.view(d)
def should_not_be_called(d, events):
# we never call this view
assert False
try:
with mvc.rollback(d):
d["a"] = 1
d["b"] # key doesn't exist
except KeyError:
pass
Undo changes for a dictionary:
.. code-block:: python
from spectate import mvc
def undo_dict_changes(model, events, error):
seen = set()
for e in reversed(events):
if e.old is mvc.Undefined:
del model[e.key]
else:
model[e.key] = e.old
try:
with mvc.rollback(d, undo=undo_dict_changes):
d["a"] = 1
d["b"] = 2
print(d)
d["c"]
except KeyError:
pass
print(d)
.. code-block:: python
{'a': 1, 'b': 2}
{}
"""
with hold(model, *args, **kwargs) as events:
try:
yield events
except Exception as error:
if undo is not None:
with mute(model):
undo(model, tuple(events), error)
events.clear()
raise | [
"def",
"rollback",
"(",
"model",
":",
"Model",
",",
"undo",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Iterator",
"[",
"list",
"]",
":",
"with",
"hold",
"(",
"model",
",",
"*",
"args... | Withold events if an error occurs.
Generall operate
Parameters:
model:
The model object whose change events may be witheld.
undo:
An optional function for reversing any changes that may have taken place.
Its signature is ``(model, events, error)`` where ``model`` is the given
model, ``event`` is a tuple of all the events that took place, and ``error``
is the exception that was riased. Any changes that you make to the model
within this function will not produce events.
Examples:
Simple supression of events:
.. code-block:: python
from spectate import mvc
d = mvc.Dict()
@mvc.view(d)
def should_not_be_called(d, events):
# we never call this view
assert False
try:
with mvc.rollback(d):
d["a"] = 1
d["b"] # key doesn't exist
except KeyError:
pass
Undo changes for a dictionary:
.. code-block:: python
from spectate import mvc
def undo_dict_changes(model, events, error):
seen = set()
for e in reversed(events):
if e.old is mvc.Undefined:
del model[e.key]
else:
model[e.key] = e.old
try:
with mvc.rollback(d, undo=undo_dict_changes):
d["a"] = 1
d["b"] = 2
print(d)
d["c"]
except KeyError:
pass
print(d)
.. code-block:: python
{'a': 1, 'b': 2}
{} | [
"Withold",
"events",
"if",
"an",
"error",
"occurs",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L80-L156 | train | 35,445 |
rmorshea/spectate | spectate/mvc/events.py | mute | def mute(model: Model):
"""Block a model's views from being notified.
All changes within a "mute" context will be blocked. No content is yielded to the
user as in :func:`hold`, and the views of the model are never notified that changes
took place.
Parameters:
mode: The model whose change events will be blocked.
Examples:
The view is never called due to the :func:`mute` context:
.. code-block:: python
from spectate import mvc
l = mvc.List()
@mvc.view(l)
def raises(events):
raise ValueError("Events occured!")
with mvc.mute(l):
l.append(1)
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
restore = model.__dict__.get("_notify_model_views")
model._notify_model_views = lambda e: None
try:
yield
finally:
if restore is None:
del model._notify_model_views
else:
model._notify_model_views = restore | python | def mute(model: Model):
"""Block a model's views from being notified.
All changes within a "mute" context will be blocked. No content is yielded to the
user as in :func:`hold`, and the views of the model are never notified that changes
took place.
Parameters:
mode: The model whose change events will be blocked.
Examples:
The view is never called due to the :func:`mute` context:
.. code-block:: python
from spectate import mvc
l = mvc.List()
@mvc.view(l)
def raises(events):
raise ValueError("Events occured!")
with mvc.mute(l):
l.append(1)
"""
if not isinstance(model, Model):
raise TypeError("Expected a Model, not %r." % model)
restore = model.__dict__.get("_notify_model_views")
model._notify_model_views = lambda e: None
try:
yield
finally:
if restore is None:
del model._notify_model_views
else:
model._notify_model_views = restore | [
"def",
"mute",
"(",
"model",
":",
"Model",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a Model, not %r.\"",
"%",
"model",
")",
"restore",
"=",
"model",
".",
"__dict__",
".",
"get",
"("... | Block a model's views from being notified.
All changes within a "mute" context will be blocked. No content is yielded to the
user as in :func:`hold`, and the views of the model are never notified that changes
took place.
Parameters:
mode: The model whose change events will be blocked.
Examples:
The view is never called due to the :func:`mute` context:
.. code-block:: python
from spectate import mvc
l = mvc.List()
@mvc.view(l)
def raises(events):
raise ValueError("Events occured!")
with mvc.mute(l):
l.append(1) | [
"Block",
"a",
"model",
"s",
"views",
"from",
"being",
"notified",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L160-L197 | train | 35,446 |
rmorshea/spectate | spectate/core.py | expose | def expose(*methods):
"""A decorator for exposing the methods of a class.
Parameters
----------
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
decorator : function
A function accepting one argument - the class whose methods will be
exposed - and which returns a new :class:`Watchable` that will
notify a :class:`Spectator` when those methods are called.
Notes
-----
This is essentially a decorator version of :func:`expose_as`
"""
def setup(base):
return expose_as(base.__name__, base, *methods)
return setup | python | def expose(*methods):
"""A decorator for exposing the methods of a class.
Parameters
----------
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
decorator : function
A function accepting one argument - the class whose methods will be
exposed - and which returns a new :class:`Watchable` that will
notify a :class:`Spectator` when those methods are called.
Notes
-----
This is essentially a decorator version of :func:`expose_as`
"""
def setup(base):
return expose_as(base.__name__, base, *methods)
return setup | [
"def",
"expose",
"(",
"*",
"methods",
")",
":",
"def",
"setup",
"(",
"base",
")",
":",
"return",
"expose_as",
"(",
"base",
".",
"__name__",
",",
"base",
",",
"*",
"methods",
")",
"return",
"setup"
] | A decorator for exposing the methods of a class.
Parameters
----------
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
decorator : function
A function accepting one argument - the class whose methods will be
exposed - and which returns a new :class:`Watchable` that will
notify a :class:`Spectator` when those methods are called.
Notes
-----
This is essentially a decorator version of :func:`expose_as` | [
"A",
"decorator",
"for",
"exposing",
"the",
"methods",
"of",
"a",
"class",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L250-L273 | train | 35,447 |
rmorshea/spectate | spectate/core.py | expose_as | def expose_as(name, base, *methods):
"""Return a new type with certain methods that are exposed to callback registration.
Parameters
----------
name : str
The name of the new type.
base : type
A type such as list or dict.
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
exposed : obj:
A :class:`Watchable` with methods that will notify a :class:`Spectator`.
"""
classdict = {}
for method in methods:
if not hasattr(base, method):
raise AttributeError(
"Cannot expose '%s', because '%s' "
"instances lack this method" % (method, base.__name__)
)
else:
classdict[method] = MethodSpectator(getattr(base, method), method)
return type(name, (base, Watchable), classdict) | python | def expose_as(name, base, *methods):
"""Return a new type with certain methods that are exposed to callback registration.
Parameters
----------
name : str
The name of the new type.
base : type
A type such as list or dict.
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
exposed : obj:
A :class:`Watchable` with methods that will notify a :class:`Spectator`.
"""
classdict = {}
for method in methods:
if not hasattr(base, method):
raise AttributeError(
"Cannot expose '%s', because '%s' "
"instances lack this method" % (method, base.__name__)
)
else:
classdict[method] = MethodSpectator(getattr(base, method), method)
return type(name, (base, Watchable), classdict) | [
"def",
"expose_as",
"(",
"name",
",",
"base",
",",
"*",
"methods",
")",
":",
"classdict",
"=",
"{",
"}",
"for",
"method",
"in",
"methods",
":",
"if",
"not",
"hasattr",
"(",
"base",
",",
"method",
")",
":",
"raise",
"AttributeError",
"(",
"\"Cannot expo... | Return a new type with certain methods that are exposed to callback registration.
Parameters
----------
name : str
The name of the new type.
base : type
A type such as list or dict.
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
exposed : obj:
A :class:`Watchable` with methods that will notify a :class:`Spectator`. | [
"Return",
"a",
"new",
"type",
"with",
"certain",
"methods",
"that",
"are",
"exposed",
"to",
"callback",
"registration",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L276-L302 | train | 35,448 |
rmorshea/spectate | spectate/core.py | Spectator.callback | def callback(self, name, before=None, after=None):
"""Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
Parameters
----------
name: str
The name of the method to which callbacks should respond.
before: None or callable
A callable of the form ``before(obj, call)`` where ``obj`` is
the instance which called a watched method, and ``call`` is a
:class:`Data` containing the name of the called method, along with
its positional and keyword arguments under the attributes "name"
"args", and "kwargs" respectively.
after: None or callable
A callable of the form ``after(obj, answer)`` where ``obj` is
the instance which alled a watched method, and ``answer`` is a
:class:`Data` containing the name of the called method, along with
the value it returned, and data ``before`` may have returned
under the attributes "name", "value", and "before" respectively.
"""
if isinstance(name, (list, tuple)):
for name in name:
self.callback(name, before, after)
else:
if not isinstance(getattr(self.subclass, name), MethodSpectator):
raise ValueError("No method specator for '%s'" % name)
if before is None and after is None:
raise ValueError("No pre or post '%s' callbacks were given" % name)
elif before is not None and not callable(before):
raise ValueError("Expected a callable, not %r." % before)
elif after is not None and not callable(after):
raise ValueError("Expected a callable, not %r." % after)
elif before is None and after is None:
raise ValueError("No callbacks were given.")
if name in self._callback_registry:
callback_list = self._callback_registry[name]
else:
callback_list = []
self._callback_registry[name] = callback_list
callback_list.append((before, after)) | python | def callback(self, name, before=None, after=None):
"""Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
Parameters
----------
name: str
The name of the method to which callbacks should respond.
before: None or callable
A callable of the form ``before(obj, call)`` where ``obj`` is
the instance which called a watched method, and ``call`` is a
:class:`Data` containing the name of the called method, along with
its positional and keyword arguments under the attributes "name"
"args", and "kwargs" respectively.
after: None or callable
A callable of the form ``after(obj, answer)`` where ``obj` is
the instance which alled a watched method, and ``answer`` is a
:class:`Data` containing the name of the called method, along with
the value it returned, and data ``before`` may have returned
under the attributes "name", "value", and "before" respectively.
"""
if isinstance(name, (list, tuple)):
for name in name:
self.callback(name, before, after)
else:
if not isinstance(getattr(self.subclass, name), MethodSpectator):
raise ValueError("No method specator for '%s'" % name)
if before is None and after is None:
raise ValueError("No pre or post '%s' callbacks were given" % name)
elif before is not None and not callable(before):
raise ValueError("Expected a callable, not %r." % before)
elif after is not None and not callable(after):
raise ValueError("Expected a callable, not %r." % after)
elif before is None and after is None:
raise ValueError("No callbacks were given.")
if name in self._callback_registry:
callback_list = self._callback_registry[name]
else:
callback_list = []
self._callback_registry[name] = callback_list
callback_list.append((before, after)) | [
"def",
"callback",
"(",
"self",
",",
"name",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"name",
"in",
"name",
":",
"self",
".",
"callback... | Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
Parameters
----------
name: str
The name of the method to which callbacks should respond.
before: None or callable
A callable of the form ``before(obj, call)`` where ``obj`` is
the instance which called a watched method, and ``call`` is a
:class:`Data` containing the name of the called method, along with
its positional and keyword arguments under the attributes "name"
"args", and "kwargs" respectively.
after: None or callable
A callable of the form ``after(obj, answer)`` where ``obj` is
the instance which alled a watched method, and ``answer`` is a
:class:`Data` containing the name of the called method, along with
the value it returned, and data ``before`` may have returned
under the attributes "name", "value", and "before" respectively. | [
"Add",
"a",
"callback",
"pair",
"to",
"this",
"spectator",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L74-L117 | train | 35,449 |
rmorshea/spectate | spectate/core.py | Spectator.remove_callback | def remove_callback(self, name, before=None, after=None):
"""Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parameters
----------
name: str
The name of the method the callback pair is associated with.
before: None or callable
The beforeback that was originally registered to the given method.
after: None or callable
The afterback that was originally registered to the given method.
"""
if isinstance(name, (list, tuple)):
for name in name:
self.remove_callback(name, before, after)
elif before is None and after is None:
del self._callback_registry[name]
else:
if name in self._callback_registry:
callback_list = self._callback_registry[name]
else:
callback_list = []
self._callback_registry[name] = callback_list
callback_list.remove((before, after))
if len(callback_list) == 0:
# cleanup if all callbacks are gone
del self._callback_registry[name] | python | def remove_callback(self, name, before=None, after=None):
"""Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parameters
----------
name: str
The name of the method the callback pair is associated with.
before: None or callable
The beforeback that was originally registered to the given method.
after: None or callable
The afterback that was originally registered to the given method.
"""
if isinstance(name, (list, tuple)):
for name in name:
self.remove_callback(name, before, after)
elif before is None and after is None:
del self._callback_registry[name]
else:
if name in self._callback_registry:
callback_list = self._callback_registry[name]
else:
callback_list = []
self._callback_registry[name] = callback_list
callback_list.remove((before, after))
if len(callback_list) == 0:
# cleanup if all callbacks are gone
del self._callback_registry[name] | [
"def",
"remove_callback",
"(",
"self",
",",
"name",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"name",
"in",
"name",
":",
"self",
".",
"r... | Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parameters
----------
name: str
The name of the method the callback pair is associated with.
before: None or callable
The beforeback that was originally registered to the given method.
after: None or callable
The afterback that was originally registered to the given method. | [
"Remove",
"a",
"beforeback",
"and",
"afterback",
"pair",
"from",
"this",
"Spectator"
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L119-L149 | train | 35,450 |
rmorshea/spectate | spectate/core.py | Spectator.call | def call(self, obj, name, method, args, kwargs):
"""Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
kwargs: dict
The keyword args that will be passed to the base method
"""
if name in self._callback_registry:
beforebacks, afterbacks = zip(*self._callback_registry.get(name, []))
hold = []
for b in beforebacks:
if b is not None:
call = Data(name=name, kwargs=kwargs.copy(), args=args)
v = b(obj, call)
else:
v = None
hold.append(v)
out = method(*args, **kwargs)
for a, bval in zip(afterbacks, hold):
if a is not None:
a(obj, Data(before=bval, name=name, value=out))
elif callable(bval):
# the beforeback's return value was an
# afterback that expects to be called
bval(out)
return out
else:
return method(*args, **kwargs) | python | def call(self, obj, name, method, args, kwargs):
"""Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
kwargs: dict
The keyword args that will be passed to the base method
"""
if name in self._callback_registry:
beforebacks, afterbacks = zip(*self._callback_registry.get(name, []))
hold = []
for b in beforebacks:
if b is not None:
call = Data(name=name, kwargs=kwargs.copy(), args=args)
v = b(obj, call)
else:
v = None
hold.append(v)
out = method(*args, **kwargs)
for a, bval in zip(afterbacks, hold):
if a is not None:
a(obj, Data(before=bval, name=name, value=out))
elif callable(bval):
# the beforeback's return value was an
# afterback that expects to be called
bval(out)
return out
else:
return method(*args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"obj",
",",
"name",
",",
"method",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"_callback_registry",
":",
"beforebacks",
",",
"afterbacks",
"=",
"zip",
"(",
"*",
"self",
".",
"_callback_regist... | Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
kwargs: dict
The keyword args that will be passed to the base method | [
"Trigger",
"a",
"method",
"along",
"with",
"its",
"beforebacks",
"and",
"afterbacks",
"."
] | 79bd84dd8d00889015ce1d1e190db865a02cdb93 | https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L151-L186 | train | 35,451 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | cut_to_length | def cut_to_length(text, length, delim):
"""Shorten given text on first delimiter after given number
of characters.
"""
cut = text.find(delim, length)
if cut > -1:
return text[:cut]
else:
return text | python | def cut_to_length(text, length, delim):
"""Shorten given text on first delimiter after given number
of characters.
"""
cut = text.find(delim, length)
if cut > -1:
return text[:cut]
else:
return text | [
"def",
"cut_to_length",
"(",
"text",
",",
"length",
",",
"delim",
")",
":",
"cut",
"=",
"text",
".",
"find",
"(",
"delim",
",",
"length",
")",
"if",
"cut",
">",
"-",
"1",
":",
"return",
"text",
"[",
":",
"cut",
"]",
"else",
":",
"return",
"text"
... | Shorten given text on first delimiter after given number
of characters. | [
"Shorten",
"given",
"text",
"on",
"first",
"delimiter",
"after",
"given",
"number",
"of",
"characters",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L32-L40 | train | 35,452 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | get_interpreter_path | def get_interpreter_path(version=None):
"""Return the executable of a specified or current version."""
if version and version != str(sys.version_info[0]):
return settings.PYTHON_INTERPRETER + version
else:
return sys.executable | python | def get_interpreter_path(version=None):
"""Return the executable of a specified or current version."""
if version and version != str(sys.version_info[0]):
return settings.PYTHON_INTERPRETER + version
else:
return sys.executable | [
"def",
"get_interpreter_path",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"and",
"version",
"!=",
"str",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
":",
"return",
"settings",
".",
"PYTHON_INTERPRETER",
"+",
"version",
"else",
":",
... | Return the executable of a specified or current version. | [
"Return",
"the",
"executable",
"of",
"a",
"specified",
"or",
"current",
"version",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L43-L48 | train | 35,453 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | pypi_metadata_extension | def pypi_metadata_extension(extraction_fce):
"""Extracts data from PyPI and merges them with data from extraction
method.
"""
def inner(self, client=None):
data = extraction_fce(self)
if client is None:
logger.warning("Client is None, it was probably disabled")
data.update_attr('source0', self.archive.name)
return data
try:
release_data = client.release_data(self.name, self.version)
except BaseException:
logger.warning("Some kind of error while communicating with "
"client: {0}.".format(client), exc_info=True)
return data
try:
url, md5_digest = get_url(client, self.name, self.version)
except exc.MissingUrlException:
url, md5_digest = ('FAILED TO EXTRACT FROM PYPI',
'FAILED TO EXTRACT FROM PYPI')
data_dict = {'source0': url, 'md5': md5_digest}
for data_field in settings.PYPI_USABLE_DATA:
data_dict[data_field] = release_data.get(data_field, '')
# we usually get better license representation from trove classifiers
data_dict["license"] = license_from_trove(release_data.get(
'classifiers', ''))
data.set_from(data_dict, update=True)
return data
return inner | python | def pypi_metadata_extension(extraction_fce):
"""Extracts data from PyPI and merges them with data from extraction
method.
"""
def inner(self, client=None):
data = extraction_fce(self)
if client is None:
logger.warning("Client is None, it was probably disabled")
data.update_attr('source0', self.archive.name)
return data
try:
release_data = client.release_data(self.name, self.version)
except BaseException:
logger.warning("Some kind of error while communicating with "
"client: {0}.".format(client), exc_info=True)
return data
try:
url, md5_digest = get_url(client, self.name, self.version)
except exc.MissingUrlException:
url, md5_digest = ('FAILED TO EXTRACT FROM PYPI',
'FAILED TO EXTRACT FROM PYPI')
data_dict = {'source0': url, 'md5': md5_digest}
for data_field in settings.PYPI_USABLE_DATA:
data_dict[data_field] = release_data.get(data_field, '')
# we usually get better license representation from trove classifiers
data_dict["license"] = license_from_trove(release_data.get(
'classifiers', ''))
data.set_from(data_dict, update=True)
return data
return inner | [
"def",
"pypi_metadata_extension",
"(",
"extraction_fce",
")",
":",
"def",
"inner",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"data",
"=",
"extraction_fce",
"(",
"self",
")",
"if",
"client",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Cl... | Extracts data from PyPI and merges them with data from extraction
method. | [
"Extracts",
"data",
"from",
"PyPI",
"and",
"merges",
"them",
"with",
"data",
"from",
"extraction",
"method",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L88-L120 | train | 35,454 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | venv_metadata_extension | def venv_metadata_extension(extraction_fce):
"""Extracts specific metadata from virtualenv object, merges them with data
from given extraction method.
"""
def inner(self):
data = extraction_fce(self)
if virtualenv is None or not self.venv:
logger.debug("Skipping virtualenv metadata extraction.")
return data
temp_dir = tempfile.mkdtemp()
try:
extractor = virtualenv.VirtualEnv(self.name, temp_dir,
self.name_convertor,
self.base_python_version)
data.set_from(extractor.get_venv_data, update=True)
except exc.VirtualenvFailException as e:
logger.error("{}, skipping virtualenv metadata extraction.".format(
e))
finally:
shutil.rmtree(temp_dir)
return data
return inner | python | def venv_metadata_extension(extraction_fce):
"""Extracts specific metadata from virtualenv object, merges them with data
from given extraction method.
"""
def inner(self):
data = extraction_fce(self)
if virtualenv is None or not self.venv:
logger.debug("Skipping virtualenv metadata extraction.")
return data
temp_dir = tempfile.mkdtemp()
try:
extractor = virtualenv.VirtualEnv(self.name, temp_dir,
self.name_convertor,
self.base_python_version)
data.set_from(extractor.get_venv_data, update=True)
except exc.VirtualenvFailException as e:
logger.error("{}, skipping virtualenv metadata extraction.".format(
e))
finally:
shutil.rmtree(temp_dir)
return data
return inner | [
"def",
"venv_metadata_extension",
"(",
"extraction_fce",
")",
":",
"def",
"inner",
"(",
"self",
")",
":",
"data",
"=",
"extraction_fce",
"(",
"self",
")",
"if",
"virtualenv",
"is",
"None",
"or",
"not",
"self",
".",
"venv",
":",
"logger",
".",
"debug",
"(... | Extracts specific metadata from virtualenv object, merges them with data
from given extraction method. | [
"Extracts",
"specific",
"metadata",
"from",
"virtualenv",
"object",
"merges",
"them",
"with",
"data",
"from",
"given",
"extraction",
"method",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L123-L146 | train | 35,455 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | process_description | def process_description(description_fce):
"""Removes special character delimiters, titles
and wraps paragraphs.
"""
def inner(description):
clear_description = \
re.sub(r'\s+', ' ', # multiple whitespaces
# general URLs
re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '',
# delimiters
re.sub('(#|=|---|~|`)*', '',
# very short lines, typically titles
re.sub('((\r?\n)|^).{0,8}((\r?\n)|$)', '',
# PyPI's version and downloads tags
re.sub(
'((\r*.. image::|:target:) https?|(:align:|:alt:))[^\n]*\n', '',
description_fce(description))))))
return ' '.join(textwrap.wrap(clear_description, 80))
return inner | python | def process_description(description_fce):
"""Removes special character delimiters, titles
and wraps paragraphs.
"""
def inner(description):
clear_description = \
re.sub(r'\s+', ' ', # multiple whitespaces
# general URLs
re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '',
# delimiters
re.sub('(#|=|---|~|`)*', '',
# very short lines, typically titles
re.sub('((\r?\n)|^).{0,8}((\r?\n)|$)', '',
# PyPI's version and downloads tags
re.sub(
'((\r*.. image::|:target:) https?|(:align:|:alt:))[^\n]*\n', '',
description_fce(description))))))
return ' '.join(textwrap.wrap(clear_description, 80))
return inner | [
"def",
"process_description",
"(",
"description_fce",
")",
":",
"def",
"inner",
"(",
"description",
")",
":",
"clear_description",
"=",
"re",
".",
"sub",
"(",
"r'\\s+'",
",",
"' '",
",",
"# multiple whitespaces",
"# general URLs",
"re",
".",
"sub",
"(",
"r'\\w... | Removes special character delimiters, titles
and wraps paragraphs. | [
"Removes",
"special",
"character",
"delimiters",
"titles",
"and",
"wraps",
"paragraphs",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L149-L167 | train | 35,456 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | LocalMetadataExtractor.versions_from_archive | def versions_from_archive(self):
"""Return Python versions extracted from trove classifiers. """
py_vers = versions_from_trove(self.classifiers)
return [ver for ver in py_vers if ver != self.unsupported_version] | python | def versions_from_archive(self):
"""Return Python versions extracted from trove classifiers. """
py_vers = versions_from_trove(self.classifiers)
return [ver for ver in py_vers if ver != self.unsupported_version] | [
"def",
"versions_from_archive",
"(",
"self",
")",
":",
"py_vers",
"=",
"versions_from_trove",
"(",
"self",
".",
"classifiers",
")",
"return",
"[",
"ver",
"for",
"ver",
"in",
"py_vers",
"if",
"ver",
"!=",
"self",
".",
"unsupported_version",
"]"
] | Return Python versions extracted from trove classifiers. | [
"Return",
"Python",
"versions",
"extracted",
"from",
"trove",
"classifiers",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L205-L208 | train | 35,457 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | LocalMetadataExtractor.srcname | def srcname(self):
"""Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name>
"""
if self.rpm_name or self.name.startswith(('python-', 'Python-')):
return self.name_convertor.base_name(self.rpm_name or self.name) | python | def srcname(self):
"""Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name>
"""
if self.rpm_name or self.name.startswith(('python-', 'Python-')):
return self.name_convertor.base_name(self.rpm_name or self.name) | [
"def",
"srcname",
"(",
"self",
")",
":",
"if",
"self",
".",
"rpm_name",
"or",
"self",
".",
"name",
".",
"startswith",
"(",
"(",
"'python-'",
",",
"'Python-'",
")",
")",
":",
"return",
"self",
".",
"name_convertor",
".",
"base_name",
"(",
"self",
".",
... | Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name> | [
"Return",
"srcname",
"for",
"the",
"macro",
"if",
"the",
"pypi",
"name",
"should",
"be",
"changed",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L235-L243 | train | 35,458 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | SetupPyMetadataExtractor.runtime_deps | def runtime_deps(self): # install_requires
"""Returns list of runtime dependencies of the package specified in
setup.py.
Dependencies are in RPM SPECFILE format - see dependency_to_rpm()
for details, but names are already transformed according to
current distro.
Returns:
list of runtime dependencies of the package
"""
install_requires = self.metadata['install_requires']
if self.metadata[
'entry_points'] and 'setuptools' not in install_requires:
install_requires.append('setuptools') # entrypoints
return sorted(self.name_convert_deps_list(deps_from_pyp_format(
install_requires, runtime=True))) | python | def runtime_deps(self): # install_requires
"""Returns list of runtime dependencies of the package specified in
setup.py.
Dependencies are in RPM SPECFILE format - see dependency_to_rpm()
for details, but names are already transformed according to
current distro.
Returns:
list of runtime dependencies of the package
"""
install_requires = self.metadata['install_requires']
if self.metadata[
'entry_points'] and 'setuptools' not in install_requires:
install_requires.append('setuptools') # entrypoints
return sorted(self.name_convert_deps_list(deps_from_pyp_format(
install_requires, runtime=True))) | [
"def",
"runtime_deps",
"(",
"self",
")",
":",
"# install_requires",
"install_requires",
"=",
"self",
".",
"metadata",
"[",
"'install_requires'",
"]",
"if",
"self",
".",
"metadata",
"[",
"'entry_points'",
"]",
"and",
"'setuptools'",
"not",
"in",
"install_requires",... | Returns list of runtime dependencies of the package specified in
setup.py.
Dependencies are in RPM SPECFILE format - see dependency_to_rpm()
for details, but names are already transformed according to
current distro.
Returns:
list of runtime dependencies of the package | [
"Returns",
"list",
"of",
"runtime",
"dependencies",
"of",
"the",
"package",
"specified",
"in",
"setup",
".",
"py",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L370-L387 | train | 35,459 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | SetupPyMetadataExtractor.build_deps | def build_deps(self): # setup_requires [tests_require, install_requires]
"""Same as runtime_deps, but build dependencies. Test and install
requires are included if package contains test suite to prevent
%check phase crashes because of missing dependencies
Returns:
list of build dependencies of the package
"""
build_requires = self.metadata['setup_requires']
if self.has_test_suite:
build_requires += self.metadata['tests_require'] + self.metadata[
'install_requires']
if 'setuptools' not in build_requires:
build_requires.append('setuptools')
return sorted(self.name_convert_deps_list(deps_from_pyp_format(
build_requires, runtime=False))) | python | def build_deps(self): # setup_requires [tests_require, install_requires]
"""Same as runtime_deps, but build dependencies. Test and install
requires are included if package contains test suite to prevent
%check phase crashes because of missing dependencies
Returns:
list of build dependencies of the package
"""
build_requires = self.metadata['setup_requires']
if self.has_test_suite:
build_requires += self.metadata['tests_require'] + self.metadata[
'install_requires']
if 'setuptools' not in build_requires:
build_requires.append('setuptools')
return sorted(self.name_convert_deps_list(deps_from_pyp_format(
build_requires, runtime=False))) | [
"def",
"build_deps",
"(",
"self",
")",
":",
"# setup_requires [tests_require, install_requires]",
"build_requires",
"=",
"self",
".",
"metadata",
"[",
"'setup_requires'",
"]",
"if",
"self",
".",
"has_test_suite",
":",
"build_requires",
"+=",
"self",
".",
"metadata",
... | Same as runtime_deps, but build dependencies. Test and install
requires are included if package contains test suite to prevent
%check phase crashes because of missing dependencies
Returns:
list of build dependencies of the package | [
"Same",
"as",
"runtime_deps",
"but",
"build",
"dependencies",
".",
"Test",
"and",
"install",
"requires",
"are",
"included",
"if",
"package",
"contains",
"test",
"suite",
"to",
"prevent",
"%check",
"phase",
"crashes",
"because",
"of",
"missing",
"dependencies"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L390-L407 | train | 35,460 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | SetupPyMetadataExtractor.data_from_archive | def data_from_archive(self):
"""Appends setup.py specific metadata to archive_data."""
archive_data = super(SetupPyMetadataExtractor, self).data_from_archive
archive_data['has_packages'] = self.has_packages
archive_data['packages'] = self.packages
archive_data['has_bundled_egg_info'] = self.has_bundled_egg_info
sphinx_dir = self.sphinx_dir
if sphinx_dir:
archive_data['sphinx_dir'] = "/".join(sphinx_dir.split("/")[1:])
archive_data['build_deps'].append(
['BuildRequires', self.name_convertor.rpm_name(
"sphinx", self.base_python_version)])
return archive_data | python | def data_from_archive(self):
"""Appends setup.py specific metadata to archive_data."""
archive_data = super(SetupPyMetadataExtractor, self).data_from_archive
archive_data['has_packages'] = self.has_packages
archive_data['packages'] = self.packages
archive_data['has_bundled_egg_info'] = self.has_bundled_egg_info
sphinx_dir = self.sphinx_dir
if sphinx_dir:
archive_data['sphinx_dir'] = "/".join(sphinx_dir.split("/")[1:])
archive_data['build_deps'].append(
['BuildRequires', self.name_convertor.rpm_name(
"sphinx", self.base_python_version)])
return archive_data | [
"def",
"data_from_archive",
"(",
"self",
")",
":",
"archive_data",
"=",
"super",
"(",
"SetupPyMetadataExtractor",
",",
"self",
")",
".",
"data_from_archive",
"archive_data",
"[",
"'has_packages'",
"]",
"=",
"self",
".",
"has_packages",
"archive_data",
"[",
"'packa... | Appends setup.py specific metadata to archive_data. | [
"Appends",
"setup",
".",
"py",
"specific",
"metadata",
"to",
"archive_data",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L518-L533 | train | 35,461 |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | WheelMetadataExtractor.get_requires | def get_requires(self, requires_types):
"""Extracts requires of given types from metadata file, filter windows
specific requires.
"""
if not isinstance(requires_types, list):
requires_types = list(requires_types)
extracted_requires = []
for requires_name in requires_types:
for requires in self.json_metadata.get(requires_name, []):
if 'win' in requires.get('environment', {}):
continue
extracted_requires.extend(requires['requires'])
return extracted_requires | python | def get_requires(self, requires_types):
"""Extracts requires of given types from metadata file, filter windows
specific requires.
"""
if not isinstance(requires_types, list):
requires_types = list(requires_types)
extracted_requires = []
for requires_name in requires_types:
for requires in self.json_metadata.get(requires_name, []):
if 'win' in requires.get('environment', {}):
continue
extracted_requires.extend(requires['requires'])
return extracted_requires | [
"def",
"get_requires",
"(",
"self",
",",
"requires_types",
")",
":",
"if",
"not",
"isinstance",
"(",
"requires_types",
",",
"list",
")",
":",
"requires_types",
"=",
"list",
"(",
"requires_types",
")",
"extracted_requires",
"=",
"[",
"]",
"for",
"requires_name"... | Extracts requires of given types from metadata file, filter windows
specific requires. | [
"Extracts",
"requires",
"of",
"given",
"types",
"from",
"metadata",
"file",
"filter",
"windows",
"specific",
"requires",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L545-L557 | train | 35,462 |
fedora-python/pyp2rpm | pyp2rpm/package_getters.py | get_url | def get_url(client, name, version, wheel=False, hashed_format=False):
"""Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest.
"""
try:
release_urls = client.release_urls(name, version)
release_data = client.release_data(name, version)
except BaseException: # some kind of error with client
logger.debug('Client: {0} Name: {1} Version: {2}.'.format(
client, name, version))
raise exceptions.MissingUrlException(
"Some kind of error while communicating with client: {0}.".format(
client), exc_info=True)
url = ''
md5_digest = None
if not wheel:
# Prefered archive is tar.gz
if len(release_urls):
zip_url = zip_md5 = ''
for release_url in release_urls:
if release_url['url'].endswith("tar.gz"):
url = release_url['url']
md5_digest = release_url['md5_digest']
if release_url['url'].endswith(".zip"):
zip_url = release_url['url']
zip_md5 = release_url['md5_digest']
if url == '':
url = zip_url or release_urls[0]['url']
md5_digest = zip_md5 or release_urls[0]['md5_digest']
elif release_data:
url = release_data['download_url']
else:
# Only wheel is acceptable
for release_url in release_urls:
if release_url['url'].endswith("none-any.whl"):
url = release_url['url']
md5_digest = release_url['md5_digest']
break
if not url:
raise exceptions.MissingUrlException(
"Url of source archive not found.")
if url == 'UNKNOWN':
raise exceptions.MissingUrlException(
"{0} package has no sources on PyPI, Please ask the maintainer "
"to upload sources.".format(release_data['name']))
if not hashed_format:
url = ("https://files.pythonhosted.org/packages/source"
"/{0[0]}/{0}/{1}").format(name, url.split("/")[-1])
return (url, md5_digest) | python | def get_url(client, name, version, wheel=False, hashed_format=False):
"""Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest.
"""
try:
release_urls = client.release_urls(name, version)
release_data = client.release_data(name, version)
except BaseException: # some kind of error with client
logger.debug('Client: {0} Name: {1} Version: {2}.'.format(
client, name, version))
raise exceptions.MissingUrlException(
"Some kind of error while communicating with client: {0}.".format(
client), exc_info=True)
url = ''
md5_digest = None
if not wheel:
# Prefered archive is tar.gz
if len(release_urls):
zip_url = zip_md5 = ''
for release_url in release_urls:
if release_url['url'].endswith("tar.gz"):
url = release_url['url']
md5_digest = release_url['md5_digest']
if release_url['url'].endswith(".zip"):
zip_url = release_url['url']
zip_md5 = release_url['md5_digest']
if url == '':
url = zip_url or release_urls[0]['url']
md5_digest = zip_md5 or release_urls[0]['md5_digest']
elif release_data:
url = release_data['download_url']
else:
# Only wheel is acceptable
for release_url in release_urls:
if release_url['url'].endswith("none-any.whl"):
url = release_url['url']
md5_digest = release_url['md5_digest']
break
if not url:
raise exceptions.MissingUrlException(
"Url of source archive not found.")
if url == 'UNKNOWN':
raise exceptions.MissingUrlException(
"{0} package has no sources on PyPI, Please ask the maintainer "
"to upload sources.".format(release_data['name']))
if not hashed_format:
url = ("https://files.pythonhosted.org/packages/source"
"/{0[0]}/{0}/{1}").format(name, url.split("/")[-1])
return (url, md5_digest) | [
"def",
"get_url",
"(",
"client",
",",
"name",
",",
"version",
",",
"wheel",
"=",
"False",
",",
"hashed_format",
"=",
"False",
")",
":",
"try",
":",
"release_urls",
"=",
"client",
".",
"release_urls",
"(",
"name",
",",
"version",
")",
"release_data",
"=",... | Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest. | [
"Retrieves",
"list",
"of",
"package",
"URLs",
"using",
"PyPI",
"s",
"XML",
"-",
"RPC",
".",
"Chooses",
"URL",
"of",
"prefered",
"archive",
"and",
"md5_digest",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/package_getters.py#L25-L78 | train | 35,463 |
fedora-python/pyp2rpm | pyp2rpm/virtualenv.py | DirsContent.fill | def fill(self, path):
'''
Scans content of directories
'''
self.bindir = set(os.listdir(path + 'bin/'))
self.lib_sitepackages = set(os.listdir(glob.glob(
path + 'lib/python?.?/site-packages/')[0])) | python | def fill(self, path):
'''
Scans content of directories
'''
self.bindir = set(os.listdir(path + 'bin/'))
self.lib_sitepackages = set(os.listdir(glob.glob(
path + 'lib/python?.?/site-packages/')[0])) | [
"def",
"fill",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"bindir",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"path",
"+",
"'bin/'",
")",
")",
"self",
".",
"lib_sitepackages",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"glob",
".",
"glob... | Scans content of directories | [
"Scans",
"content",
"of",
"directories"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/virtualenv.py#L39-L45 | train | 35,464 |
fedora-python/pyp2rpm | pyp2rpm/virtualenv.py | VirtualEnv.install_package_to_venv | def install_package_to_venv(self):
'''
Installs package given as first argument to virtualenv without
dependencies
'''
try:
self.env.install(self.name, force=True, options=["--no-deps"])
except (ve.PackageInstallationException,
ve.VirtualenvReadonlyException):
raise VirtualenvFailException(
'Failed to install package to virtualenv')
self.dirs_after_install.fill(self.temp_dir + '/venv/') | python | def install_package_to_venv(self):
'''
Installs package given as first argument to virtualenv without
dependencies
'''
try:
self.env.install(self.name, force=True, options=["--no-deps"])
except (ve.PackageInstallationException,
ve.VirtualenvReadonlyException):
raise VirtualenvFailException(
'Failed to install package to virtualenv')
self.dirs_after_install.fill(self.temp_dir + '/venv/') | [
"def",
"install_package_to_venv",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"env",
".",
"install",
"(",
"self",
".",
"name",
",",
"force",
"=",
"True",
",",
"options",
"=",
"[",
"\"--no-deps\"",
"]",
")",
"except",
"(",
"ve",
".",
"PackageInstall... | Installs package given as first argument to virtualenv without
dependencies | [
"Installs",
"package",
"given",
"as",
"first",
"argument",
"to",
"virtualenv",
"without",
"dependencies"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/virtualenv.py#L81-L92 | train | 35,465 |
fedora-python/pyp2rpm | pyp2rpm/virtualenv.py | VirtualEnv.get_dirs_differance | def get_dirs_differance(self):
'''
Makes final versions of site_packages and scripts using DirsContent
sub method and filters
'''
try:
diff = self.dirs_after_install - self.dirs_before_install
except ValueError:
raise VirtualenvFailException(
"Some of the DirsContent attributes is uninicialized")
self.data['has_pth'] = \
any([x for x in diff.lib_sitepackages if x.endswith('.pth')])
site_packages = site_packages_filter(diff.lib_sitepackages)
self.data['packages'] = sorted(
[p for p in site_packages if not p.endswith(MODULE_SUFFIXES)])
self.data['py_modules'] = sorted(set(
[os.path.splitext(m)[0] for m in site_packages - set(
self.data['packages'])]))
self.data['scripts'] = scripts_filter(sorted(diff.bindir))
logger.debug('Data from files differance in virtualenv:')
logger.debug(pprint.pformat(self.data)) | python | def get_dirs_differance(self):
'''
Makes final versions of site_packages and scripts using DirsContent
sub method and filters
'''
try:
diff = self.dirs_after_install - self.dirs_before_install
except ValueError:
raise VirtualenvFailException(
"Some of the DirsContent attributes is uninicialized")
self.data['has_pth'] = \
any([x for x in diff.lib_sitepackages if x.endswith('.pth')])
site_packages = site_packages_filter(diff.lib_sitepackages)
self.data['packages'] = sorted(
[p for p in site_packages if not p.endswith(MODULE_SUFFIXES)])
self.data['py_modules'] = sorted(set(
[os.path.splitext(m)[0] for m in site_packages - set(
self.data['packages'])]))
self.data['scripts'] = scripts_filter(sorted(diff.bindir))
logger.debug('Data from files differance in virtualenv:')
logger.debug(pprint.pformat(self.data)) | [
"def",
"get_dirs_differance",
"(",
"self",
")",
":",
"try",
":",
"diff",
"=",
"self",
".",
"dirs_after_install",
"-",
"self",
".",
"dirs_before_install",
"except",
"ValueError",
":",
"raise",
"VirtualenvFailException",
"(",
"\"Some of the DirsContent attributes is unini... | Makes final versions of site_packages and scripts using DirsContent
sub method and filters | [
"Makes",
"final",
"versions",
"of",
"site_packages",
"and",
"scripts",
"using",
"DirsContent",
"sub",
"method",
"and",
"filters"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/virtualenv.py#L94-L115 | train | 35,466 |
fedora-python/pyp2rpm | pyp2rpm/bin.py | main | def main(package, v, d, s, r, proxy, srpm, p, b, o, t, venv, autonc, sclize,
**scl_kwargs):
"""Convert PyPI package to RPM specfile or SRPM.
\b
\b\bArguments:
PACKAGE Provide PyPI name of the package or path to compressed
source file.
"""
register_file_log_handler('/tmp/pyp2rpm-{0}.log'.format(getpass.getuser()))
if srpm or s:
register_console_log_handler()
distro = o
if t and os.path.splitext(t)[0] in settings.KNOWN_DISTROS:
distro = t
elif t and not (b or p):
raise click.UsageError("Default python versions for template {0} are "
"missing in settings, add them or use flags "
"-b/-p to set python versions.".format(t))
logger = logging.getLogger(__name__)
logger.info('Pyp2rpm initialized.')
convertor = Convertor(package=package,
version=v,
save_dir=d,
template=t or settings.DEFAULT_TEMPLATE,
distro=distro,
base_python_version=b,
python_versions=p,
rpm_name=r,
proxy=proxy,
venv=venv,
autonc=autonc)
logger.debug(
'Convertor: {0} created. Trying to convert.'.format(convertor))
converted = convertor.convert()
logger.debug('Convertor: {0} succesfully converted.'.format(convertor))
if sclize:
converted = convert_to_scl(converted, scl_kwargs)
if srpm or s:
if r:
spec_name = r + '.spec'
else:
prefix = 'python-' if not convertor.name.startswith(
'python-') else ''
spec_name = prefix + convertor.name + '.spec'
logger.info('Using name: {0} for specfile.'.format(spec_name))
if d == settings.DEFAULT_PKG_SAVE_PATH:
# default save_path is rpmbuild tree so we want to save spec
# in rpmbuild/SPECS/
spec_path = d + '/SPECS/' + spec_name
else:
# if user provide save_path then save spec in provided path
spec_path = d + '/' + spec_name
spec_dir = os.path.dirname(spec_path)
if not os.path.exists(spec_dir):
os.makedirs(spec_dir)
logger.debug('Opening specfile: {0}.'.format(spec_path))
if not utils.PY3:
converted = converted.encode('utf-8')
with open(spec_path, 'w') as f:
f.write(converted)
logger.info('Specfile saved at: {0}.'.format(spec_path))
if srpm:
msg = utils.build_srpm(spec_path, d)
logger.info(msg)
else:
logger.debug('Printing specfile to stdout.')
if utils.PY3:
print(converted)
else:
print(converted.encode('utf-8'))
logger.debug('Specfile printed.')
logger.info("That's all folks!") | python | def main(package, v, d, s, r, proxy, srpm, p, b, o, t, venv, autonc, sclize,
**scl_kwargs):
"""Convert PyPI package to RPM specfile or SRPM.
\b
\b\bArguments:
PACKAGE Provide PyPI name of the package or path to compressed
source file.
"""
register_file_log_handler('/tmp/pyp2rpm-{0}.log'.format(getpass.getuser()))
if srpm or s:
register_console_log_handler()
distro = o
if t and os.path.splitext(t)[0] in settings.KNOWN_DISTROS:
distro = t
elif t and not (b or p):
raise click.UsageError("Default python versions for template {0} are "
"missing in settings, add them or use flags "
"-b/-p to set python versions.".format(t))
logger = logging.getLogger(__name__)
logger.info('Pyp2rpm initialized.')
convertor = Convertor(package=package,
version=v,
save_dir=d,
template=t or settings.DEFAULT_TEMPLATE,
distro=distro,
base_python_version=b,
python_versions=p,
rpm_name=r,
proxy=proxy,
venv=venv,
autonc=autonc)
logger.debug(
'Convertor: {0} created. Trying to convert.'.format(convertor))
converted = convertor.convert()
logger.debug('Convertor: {0} succesfully converted.'.format(convertor))
if sclize:
converted = convert_to_scl(converted, scl_kwargs)
if srpm or s:
if r:
spec_name = r + '.spec'
else:
prefix = 'python-' if not convertor.name.startswith(
'python-') else ''
spec_name = prefix + convertor.name + '.spec'
logger.info('Using name: {0} for specfile.'.format(spec_name))
if d == settings.DEFAULT_PKG_SAVE_PATH:
# default save_path is rpmbuild tree so we want to save spec
# in rpmbuild/SPECS/
spec_path = d + '/SPECS/' + spec_name
else:
# if user provide save_path then save spec in provided path
spec_path = d + '/' + spec_name
spec_dir = os.path.dirname(spec_path)
if not os.path.exists(spec_dir):
os.makedirs(spec_dir)
logger.debug('Opening specfile: {0}.'.format(spec_path))
if not utils.PY3:
converted = converted.encode('utf-8')
with open(spec_path, 'w') as f:
f.write(converted)
logger.info('Specfile saved at: {0}.'.format(spec_path))
if srpm:
msg = utils.build_srpm(spec_path, d)
logger.info(msg)
else:
logger.debug('Printing specfile to stdout.')
if utils.PY3:
print(converted)
else:
print(converted.encode('utf-8'))
logger.debug('Specfile printed.')
logger.info("That's all folks!") | [
"def",
"main",
"(",
"package",
",",
"v",
",",
"d",
",",
"s",
",",
"r",
",",
"proxy",
",",
"srpm",
",",
"p",
",",
"b",
",",
"o",
",",
"t",
",",
"venv",
",",
"autonc",
",",
"sclize",
",",
"*",
"*",
"scl_kwargs",
")",
":",
"register_file_log_handl... | Convert PyPI package to RPM specfile or SRPM.
\b
\b\bArguments:
PACKAGE Provide PyPI name of the package or path to compressed
source file. | [
"Convert",
"PyPI",
"package",
"to",
"RPM",
"specfile",
"or",
"SRPM",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/bin.py#L170-L253 | train | 35,467 |
fedora-python/pyp2rpm | pyp2rpm/bin.py | convert_to_scl | def convert_to_scl(spec, scl_options):
"""Convert spec into SCL-style spec file using `spec2scl`.
Args:
spec: (str) a spec file
scl_options: (dict) SCL options provided
Returns:
A converted spec file
"""
scl_options['skip_functions'] = scl_options['skip_functions'].split(',')
scl_options['meta_spec'] = None
convertor = SclConvertor(options=scl_options)
return str(convertor.convert(spec)) | python | def convert_to_scl(spec, scl_options):
"""Convert spec into SCL-style spec file using `spec2scl`.
Args:
spec: (str) a spec file
scl_options: (dict) SCL options provided
Returns:
A converted spec file
"""
scl_options['skip_functions'] = scl_options['skip_functions'].split(',')
scl_options['meta_spec'] = None
convertor = SclConvertor(options=scl_options)
return str(convertor.convert(spec)) | [
"def",
"convert_to_scl",
"(",
"spec",
",",
"scl_options",
")",
":",
"scl_options",
"[",
"'skip_functions'",
"]",
"=",
"scl_options",
"[",
"'skip_functions'",
"]",
".",
"split",
"(",
"','",
")",
"scl_options",
"[",
"'meta_spec'",
"]",
"=",
"None",
"convertor",
... | Convert spec into SCL-style spec file using `spec2scl`.
Args:
spec: (str) a spec file
scl_options: (dict) SCL options provided
Returns:
A converted spec file | [
"Convert",
"spec",
"into",
"SCL",
"-",
"style",
"spec",
"file",
"using",
"spec2scl",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/bin.py#L256-L268 | train | 35,468 |
fedora-python/pyp2rpm | pyp2rpm/bin.py | Pyp2rpmCommand.format_options | def format_options(self, ctx, formatter):
"""Writes SCL related options into the formatter as a separate
group.
"""
super(Pyp2rpmCommand, self).format_options(ctx, formatter)
scl_opts = []
for param in self.get_params(ctx):
if isinstance(param, SclizeOption):
scl_opts.append(param.get_scl_help_record(ctx))
if scl_opts:
with formatter.section('SCL related options'):
formatter.write_dl(scl_opts) | python | def format_options(self, ctx, formatter):
"""Writes SCL related options into the formatter as a separate
group.
"""
super(Pyp2rpmCommand, self).format_options(ctx, formatter)
scl_opts = []
for param in self.get_params(ctx):
if isinstance(param, SclizeOption):
scl_opts.append(param.get_scl_help_record(ctx))
if scl_opts:
with formatter.section('SCL related options'):
formatter.write_dl(scl_opts) | [
"def",
"format_options",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"super",
"(",
"Pyp2rpmCommand",
",",
"self",
")",
".",
"format_options",
"(",
"ctx",
",",
"formatter",
")",
"scl_opts",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"get... | Writes SCL related options into the formatter as a separate
group. | [
"Writes",
"SCL",
"related",
"options",
"into",
"the",
"formatter",
"as",
"a",
"separate",
"group",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/bin.py#L32-L44 | train | 35,469 |
fedora-python/pyp2rpm | pyp2rpm/bin.py | SclizeOption.handle_parse_result | def handle_parse_result(self, ctx, opts, args):
"""Validate SCL related options before parsing."""
if 'sclize' in opts and not SclConvertor:
raise click.UsageError("Please install spec2scl package to "
"perform SCL-style conversion")
if self.name in opts and 'sclize' not in opts:
raise click.UsageError(
"`--{}` can only be used with --sclize option".format(
self.name))
return super(SclizeOption, self).handle_parse_result(ctx, opts, args) | python | def handle_parse_result(self, ctx, opts, args):
"""Validate SCL related options before parsing."""
if 'sclize' in opts and not SclConvertor:
raise click.UsageError("Please install spec2scl package to "
"perform SCL-style conversion")
if self.name in opts and 'sclize' not in opts:
raise click.UsageError(
"`--{}` can only be used with --sclize option".format(
self.name))
return super(SclizeOption, self).handle_parse_result(ctx, opts, args) | [
"def",
"handle_parse_result",
"(",
"self",
",",
"ctx",
",",
"opts",
",",
"args",
")",
":",
"if",
"'sclize'",
"in",
"opts",
"and",
"not",
"SclConvertor",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"Please install spec2scl package to \"",
"\"perform SCL-style ... | Validate SCL related options before parsing. | [
"Validate",
"SCL",
"related",
"options",
"before",
"parsing",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/bin.py#L53-L63 | train | 35,470 |
fedora-python/pyp2rpm | pyp2rpm/command/extract_dist.py | to_list | def to_list(var):
"""Checks if given value is a list, tries to convert, if it is not."""
if var is None:
return []
if isinstance(var, str):
var = var.split('\n')
elif not isinstance(var, list):
try:
var = list(var)
except TypeError:
raise ValueError("{} cannot be converted to the list.".format(var))
return var | python | def to_list(var):
"""Checks if given value is a list, tries to convert, if it is not."""
if var is None:
return []
if isinstance(var, str):
var = var.split('\n')
elif not isinstance(var, list):
try:
var = list(var)
except TypeError:
raise ValueError("{} cannot be converted to the list.".format(var))
return var | [
"def",
"to_list",
"(",
"var",
")",
":",
"if",
"var",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"var",
",",
"str",
")",
":",
"var",
"=",
"var",
".",
"split",
"(",
"'\\n'",
")",
"elif",
"not",
"isinstance",
"(",
"var",
",",
... | Checks if given value is a list, tries to convert, if it is not. | [
"Checks",
"if",
"given",
"value",
"is",
"a",
"list",
"tries",
"to",
"convert",
"if",
"it",
"is",
"not",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/command/extract_dist.py#L75-L86 | train | 35,471 |
fedora-python/pyp2rpm | pyp2rpm/command/extract_dist.py | extract_dist.run | def run(self):
"""Sends extracted metadata in json format to stdout if stdout
option is specified, assigns metadata dictionary to class_metadata
variable otherwise.
"""
if self.stdout:
sys.stdout.write("extracted json data:\n" + json.dumps(
self.metadata, default=to_str) + "\n")
else:
extract_dist.class_metadata = self.metadata | python | def run(self):
"""Sends extracted metadata in json format to stdout if stdout
option is specified, assigns metadata dictionary to class_metadata
variable otherwise.
"""
if self.stdout:
sys.stdout.write("extracted json data:\n" + json.dumps(
self.metadata, default=to_str) + "\n")
else:
extract_dist.class_metadata = self.metadata | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"stdout",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"extracted json data:\\n\"",
"+",
"json",
".",
"dumps",
"(",
"self",
".",
"metadata",
",",
"default",
"=",
"to_str",
")",
"+",
"\"\\n\"",
... | Sends extracted metadata in json format to stdout if stdout
option is specified, assigns metadata dictionary to class_metadata
variable otherwise. | [
"Sends",
"extracted",
"metadata",
"in",
"json",
"format",
"to",
"stdout",
"if",
"stdout",
"option",
"is",
"specified",
"assigns",
"metadata",
"dictionary",
"to",
"class_metadata",
"variable",
"otherwise",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/command/extract_dist.py#L63-L72 | train | 35,472 |
fedora-python/pyp2rpm | pyp2rpm/package_data.py | PackageData.get_changelog_date_packager | def get_changelog_date_packager(self):
"""Returns part of the changelog entry, containing date and packager.
"""
try:
packager = subprocess.Popen(
'rpmdev-packager', stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
# Hi John Doe, you should install rpmdevtools
packager = "John Doe <john@doe.com>"
logger.warn("Package rpmdevtools is missing, using default "
"name: {0}.".format(packager))
with utils.c_time_locale():
date_str = time.strftime('%a %b %d %Y', time.gmtime())
encoding = locale.getpreferredencoding()
return u'{0} {1}'.format(date_str, packager.decode(encoding)) | python | def get_changelog_date_packager(self):
"""Returns part of the changelog entry, containing date and packager.
"""
try:
packager = subprocess.Popen(
'rpmdev-packager', stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
# Hi John Doe, you should install rpmdevtools
packager = "John Doe <john@doe.com>"
logger.warn("Package rpmdevtools is missing, using default "
"name: {0}.".format(packager))
with utils.c_time_locale():
date_str = time.strftime('%a %b %d %Y', time.gmtime())
encoding = locale.getpreferredencoding()
return u'{0} {1}'.format(date_str, packager.decode(encoding)) | [
"def",
"get_changelog_date_packager",
"(",
"self",
")",
":",
"try",
":",
"packager",
"=",
"subprocess",
".",
"Popen",
"(",
"'rpmdev-packager'",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"strip",
... | Returns part of the changelog entry, containing date and packager. | [
"Returns",
"part",
"of",
"the",
"changelog",
"entry",
"containing",
"date",
"and",
"packager",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/package_data.py#L89-L104 | train | 35,473 |
fedora-python/pyp2rpm | pyp2rpm/module_runners.py | RunpyModuleRunner.run | def run(self):
"""Executes the code of the specified module."""
with utils.ChangeDir(self.dirname):
sys.path.insert(0, self.dirname)
sys.argv[1:] = self.args
runpy.run_module(self.not_suffixed(self.filename),
run_name='__main__',
alter_sys=True) | python | def run(self):
"""Executes the code of the specified module."""
with utils.ChangeDir(self.dirname):
sys.path.insert(0, self.dirname)
sys.argv[1:] = self.args
runpy.run_module(self.not_suffixed(self.filename),
run_name='__main__',
alter_sys=True) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"utils",
".",
"ChangeDir",
"(",
"self",
".",
"dirname",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"self",
".",
"dirname",
")",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"=",
"self",
... | Executes the code of the specified module. | [
"Executes",
"the",
"code",
"of",
"the",
"specified",
"module",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/module_runners.py#L35-L42 | train | 35,474 |
fedora-python/pyp2rpm | pyp2rpm/module_runners.py | SubprocessModuleRunner.run | def run(self, interpreter):
"""Executes the code of the specified module. Deserializes captured
json data.
"""
with utils.ChangeDir(self.dirname):
command_list = ['PYTHONPATH=' + main_dir, interpreter,
self.filename] + list(self.args)
try:
proc = Popen(' '.join(command_list), stdout=PIPE, stderr=PIPE,
shell=True)
stream_data = proc.communicate()
except Exception as e:
logger.error(
"Error {0} while executing extract_dist command.".format(e))
raise ExtractionError
stream_data = [utils.console_to_str(s) for s in stream_data]
if proc.returncode:
logger.error(
"Subprocess failed, stdout: {0[0]}, stderr: {0[1]}".format(
stream_data))
self._result = json.loads(stream_data[0].split(
"extracted json data:\n")[-1].split("\n")[0]) | python | def run(self, interpreter):
"""Executes the code of the specified module. Deserializes captured
json data.
"""
with utils.ChangeDir(self.dirname):
command_list = ['PYTHONPATH=' + main_dir, interpreter,
self.filename] + list(self.args)
try:
proc = Popen(' '.join(command_list), stdout=PIPE, stderr=PIPE,
shell=True)
stream_data = proc.communicate()
except Exception as e:
logger.error(
"Error {0} while executing extract_dist command.".format(e))
raise ExtractionError
stream_data = [utils.console_to_str(s) for s in stream_data]
if proc.returncode:
logger.error(
"Subprocess failed, stdout: {0[0]}, stderr: {0[1]}".format(
stream_data))
self._result = json.loads(stream_data[0].split(
"extracted json data:\n")[-1].split("\n")[0]) | [
"def",
"run",
"(",
"self",
",",
"interpreter",
")",
":",
"with",
"utils",
".",
"ChangeDir",
"(",
"self",
".",
"dirname",
")",
":",
"command_list",
"=",
"[",
"'PYTHONPATH='",
"+",
"main_dir",
",",
"interpreter",
",",
"self",
".",
"filename",
"]",
"+",
"... | Executes the code of the specified module. Deserializes captured
json data. | [
"Executes",
"the",
"code",
"of",
"the",
"specified",
"module",
".",
"Deserializes",
"captured",
"json",
"data",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/module_runners.py#L52-L73 | train | 35,475 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | generator_to_list | def generator_to_list(fn):
"""This decorator is for flat_list function.
It converts returned generator to list.
"""
def wrapper(*args, **kw):
return list(fn(*args, **kw))
return wrapper | python | def generator_to_list(fn):
"""This decorator is for flat_list function.
It converts returned generator to list.
"""
def wrapper(*args, **kw):
return list(fn(*args, **kw))
return wrapper | [
"def",
"generator_to_list",
"(",
"fn",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"list",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
")",
"return",
"wrapper"
] | This decorator is for flat_list function.
It converts returned generator to list. | [
"This",
"decorator",
"is",
"for",
"flat_list",
"function",
".",
"It",
"converts",
"returned",
"generator",
"to",
"list",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L17-L23 | train | 35,476 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.get_content_of_file | def get_content_of_file(self, name, full_path=False):
"""Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
Args:
name: name of the file to get content of
Returns:
Content of the file with given name or None, if no such.
"""
if self.handle:
for member in self.handle.getmembers():
if (full_path and member.name == name) or (
not full_path and os.path.basename(
member.name) == name):
extracted = self.handle.extractfile(member)
return extracted.read().decode(
locale.getpreferredencoding())
return None | python | def get_content_of_file(self, name, full_path=False):
"""Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
Args:
name: name of the file to get content of
Returns:
Content of the file with given name or None, if no such.
"""
if self.handle:
for member in self.handle.getmembers():
if (full_path and member.name == name) or (
not full_path and os.path.basename(
member.name) == name):
extracted = self.handle.extractfile(member)
return extracted.read().decode(
locale.getpreferredencoding())
return None | [
"def",
"get_content_of_file",
"(",
"self",
",",
"name",
",",
"full_path",
"=",
"False",
")",
":",
"if",
"self",
".",
"handle",
":",
"for",
"member",
"in",
"self",
".",
"handle",
".",
"getmembers",
"(",
")",
":",
"if",
"(",
"full_path",
"and",
"member",... | Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
Args:
name: name of the file to get content of
Returns:
Content of the file with given name or None, if no such. | [
"Returns",
"content",
"of",
"file",
"from",
"archive",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L147-L168 | train | 35,477 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.extract_file | def extract_file(self, name, full_path=False, directory="."):
"""Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file.
"""
if self.handle:
for member in self.handle.getmembers():
if (full_path and member.name == name or
not full_path and os.path.basename(
member.name) == name):
# TODO handle KeyError exception
self.handle.extract(member, path=directory) | python | def extract_file(self, name, full_path=False, directory="."):
"""Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file.
"""
if self.handle:
for member in self.handle.getmembers():
if (full_path and member.name == name or
not full_path and os.path.basename(
member.name) == name):
# TODO handle KeyError exception
self.handle.extract(member, path=directory) | [
"def",
"extract_file",
"(",
"self",
",",
"name",
",",
"full_path",
"=",
"False",
",",
"directory",
"=",
"\".\"",
")",
":",
"if",
"self",
".",
"handle",
":",
"for",
"member",
"in",
"self",
".",
"handle",
".",
"getmembers",
"(",
")",
":",
"if",
"(",
... | Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file. | [
"Extract",
"a",
"member",
"from",
"the",
"archive",
"to",
"the",
"specified",
"working",
"directory",
".",
"Behaviour",
"of",
"name",
"and",
"pull_path",
"is",
"the",
"same",
"as",
"in",
"function",
"get_content_of_file",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L170-L181 | train | 35,478 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.extract_all | def extract_all(self, directory=".", members=None):
"""Extract all member from the archive to the specified working
directory.
"""
if self.handle:
self.handle.extractall(path=directory, members=members) | python | def extract_all(self, directory=".", members=None):
"""Extract all member from the archive to the specified working
directory.
"""
if self.handle:
self.handle.extractall(path=directory, members=members) | [
"def",
"extract_all",
"(",
"self",
",",
"directory",
"=",
"\".\"",
",",
"members",
"=",
"None",
")",
":",
"if",
"self",
".",
"handle",
":",
"self",
".",
"handle",
".",
"extractall",
"(",
"path",
"=",
"directory",
",",
"members",
"=",
"members",
")"
] | Extract all member from the archive to the specified working
directory. | [
"Extract",
"all",
"member",
"from",
"the",
"archive",
"to",
"the",
"specified",
"working",
"directory",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L183-L188 | train | 35,479 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.get_files_re | def get_files_re(self, file_re, full_path=False, ignorecase=False):
"""Finds all files that match file_re and returns their list.
Doesn't return directories, only files.
Args:
file_re: raw string to match files against (gets compiled into re)
full_path: whether to match against full path inside the archive
or just the filenames
ignorecase: whether to ignore case when using the given re
Returns:
List of full paths of files inside the archive that match the given
file_re.
"""
try:
if ignorecase:
compiled_re = re.compile(file_re, re.I)
else:
compiled_re = re.compile(file_re)
except sre_constants.error:
logger.error("Failed to compile regex: {}.".format(file_re))
return []
found = []
if self.handle:
for member in self.handle.getmembers():
if isinstance(member, TarInfo) and member.isdir():
pass # for TarInfo files, filter out directories
elif (full_path and compiled_re.search(member.name)) or (
not full_path and compiled_re.search(os.path.basename(
member.name))):
found.append(member.name)
return found | python | def get_files_re(self, file_re, full_path=False, ignorecase=False):
"""Finds all files that match file_re and returns their list.
Doesn't return directories, only files.
Args:
file_re: raw string to match files against (gets compiled into re)
full_path: whether to match against full path inside the archive
or just the filenames
ignorecase: whether to ignore case when using the given re
Returns:
List of full paths of files inside the archive that match the given
file_re.
"""
try:
if ignorecase:
compiled_re = re.compile(file_re, re.I)
else:
compiled_re = re.compile(file_re)
except sre_constants.error:
logger.error("Failed to compile regex: {}.".format(file_re))
return []
found = []
if self.handle:
for member in self.handle.getmembers():
if isinstance(member, TarInfo) and member.isdir():
pass # for TarInfo files, filter out directories
elif (full_path and compiled_re.search(member.name)) or (
not full_path and compiled_re.search(os.path.basename(
member.name))):
found.append(member.name)
return found | [
"def",
"get_files_re",
"(",
"self",
",",
"file_re",
",",
"full_path",
"=",
"False",
",",
"ignorecase",
"=",
"False",
")",
":",
"try",
":",
"if",
"ignorecase",
":",
"compiled_re",
"=",
"re",
".",
"compile",
"(",
"file_re",
",",
"re",
".",
"I",
")",
"e... | Finds all files that match file_re and returns their list.
Doesn't return directories, only files.
Args:
file_re: raw string to match files against (gets compiled into re)
full_path: whether to match against full path inside the archive
or just the filenames
ignorecase: whether to ignore case when using the given re
Returns:
List of full paths of files inside the archive that match the given
file_re. | [
"Finds",
"all",
"files",
"that",
"match",
"file_re",
"and",
"returns",
"their",
"list",
".",
"Doesn",
"t",
"return",
"directories",
"only",
"files",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L215-L248 | train | 35,480 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.get_directories_re | def get_directories_re(
self,
directory_re,
full_path=False,
ignorecase=False):
"""Same as get_files_re, but for directories"""
if ignorecase:
compiled_re = re.compile(directory_re, re.I)
else:
compiled_re = re.compile(directory_re)
found = set()
if self.handle:
for member in self.handle.getmembers():
# zipfiles only list directories => have to work around that
if isinstance(member, ZipInfo):
to_match = os.path.dirname(member.name)
# tarfiles => only match directories
elif isinstance(member, TarInfo) and member.isdir():
to_match = member.name
else:
to_match = None
if to_match:
if ((full_path and compiled_re.search(to_match)) or (
not full_path and compiled_re.search(
os.path.basename(to_match)))):
found.add(to_match)
return list(found) | python | def get_directories_re(
self,
directory_re,
full_path=False,
ignorecase=False):
"""Same as get_files_re, but for directories"""
if ignorecase:
compiled_re = re.compile(directory_re, re.I)
else:
compiled_re = re.compile(directory_re)
found = set()
if self.handle:
for member in self.handle.getmembers():
# zipfiles only list directories => have to work around that
if isinstance(member, ZipInfo):
to_match = os.path.dirname(member.name)
# tarfiles => only match directories
elif isinstance(member, TarInfo) and member.isdir():
to_match = member.name
else:
to_match = None
if to_match:
if ((full_path and compiled_re.search(to_match)) or (
not full_path and compiled_re.search(
os.path.basename(to_match)))):
found.add(to_match)
return list(found) | [
"def",
"get_directories_re",
"(",
"self",
",",
"directory_re",
",",
"full_path",
"=",
"False",
",",
"ignorecase",
"=",
"False",
")",
":",
"if",
"ignorecase",
":",
"compiled_re",
"=",
"re",
".",
"compile",
"(",
"directory_re",
",",
"re",
".",
"I",
")",
"e... | Same as get_files_re, but for directories | [
"Same",
"as",
"get_files_re",
"but",
"for",
"directories"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L250-L279 | train | 35,481 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | Archive.top_directory | def top_directory(self):
"""Return the name of the archive topmost directory."""
if self.handle:
return os.path.commonprefix(self.handle.getnames()).rstrip('/') | python | def top_directory(self):
"""Return the name of the archive topmost directory."""
if self.handle:
return os.path.commonprefix(self.handle.getnames()).rstrip('/') | [
"def",
"top_directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
":",
"return",
"os",
".",
"path",
".",
"commonprefix",
"(",
"self",
".",
"handle",
".",
"getnames",
"(",
")",
")",
".",
"rstrip",
"(",
"'/'",
")"
] | Return the name of the archive topmost directory. | [
"Return",
"the",
"name",
"of",
"the",
"archive",
"topmost",
"directory",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L282-L285 | train | 35,482 |
fedora-python/pyp2rpm | pyp2rpm/name_convertor.py | NameConvertor.base_name | def base_name(self, name):
"""Removes any python prefixes of suffixes from name if present."""
base_name = name.replace('.', "-")
# remove python prefix if present
found_prefix = self.reg_start.search(name)
if found_prefix:
base_name = found_prefix.group(2)
# remove -pythonXY like suffix if present
found_end = self.reg_end.search(name.lower())
if found_end:
base_name = found_end.group(1)
return base_name | python | def base_name(self, name):
"""Removes any python prefixes of suffixes from name if present."""
base_name = name.replace('.', "-")
# remove python prefix if present
found_prefix = self.reg_start.search(name)
if found_prefix:
base_name = found_prefix.group(2)
# remove -pythonXY like suffix if present
found_end = self.reg_end.search(name.lower())
if found_end:
base_name = found_end.group(1)
return base_name | [
"def",
"base_name",
"(",
"self",
",",
"name",
")",
":",
"base_name",
"=",
"name",
".",
"replace",
"(",
"'.'",
",",
"\"-\"",
")",
"# remove python prefix if present",
"found_prefix",
"=",
"self",
".",
"reg_start",
".",
"search",
"(",
"name",
")",
"if",
"fou... | Removes any python prefixes of suffixes from name if present. | [
"Removes",
"any",
"python",
"prefixes",
"of",
"suffixes",
"from",
"name",
"if",
"present",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/name_convertor.py#L108-L121 | train | 35,483 |
fedora-python/pyp2rpm | pyp2rpm/name_convertor.py | NameVariants.merge | def merge(self, other):
"""Merges object with other NameVariants object, not set values
of self.variants are replace by values from other object.
"""
if not isinstance(other, NameVariants):
raise TypeError("NameVariants isinstance can be merge with"
"other isinstance of the same class")
for key in self.variants:
self.variants[key] = self.variants[key] or other.variants[key]
return self | python | def merge(self, other):
"""Merges object with other NameVariants object, not set values
of self.variants are replace by values from other object.
"""
if not isinstance(other, NameVariants):
raise TypeError("NameVariants isinstance can be merge with"
"other isinstance of the same class")
for key in self.variants:
self.variants[key] = self.variants[key] or other.variants[key]
return self | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"NameVariants",
")",
":",
"raise",
"TypeError",
"(",
"\"NameVariants isinstance can be merge with\"",
"\"other isinstance of the same class\"",
")",
"for",
"key",
"in"... | Merges object with other NameVariants object, not set values
of self.variants are replace by values from other object. | [
"Merges",
"object",
"with",
"other",
"NameVariants",
"object",
"not",
"set",
"values",
"of",
"self",
".",
"variants",
"are",
"replace",
"by",
"values",
"from",
"other",
"object",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/name_convertor.py#L144-L154 | train | 35,484 |
fedora-python/pyp2rpm | pyp2rpm/convertor.py | Convertor.merge_versions | def merge_versions(self, data):
"""Merges python versions specified in command lines options with
extracted versions, checks if some of the versions is not > 2 if EPEL6
template will be used. attributes base_python_version and
python_versions contain values specified by command line options or
default values, data.python_versions contains extracted data.
"""
if self.template == "epel6.spec":
# if user requested version greater than 2, writes error message
# and exits
requested_versions = self.python_versions
if self.base_python_version:
requested_versions += [self.base_python_version]
if any(int(ver[0]) > 2 for ver in requested_versions):
sys.stderr.write(
"Invalid version, major number of python version for "
"EPEL6 spec file must not be greater than 2.\n")
sys.exit(1)
# if version greater than 2 were extracted it is removed
data.python_versions = [
ver for ver in data.python_versions if not int(ver[0]) > 2]
# Set python versions from default values in settings.
base_version, additional_versions = (
self.template_base_py_ver, self.template_py_vers)
# Sync default values with extracted versions from PyPI classifiers.
if data.python_versions:
if base_version not in data.python_versions:
base_version = data.python_versions[0]
additional_versions = [
v for v in additional_versions if v in data.python_versions]
# Override default values with those set from command line if any.
if self.base_python_version:
base_version = self.base_python_version
if self.python_versions:
additional_versions = [
v for v in self.python_versions if v != base_version]
data.base_python_version = base_version
data.python_versions = additional_versions | python | def merge_versions(self, data):
"""Merges python versions specified in command lines options with
extracted versions, checks if some of the versions is not > 2 if EPEL6
template will be used. attributes base_python_version and
python_versions contain values specified by command line options or
default values, data.python_versions contains extracted data.
"""
if self.template == "epel6.spec":
# if user requested version greater than 2, writes error message
# and exits
requested_versions = self.python_versions
if self.base_python_version:
requested_versions += [self.base_python_version]
if any(int(ver[0]) > 2 for ver in requested_versions):
sys.stderr.write(
"Invalid version, major number of python version for "
"EPEL6 spec file must not be greater than 2.\n")
sys.exit(1)
# if version greater than 2 were extracted it is removed
data.python_versions = [
ver for ver in data.python_versions if not int(ver[0]) > 2]
# Set python versions from default values in settings.
base_version, additional_versions = (
self.template_base_py_ver, self.template_py_vers)
# Sync default values with extracted versions from PyPI classifiers.
if data.python_versions:
if base_version not in data.python_versions:
base_version = data.python_versions[0]
additional_versions = [
v for v in additional_versions if v in data.python_versions]
# Override default values with those set from command line if any.
if self.base_python_version:
base_version = self.base_python_version
if self.python_versions:
additional_versions = [
v for v in self.python_versions if v != base_version]
data.base_python_version = base_version
data.python_versions = additional_versions | [
"def",
"merge_versions",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"template",
"==",
"\"epel6.spec\"",
":",
"# if user requested version greater than 2, writes error message",
"# and exits",
"requested_versions",
"=",
"self",
".",
"python_versions",
"if",
"... | Merges python versions specified in command lines options with
extracted versions, checks if some of the versions is not > 2 if EPEL6
template will be used. attributes base_python_version and
python_versions contain values specified by command line options or
default values, data.python_versions contains extracted data. | [
"Merges",
"python",
"versions",
"specified",
"in",
"command",
"lines",
"options",
"with",
"extracted",
"versions",
"checks",
"if",
"some",
"of",
"the",
"versions",
"is",
"not",
">",
"2",
"if",
"EPEL6",
"template",
"will",
"be",
"used",
".",
"attributes",
"ba... | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/convertor.py#L81-L123 | train | 35,485 |
fedora-python/pyp2rpm | pyp2rpm/convertor.py | Convertor.getter | def getter(self):
"""Returns an instance of proper PackageGetter subclass. Always
returns the same instance.
Returns:
Instance of the proper PackageGetter subclass according to
provided argument.
Raises:
NoSuchSourceException if source to get the package from is unknown
NoSuchPackageException if the package is unknown on PyPI
"""
if not hasattr(self, '_getter'):
if not self.pypi:
self._getter = package_getters.LocalFileGetter(
self.package,
self.save_dir)
else:
logger.debug(
'{0} does not exist as local file trying PyPI.'.format(
self.package))
self._getter = package_getters.PypiDownloader(
self.client,
self.package,
self.version,
self.save_dir)
return self._getter | python | def getter(self):
"""Returns an instance of proper PackageGetter subclass. Always
returns the same instance.
Returns:
Instance of the proper PackageGetter subclass according to
provided argument.
Raises:
NoSuchSourceException if source to get the package from is unknown
NoSuchPackageException if the package is unknown on PyPI
"""
if not hasattr(self, '_getter'):
if not self.pypi:
self._getter = package_getters.LocalFileGetter(
self.package,
self.save_dir)
else:
logger.debug(
'{0} does not exist as local file trying PyPI.'.format(
self.package))
self._getter = package_getters.PypiDownloader(
self.client,
self.package,
self.version,
self.save_dir)
return self._getter | [
"def",
"getter",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_getter'",
")",
":",
"if",
"not",
"self",
".",
"pypi",
":",
"self",
".",
"_getter",
"=",
"package_getters",
".",
"LocalFileGetter",
"(",
"self",
".",
"package",
",",
... | Returns an instance of proper PackageGetter subclass. Always
returns the same instance.
Returns:
Instance of the proper PackageGetter subclass according to
provided argument.
Raises:
NoSuchSourceException if source to get the package from is unknown
NoSuchPackageException if the package is unknown on PyPI | [
"Returns",
"an",
"instance",
"of",
"proper",
"PackageGetter",
"subclass",
".",
"Always",
"returns",
"the",
"same",
"instance",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/convertor.py#L172-L198 | train | 35,486 |
fedora-python/pyp2rpm | pyp2rpm/convertor.py | Convertor.metadata_extractor | def metadata_extractor(self):
"""Returns an instance of proper MetadataExtractor subclass.
Always returns the same instance.
Returns:
The proper MetadataExtractor subclass according to local file
suffix.
"""
if not hasattr(self, '_local_file'):
raise AttributeError("local_file attribute must be set before "
"calling metadata_extractor")
if not hasattr(self, '_metadata_extractor'):
if self.local_file.endswith('.whl'):
logger.info("Getting metadata from wheel using "
"WheelMetadataExtractor.")
extractor_cls = metadata_extractors.WheelMetadataExtractor
else:
logger.info("Getting metadata from setup.py using "
"SetupPyMetadataExtractor.")
extractor_cls = metadata_extractors.SetupPyMetadataExtractor
base_python_version = (
self.base_python_version or self.template_base_py_ver)
self._metadata_extractor = extractor_cls(
self.local_file,
self.name,
self.name_convertor,
self.version,
self.rpm_name,
self.venv,
base_python_version)
return self._metadata_extractor | python | def metadata_extractor(self):
"""Returns an instance of proper MetadataExtractor subclass.
Always returns the same instance.
Returns:
The proper MetadataExtractor subclass according to local file
suffix.
"""
if not hasattr(self, '_local_file'):
raise AttributeError("local_file attribute must be set before "
"calling metadata_extractor")
if not hasattr(self, '_metadata_extractor'):
if self.local_file.endswith('.whl'):
logger.info("Getting metadata from wheel using "
"WheelMetadataExtractor.")
extractor_cls = metadata_extractors.WheelMetadataExtractor
else:
logger.info("Getting metadata from setup.py using "
"SetupPyMetadataExtractor.")
extractor_cls = metadata_extractors.SetupPyMetadataExtractor
base_python_version = (
self.base_python_version or self.template_base_py_ver)
self._metadata_extractor = extractor_cls(
self.local_file,
self.name,
self.name_convertor,
self.version,
self.rpm_name,
self.venv,
base_python_version)
return self._metadata_extractor | [
"def",
"metadata_extractor",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_local_file'",
")",
":",
"raise",
"AttributeError",
"(",
"\"local_file attribute must be set before \"",
"\"calling metadata_extractor\"",
")",
"if",
"not",
"hasattr",
"(",... | Returns an instance of proper MetadataExtractor subclass.
Always returns the same instance.
Returns:
The proper MetadataExtractor subclass according to local file
suffix. | [
"Returns",
"an",
"instance",
"of",
"proper",
"MetadataExtractor",
"subclass",
".",
"Always",
"returns",
"the",
"same",
"instance",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/convertor.py#L245-L278 | train | 35,487 |
fedora-python/pyp2rpm | pyp2rpm/convertor.py | Convertor.client | def client(self):
"""XMLRPC client for PyPI. Always returns the same instance.
If the package is provided as a path to compressed source file,
PyPI will not be used and the client will not be instantiated.
Returns:
XMLRPC client for PyPI or None.
"""
if self.proxy:
proxyhandler = urllib.ProxyHandler({"http": self.proxy})
opener = urllib.build_opener(proxyhandler)
urllib.install_opener(opener)
transport = ProxyTransport()
if not hasattr(self, '_client'):
transport = None
if self.pypi:
if self.proxy:
logger.info('Using provided proxy: {0}.'.format(
self.proxy))
self._client = xmlrpclib.ServerProxy(settings.PYPI_URL,
transport=transport)
self._client_set = True
else:
self._client = None
return self._client | python | def client(self):
"""XMLRPC client for PyPI. Always returns the same instance.
If the package is provided as a path to compressed source file,
PyPI will not be used and the client will not be instantiated.
Returns:
XMLRPC client for PyPI or None.
"""
if self.proxy:
proxyhandler = urllib.ProxyHandler({"http": self.proxy})
opener = urllib.build_opener(proxyhandler)
urllib.install_opener(opener)
transport = ProxyTransport()
if not hasattr(self, '_client'):
transport = None
if self.pypi:
if self.proxy:
logger.info('Using provided proxy: {0}.'.format(
self.proxy))
self._client = xmlrpclib.ServerProxy(settings.PYPI_URL,
transport=transport)
self._client_set = True
else:
self._client = None
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"proxy",
":",
"proxyhandler",
"=",
"urllib",
".",
"ProxyHandler",
"(",
"{",
"\"http\"",
":",
"self",
".",
"proxy",
"}",
")",
"opener",
"=",
"urllib",
".",
"build_opener",
"(",
"proxyhandler",
"... | XMLRPC client for PyPI. Always returns the same instance.
If the package is provided as a path to compressed source file,
PyPI will not be used and the client will not be instantiated.
Returns:
XMLRPC client for PyPI or None. | [
"XMLRPC",
"client",
"for",
"PyPI",
".",
"Always",
"returns",
"the",
"same",
"instance",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/convertor.py#L281-L307 | train | 35,488 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | memoize_by_args | def memoize_by_args(func):
"""Memoizes return value of a func based on args."""
memory = {}
@functools.wraps(func)
def memoized(*args):
if args not in memory.keys():
value = func(*args)
memory[args] = value
return memory[args]
return memoized | python | def memoize_by_args(func):
"""Memoizes return value of a func based on args."""
memory = {}
@functools.wraps(func)
def memoized(*args):
if args not in memory.keys():
value = func(*args)
memory[args] = value
return memory[args]
return memoized | [
"def",
"memoize_by_args",
"(",
"func",
")",
":",
"memory",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"memoized",
"(",
"*",
"args",
")",
":",
"if",
"args",
"not",
"in",
"memory",
".",
"keys",
"(",
")",
":",
"value",
"... | Memoizes return value of a func based on args. | [
"Memoizes",
"return",
"value",
"of",
"a",
"func",
"based",
"on",
"args",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L44-L56 | train | 35,489 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | build_srpm | def build_srpm(specfile, save_dir):
"""Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree
"""
logger.info('Starting rpmbuild to build: {0} SRPM.'.format(specfile))
if save_dir != get_default_save_path():
try:
msg = subprocess.Popen(
['rpmbuild',
'--define', '_sourcedir {0}'.format(save_dir),
'--define', '_builddir {0}'.format(save_dir),
'--define', '_srcrpmdir {0}'.format(save_dir),
'--define', '_rpmdir {0}'.format(save_dir),
'-bs', specfile], stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
logger.error(
"Rpmbuild failed for specfile: {0} and save_dir: {1}".format(
specfile, save_dir), exc_info=True)
msg = 'Rpmbuild failed. See log for more info.'
return msg
else:
if not os.path.exists(save_dir):
raise IOError("Specify folder to store a file (SAVE_DIR) "
"or install rpmdevtools.")
try:
msg = subprocess.Popen(
['rpmbuild',
'--define', '_sourcedir {0}'.format(save_dir + '/SOURCES'),
'--define', '_builddir {0}'.format(save_dir + '/BUILD'),
'--define', '_srcrpmdir {0}'.format(save_dir + '/SRPMS'),
'--define', '_rpmdir {0}'.format(save_dir + '/RPMS'),
'-bs', specfile], stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
logger.error("Rpmbuild failed for specfile: {0} and save_dir: "
"{1}".format(specfile, save_dir), exc_info=True)
msg = 'Rpmbuild failed. See log for more info.'
return msg | python | def build_srpm(specfile, save_dir):
"""Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree
"""
logger.info('Starting rpmbuild to build: {0} SRPM.'.format(specfile))
if save_dir != get_default_save_path():
try:
msg = subprocess.Popen(
['rpmbuild',
'--define', '_sourcedir {0}'.format(save_dir),
'--define', '_builddir {0}'.format(save_dir),
'--define', '_srcrpmdir {0}'.format(save_dir),
'--define', '_rpmdir {0}'.format(save_dir),
'-bs', specfile], stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
logger.error(
"Rpmbuild failed for specfile: {0} and save_dir: {1}".format(
specfile, save_dir), exc_info=True)
msg = 'Rpmbuild failed. See log for more info.'
return msg
else:
if not os.path.exists(save_dir):
raise IOError("Specify folder to store a file (SAVE_DIR) "
"or install rpmdevtools.")
try:
msg = subprocess.Popen(
['rpmbuild',
'--define', '_sourcedir {0}'.format(save_dir + '/SOURCES'),
'--define', '_builddir {0}'.format(save_dir + '/BUILD'),
'--define', '_srcrpmdir {0}'.format(save_dir + '/SRPMS'),
'--define', '_rpmdir {0}'.format(save_dir + '/RPMS'),
'-bs', specfile], stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
logger.error("Rpmbuild failed for specfile: {0} and save_dir: "
"{1}".format(specfile, save_dir), exc_info=True)
msg = 'Rpmbuild failed. See log for more info.'
return msg | [
"def",
"build_srpm",
"(",
"specfile",
",",
"save_dir",
")",
":",
"logger",
".",
"info",
"(",
"'Starting rpmbuild to build: {0} SRPM.'",
".",
"format",
"(",
"specfile",
")",
")",
"if",
"save_dir",
"!=",
"get_default_save_path",
"(",
")",
":",
"try",
":",
"msg",... | Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree | [
"Builds",
"a",
"srpm",
"from",
"given",
"specfile",
"using",
"rpmbuild",
".",
"Generated",
"srpm",
"is",
"stored",
"in",
"directory",
"specified",
"by",
"save_dir",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L59-L101 | train | 35,490 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | remove_major_minor_suffix | def remove_major_minor_suffix(scripts):
"""Checks if executables already contain a "-MAJOR.MINOR" suffix. """
minor_major_regex = re.compile("-\d.?\d?$")
return [x for x in scripts if not minor_major_regex.search(x)] | python | def remove_major_minor_suffix(scripts):
"""Checks if executables already contain a "-MAJOR.MINOR" suffix. """
minor_major_regex = re.compile("-\d.?\d?$")
return [x for x in scripts if not minor_major_regex.search(x)] | [
"def",
"remove_major_minor_suffix",
"(",
"scripts",
")",
":",
"minor_major_regex",
"=",
"re",
".",
"compile",
"(",
"\"-\\d.?\\d?$\"",
")",
"return",
"[",
"x",
"for",
"x",
"in",
"scripts",
"if",
"not",
"minor_major_regex",
".",
"search",
"(",
"x",
")",
"]"
] | Checks if executables already contain a "-MAJOR.MINOR" suffix. | [
"Checks",
"if",
"executables",
"already",
"contain",
"a",
"-",
"MAJOR",
".",
"MINOR",
"suffix",
"."
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L104-L107 | train | 35,491 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | runtime_to_build | def runtime_to_build(runtime_deps):
"""Adds all runtime deps to build deps"""
build_deps = copy.deepcopy(runtime_deps)
for dep in build_deps:
if len(dep) > 0:
dep[0] = 'BuildRequires'
return build_deps | python | def runtime_to_build(runtime_deps):
"""Adds all runtime deps to build deps"""
build_deps = copy.deepcopy(runtime_deps)
for dep in build_deps:
if len(dep) > 0:
dep[0] = 'BuildRequires'
return build_deps | [
"def",
"runtime_to_build",
"(",
"runtime_deps",
")",
":",
"build_deps",
"=",
"copy",
".",
"deepcopy",
"(",
"runtime_deps",
")",
"for",
"dep",
"in",
"build_deps",
":",
"if",
"len",
"(",
"dep",
")",
">",
"0",
":",
"dep",
"[",
"0",
"]",
"=",
"'BuildRequir... | Adds all runtime deps to build deps | [
"Adds",
"all",
"runtime",
"deps",
"to",
"build",
"deps"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L110-L116 | train | 35,492 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | unique_deps | def unique_deps(deps):
"""Remove duplicities from deps list of the lists"""
deps.sort()
return list(k for k, _ in itertools.groupby(deps)) | python | def unique_deps(deps):
"""Remove duplicities from deps list of the lists"""
deps.sort()
return list(k for k, _ in itertools.groupby(deps)) | [
"def",
"unique_deps",
"(",
"deps",
")",
":",
"deps",
".",
"sort",
"(",
")",
"return",
"list",
"(",
"k",
"for",
"k",
",",
"_",
"in",
"itertools",
".",
"groupby",
"(",
"deps",
")",
")"
] | Remove duplicities from deps list of the lists | [
"Remove",
"duplicities",
"from",
"deps",
"list",
"of",
"the",
"lists"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L119-L122 | train | 35,493 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | c_time_locale | def c_time_locale():
"""Context manager with C LC_TIME locale"""
old_time_locale = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, 'C')
yield
locale.setlocale(locale.LC_TIME, old_time_locale) | python | def c_time_locale():
"""Context manager with C LC_TIME locale"""
old_time_locale = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, 'C')
yield
locale.setlocale(locale.LC_TIME, old_time_locale) | [
"def",
"c_time_locale",
"(",
")",
":",
"old_time_locale",
"=",
"locale",
".",
"getlocale",
"(",
"locale",
".",
"LC_TIME",
")",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_TIME",
",",
"'C'",
")",
"yield",
"locale",
".",
"setlocale",
"(",
"locale",
... | Context manager with C LC_TIME locale | [
"Context",
"manager",
"with",
"C",
"LC_TIME",
"locale"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L137-L142 | train | 35,494 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | rpm_eval | def rpm_eval(macro):
"""Get value of given macro using rpm tool"""
try:
value = subprocess.Popen(
['rpm', '--eval', macro],
stdout=subprocess.PIPE).communicate()[0].strip()
except OSError:
logger.error('Failed to get value of {0} rpm macro'.format(
macro), exc_info=True)
value = b''
return console_to_str(value) | python | def rpm_eval(macro):
"""Get value of given macro using rpm tool"""
try:
value = subprocess.Popen(
['rpm', '--eval', macro],
stdout=subprocess.PIPE).communicate()[0].strip()
except OSError:
logger.error('Failed to get value of {0} rpm macro'.format(
macro), exc_info=True)
value = b''
return console_to_str(value) | [
"def",
"rpm_eval",
"(",
"macro",
")",
":",
"try",
":",
"value",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'rpm'",
",",
"'--eval'",
",",
"macro",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",... | Get value of given macro using rpm tool | [
"Get",
"value",
"of",
"given",
"macro",
"using",
"rpm",
"tool"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L145-L155 | train | 35,495 |
fedora-python/pyp2rpm | pyp2rpm/utils.py | get_default_save_path | def get_default_save_path():
"""Return default save path for the packages"""
macro = '%{_topdir}'
if rpm:
save_path = rpm.expandMacro(macro)
else:
save_path = rpm_eval(macro)
if not save_path:
logger.warn("rpm tools are missing, using default save path "
"~/rpmbuild/.")
save_path = os.path.expanduser('~/rpmbuild')
return save_path | python | def get_default_save_path():
"""Return default save path for the packages"""
macro = '%{_topdir}'
if rpm:
save_path = rpm.expandMacro(macro)
else:
save_path = rpm_eval(macro)
if not save_path:
logger.warn("rpm tools are missing, using default save path "
"~/rpmbuild/.")
save_path = os.path.expanduser('~/rpmbuild')
return save_path | [
"def",
"get_default_save_path",
"(",
")",
":",
"macro",
"=",
"'%{_topdir}'",
"if",
"rpm",
":",
"save_path",
"=",
"rpm",
".",
"expandMacro",
"(",
"macro",
")",
"else",
":",
"save_path",
"=",
"rpm_eval",
"(",
"macro",
")",
"if",
"not",
"save_path",
":",
"l... | Return default save path for the packages | [
"Return",
"default",
"save",
"path",
"for",
"the",
"packages"
] | 853eb3d226689a5ccdcdb9358b1a3394fafbd2b5 | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/utils.py#L158-L169 | train | 35,496 |
spacetelescope/drizzlepac | drizzlepac/alignimages.py | check_and_get_data | def check_and_get_data(input_list,**pars):
"""Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list: list
list of full filenames
"""
empty_list = []
retrieve_list = [] # Actual files retrieved via astroquery and resident on disk
candidate_list = [] # File names gathered from *_asn.fits file
ipppssoot_list = [] # ipppssoot names used to avoid duplicate downloads
total_input_list = [] # Output full filename list of data on disk
# Loop over the input_list to determine if the item in the input_list is a full association file
# (*_asn.fits), a full individual image file (aka singleton, *_flt.fits), or a root name specification
# (association or singleton, ipppssoot).
for input_item in input_list:
print('Input item: ', input_item)
indx = input_item.find('_')
# Input with a suffix (_xxx.fits)
if indx != -1:
lc_input_item = input_item.lower()
suffix = lc_input_item[indx+1:indx+4]
print('file: ', lc_input_item)
# For an association, need to open the table and read the image names as this could
# be a custom association. The assumption is this file is on local disk when specified
# in this manner (vs just the ipppssoot of the association).
# This "if" block just collects the wanted full file names.
if suffix == 'asn':
try:
asntab = Table.read(input_item, format='fits')
except FileNotFoundError:
log.error('File {} not found.'.format(input_item))
return(empty_list)
for row in asntab:
if row['MEMTYPE'].startswith('PROD'):
continue
memname = row['MEMNAME'].lower().strip()
# Need to check if the MEMNAME is a full filename or an ipppssoot
if memname.find('_') != -1:
candidate_list.append(memname)
else:
candidate_list.append(memname + '_flc.fits')
elif suffix == 'flc' or suffix == 'flt':
if lc_input_item not in candidate_list:
candidate_list.append(lc_input_item)
else:
log.error('Inappropriate file suffix: {}. Looking for "asn.fits", "flc.fits", or "flt.fits".'.format(suffix))
return(empty_list)
# Input is an ipppssoot (association or singleton), nine characters by definition.
# This "else" block actually downloads the data specified as ipppssoot.
elif len(input_item) == 9:
try:
if input_item not in ipppssoot_list:
# An ipppssoot of an individual file which is part of an association cannot be
# retrieved from MAST
retrieve_list = aqutils.retrieve_observation(input_item,**pars)
# If the retrieved list is not empty, add filename(s) to the total_input_list.
# Also, update the ipppssoot_list so we do not try to download the data again. Need
# to do this since retrieve_list can be empty because (1) data cannot be acquired (error)
# or (2) data is already on disk (ok).
if retrieve_list:
total_input_list += retrieve_list
ipppssoot_list.append(input_item)
else:
log.error('File {} cannot be retrieved from MAST.'.format(input_item))
return(empty_list)
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stdout)
# Only the retrieve_list files via astroquery have been put into the total_input_list thus far.
# Now check candidate_list to detect or acquire the requested files from MAST via
# astroquery.
for file in candidate_list:
# If the file is found on disk, add it to the total_input_list and continue
if glob.glob(file):
total_input_list.append(file)
continue
else:
log.error('File {} cannot be found on the local disk.'.format(file))
return(empty_list)
log.info("TOTAL INPUT LIST: {}".format(total_input_list))
return(total_input_list) | python | def check_and_get_data(input_list,**pars):
"""Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list: list
list of full filenames
"""
empty_list = []
retrieve_list = [] # Actual files retrieved via astroquery and resident on disk
candidate_list = [] # File names gathered from *_asn.fits file
ipppssoot_list = [] # ipppssoot names used to avoid duplicate downloads
total_input_list = [] # Output full filename list of data on disk
# Loop over the input_list to determine if the item in the input_list is a full association file
# (*_asn.fits), a full individual image file (aka singleton, *_flt.fits), or a root name specification
# (association or singleton, ipppssoot).
for input_item in input_list:
print('Input item: ', input_item)
indx = input_item.find('_')
# Input with a suffix (_xxx.fits)
if indx != -1:
lc_input_item = input_item.lower()
suffix = lc_input_item[indx+1:indx+4]
print('file: ', lc_input_item)
# For an association, need to open the table and read the image names as this could
# be a custom association. The assumption is this file is on local disk when specified
# in this manner (vs just the ipppssoot of the association).
# This "if" block just collects the wanted full file names.
if suffix == 'asn':
try:
asntab = Table.read(input_item, format='fits')
except FileNotFoundError:
log.error('File {} not found.'.format(input_item))
return(empty_list)
for row in asntab:
if row['MEMTYPE'].startswith('PROD'):
continue
memname = row['MEMNAME'].lower().strip()
# Need to check if the MEMNAME is a full filename or an ipppssoot
if memname.find('_') != -1:
candidate_list.append(memname)
else:
candidate_list.append(memname + '_flc.fits')
elif suffix == 'flc' or suffix == 'flt':
if lc_input_item not in candidate_list:
candidate_list.append(lc_input_item)
else:
log.error('Inappropriate file suffix: {}. Looking for "asn.fits", "flc.fits", or "flt.fits".'.format(suffix))
return(empty_list)
# Input is an ipppssoot (association or singleton), nine characters by definition.
# This "else" block actually downloads the data specified as ipppssoot.
elif len(input_item) == 9:
try:
if input_item not in ipppssoot_list:
# An ipppssoot of an individual file which is part of an association cannot be
# retrieved from MAST
retrieve_list = aqutils.retrieve_observation(input_item,**pars)
# If the retrieved list is not empty, add filename(s) to the total_input_list.
# Also, update the ipppssoot_list so we do not try to download the data again. Need
# to do this since retrieve_list can be empty because (1) data cannot be acquired (error)
# or (2) data is already on disk (ok).
if retrieve_list:
total_input_list += retrieve_list
ipppssoot_list.append(input_item)
else:
log.error('File {} cannot be retrieved from MAST.'.format(input_item))
return(empty_list)
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_tb, file=sys.stdout)
# Only the retrieve_list files via astroquery have been put into the total_input_list thus far.
# Now check candidate_list to detect or acquire the requested files from MAST via
# astroquery.
for file in candidate_list:
# If the file is found on disk, add it to the total_input_list and continue
if glob.glob(file):
total_input_list.append(file)
continue
else:
log.error('File {} cannot be found on the local disk.'.format(file))
return(empty_list)
log.info("TOTAL INPUT LIST: {}".format(total_input_list))
return(total_input_list) | [
"def",
"check_and_get_data",
"(",
"input_list",
",",
"*",
"*",
"pars",
")",
":",
"empty_list",
"=",
"[",
"]",
"retrieve_list",
"=",
"[",
"]",
"# Actual files retrieved via astroquery and resident on disk",
"candidate_list",
"=",
"[",
"]",
"# File names gathered from *_a... | Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list: list
list of full filenames | [
"Verify",
"that",
"all",
"specified",
"files",
"are",
"present",
".",
"If",
"not",
"retrieve",
"them",
"from",
"MAST",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L78-L172 | train | 35,497 |
spacetelescope/drizzlepac | drizzlepac/alignimages.py | perform_align | def perform_align(input_list, **kwargs):
"""Main calling function.
Parameters
----------
input_list : list
List of one or more IPPSSOOTs (rootnames) to align.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories?
clobber : Boolean
Download and overwrite existing local copies of input files?
debug : Boolean
Attempt to use saved sourcelists stored in pickle files if they exist, or if they do not exist, save
sourcelists in pickle files for reuse so that step 4 can be skipped for faster subsequent debug/development
runs??
update_hdr_wcs : Boolean
Write newly computed WCS information to image image headers?
print_fit_parameters : Boolean
Specify whether or not to print out FIT results for each chip.
print_git_info : Boolean
Display git repository information?
output : Boolean
Should utils.astrometric_utils.create_astrometric_catalog() generate file 'ref_cat.ecsv' and should
generate_source_catalogs() generate the .reg region files for every chip of every input image and should
generate_astrometric_catalog() generate file 'refcatalog.cat'?
Updates
-------
filteredTable: Astropy Table
Table which contains processing information and alignment results for every raw image evaluated
"""
filteredTable = Table()
run_align(input_list, result=filteredTable, **kwargs)
return filteredTable | python | def perform_align(input_list, **kwargs):
"""Main calling function.
Parameters
----------
input_list : list
List of one or more IPPSSOOTs (rootnames) to align.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories?
clobber : Boolean
Download and overwrite existing local copies of input files?
debug : Boolean
Attempt to use saved sourcelists stored in pickle files if they exist, or if they do not exist, save
sourcelists in pickle files for reuse so that step 4 can be skipped for faster subsequent debug/development
runs??
update_hdr_wcs : Boolean
Write newly computed WCS information to image image headers?
print_fit_parameters : Boolean
Specify whether or not to print out FIT results for each chip.
print_git_info : Boolean
Display git repository information?
output : Boolean
Should utils.astrometric_utils.create_astrometric_catalog() generate file 'ref_cat.ecsv' and should
generate_source_catalogs() generate the .reg region files for every chip of every input image and should
generate_astrometric_catalog() generate file 'refcatalog.cat'?
Updates
-------
filteredTable: Astropy Table
Table which contains processing information and alignment results for every raw image evaluated
"""
filteredTable = Table()
run_align(input_list, result=filteredTable, **kwargs)
return filteredTable | [
"def",
"perform_align",
"(",
"input_list",
",",
"*",
"*",
"kwargs",
")",
":",
"filteredTable",
"=",
"Table",
"(",
")",
"run_align",
"(",
"input_list",
",",
"result",
"=",
"filteredTable",
",",
"*",
"*",
"kwargs",
")",
"return",
"filteredTable"
] | Main calling function.
Parameters
----------
input_list : list
List of one or more IPPSSOOTs (rootnames) to align.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories?
clobber : Boolean
Download and overwrite existing local copies of input files?
debug : Boolean
Attempt to use saved sourcelists stored in pickle files if they exist, or if they do not exist, save
sourcelists in pickle files for reuse so that step 4 can be skipped for faster subsequent debug/development
runs??
update_hdr_wcs : Boolean
Write newly computed WCS information to image image headers?
print_fit_parameters : Boolean
Specify whether or not to print out FIT results for each chip.
print_git_info : Boolean
Display git repository information?
output : Boolean
Should utils.astrometric_utils.create_astrometric_catalog() generate file 'ref_cat.ecsv' and should
generate_source_catalogs() generate the .reg region files for every chip of every input image and should
generate_astrometric_catalog() generate file 'refcatalog.cat'?
Updates
-------
filteredTable: Astropy Table
Table which contains processing information and alignment results for every raw image evaluated | [
"Main",
"calling",
"function",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L175-L216 | train | 35,498 |
spacetelescope/drizzlepac | drizzlepac/alignimages.py | generate_astrometric_catalog | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table : object
Astropy Table object of the catalog
"""
# generate catalog
temp_pars = pars.copy()
if pars['output'] == True:
pars['output'] = 'ref_cat.ecsv'
else:
pars['output'] = None
out_catalog = amutils.create_astrometric_catalog(imglist,**pars)
pars = temp_pars.copy()
#if the catalog has contents, write the catalog to ascii text file
if len(out_catalog) > 0 and pars['output']:
catalog_filename = "refcatalog.cat"
out_catalog.write(catalog_filename, format="ascii.fast_commented_header")
log.info("Wrote reference catalog {}.".format(catalog_filename))
return(out_catalog) | python | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table : object
Astropy Table object of the catalog
"""
# generate catalog
temp_pars = pars.copy()
if pars['output'] == True:
pars['output'] = 'ref_cat.ecsv'
else:
pars['output'] = None
out_catalog = amutils.create_astrometric_catalog(imglist,**pars)
pars = temp_pars.copy()
#if the catalog has contents, write the catalog to ascii text file
if len(out_catalog) > 0 and pars['output']:
catalog_filename = "refcatalog.cat"
out_catalog.write(catalog_filename, format="ascii.fast_commented_header")
log.info("Wrote reference catalog {}.".format(catalog_filename))
return(out_catalog) | [
"def",
"generate_astrometric_catalog",
"(",
"imglist",
",",
"*",
"*",
"pars",
")",
":",
"# generate catalog",
"temp_pars",
"=",
"pars",
".",
"copy",
"(",
")",
"if",
"pars",
"[",
"'output'",
"]",
"==",
"True",
":",
"pars",
"[",
"'output'",
"]",
"=",
"'ref... | Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table : object
Astropy Table object of the catalog | [
"Generates",
"a",
"catalog",
"of",
"all",
"sources",
"from",
"an",
"existing",
"astrometric",
"catalog",
"are",
"in",
"or",
"near",
"the",
"FOVs",
"of",
"the",
"images",
"in",
"the",
"input",
"list",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L868-L897 | train | 35,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.