id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
235,000 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | server_group_list | def server_group_list(request):
"""Utility method to retrieve a list of server groups."""
try:
return api.nova.server_group_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve Nova server groups.'))
return [] | python | def server_group_list(request):
try:
return api.nova.server_group_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve Nova server groups.'))
return [] | [
"def",
"server_group_list",
"(",
"request",
")",
":",
"try",
":",
"return",
"api",
".",
"nova",
".",
"server_group_list",
"(",
"request",
")",
"except",
"Exception",
":",
"exceptions",
".",
"handle",
"(",
"request",
",",
"_",
"(",
"'Unable to retrieve Nova ser... | Utility method to retrieve a list of server groups. | [
"Utility",
"method",
"to",
"retrieve",
"a",
"list",
"of",
"server",
"groups",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L83-L90 |
235,001 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | network_field_data | def network_field_data(request, include_empty_option=False, with_cidr=False,
for_launch=False):
"""Returns a list of tuples of all networks.
Generates a list of networks available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:param with_cidr: flag to include subnets cidr in field name
:return: list of (id, name) tuples
"""
tenant_id = request.user.tenant_id
networks = []
if api.base.is_service_enabled(request, 'network'):
extra_params = {}
if for_launch:
extra_params['include_pre_auto_allocate'] = True
try:
networks = api.neutron.network_list_for_tenant(
request, tenant_id, **extra_params)
except Exception as e:
msg = _('Failed to get network list {0}').format(six.text_type(e))
exceptions.handle(request, msg)
_networks = []
for n in networks:
if not n['subnets']:
continue
v = n.name_or_id
if with_cidr:
cidrs = ([subnet.cidr for subnet in n['subnets']
if subnet.ip_version == 4] +
[subnet.cidr for subnet in n['subnets']
if subnet.ip_version == 6])
v += ' (%s)' % ', '.join(cidrs)
_networks.append((n.id, v))
networks = sorted(_networks, key=itemgetter(1))
if not networks:
if include_empty_option:
return [("", _("No networks available")), ]
return []
if include_empty_option:
return [("", _("Select Network")), ] + networks
return networks | python | def network_field_data(request, include_empty_option=False, with_cidr=False,
for_launch=False):
tenant_id = request.user.tenant_id
networks = []
if api.base.is_service_enabled(request, 'network'):
extra_params = {}
if for_launch:
extra_params['include_pre_auto_allocate'] = True
try:
networks = api.neutron.network_list_for_tenant(
request, tenant_id, **extra_params)
except Exception as e:
msg = _('Failed to get network list {0}').format(six.text_type(e))
exceptions.handle(request, msg)
_networks = []
for n in networks:
if not n['subnets']:
continue
v = n.name_or_id
if with_cidr:
cidrs = ([subnet.cidr for subnet in n['subnets']
if subnet.ip_version == 4] +
[subnet.cidr for subnet in n['subnets']
if subnet.ip_version == 6])
v += ' (%s)' % ', '.join(cidrs)
_networks.append((n.id, v))
networks = sorted(_networks, key=itemgetter(1))
if not networks:
if include_empty_option:
return [("", _("No networks available")), ]
return []
if include_empty_option:
return [("", _("Select Network")), ] + networks
return networks | [
"def",
"network_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
",",
"with_cidr",
"=",
"False",
",",
"for_launch",
"=",
"False",
")",
":",
"tenant_id",
"=",
"request",
".",
"user",
".",
"tenant_id",
"networks",
"=",
"[",
"]",
"if",
... | Returns a list of tuples of all networks.
Generates a list of networks available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:param with_cidr: flag to include subnets cidr in field name
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"networks",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L93-L140 |
235,002 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | keypair_field_data | def keypair_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all keypairs.
Generates a list of keypairs available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""
keypair_list = []
try:
keypairs = api.nova.keypair_list(request)
keypair_list = [(kp.name, kp.name) for kp in keypairs]
except Exception:
exceptions.handle(request, _('Unable to retrieve key pairs.'))
if not keypair_list:
if include_empty_option:
return [("", _("No key pairs available")), ]
return []
if include_empty_option:
return [("", _("Select a key pair")), ] + keypair_list
return keypair_list | python | def keypair_field_data(request, include_empty_option=False):
keypair_list = []
try:
keypairs = api.nova.keypair_list(request)
keypair_list = [(kp.name, kp.name) for kp in keypairs]
except Exception:
exceptions.handle(request, _('Unable to retrieve key pairs.'))
if not keypair_list:
if include_empty_option:
return [("", _("No key pairs available")), ]
return []
if include_empty_option:
return [("", _("Select a key pair")), ] + keypair_list
return keypair_list | [
"def",
"keypair_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
")",
":",
"keypair_list",
"=",
"[",
"]",
"try",
":",
"keypairs",
"=",
"api",
".",
"nova",
".",
"keypair_list",
"(",
"request",
")",
"keypair_list",
"=",
"[",
"(",
"kp",... | Returns a list of tuples of all keypairs.
Generates a list of keypairs available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"keypairs",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L143-L168 |
235,003 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | flavor_field_data | def flavor_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all image flavors.
Generates a list of image flavors available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""
flavors = flavor_list(request)
if flavors:
flavors_list = sort_flavor_list(request, flavors)
if include_empty_option:
return [("", _("Select Flavor")), ] + flavors_list
return flavors_list
if include_empty_option:
return [("", _("No flavors available")), ]
return [] | python | def flavor_field_data(request, include_empty_option=False):
flavors = flavor_list(request)
if flavors:
flavors_list = sort_flavor_list(request, flavors)
if include_empty_option:
return [("", _("Select Flavor")), ] + flavors_list
return flavors_list
if include_empty_option:
return [("", _("No flavors available")), ]
return [] | [
"def",
"flavor_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
")",
":",
"flavors",
"=",
"flavor_list",
"(",
"request",
")",
"if",
"flavors",
":",
"flavors_list",
"=",
"sort_flavor_list",
"(",
"request",
",",
"flavors",
")",
"if",
"incl... | Returns a list of tuples of all image flavors.
Generates a list of image flavors available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"image",
"flavors",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L171-L191 |
235,004 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | port_field_data | def port_field_data(request, with_network=False):
"""Returns a list of tuples of all ports available for the tenant.
Generates a list of ports that have no device_owner based on the networks
available to the tenant doing the request.
:param request: django http request object
:param with_network: include network name in field name
:return: list of (id, name) tuples
"""
def add_more_info_port_name(port, network):
# add more info to the port for the display
port_name = "{} ({})".format(
port.name_or_id, ",".join(
[ip['ip_address'] for ip in port['fixed_ips']]))
if with_network and network:
port_name += " - {}".format(network.name_or_id)
return port_name
ports = []
if api.base.is_service_enabled(request, 'network'):
network_list = api.neutron.network_list_for_tenant(
request, request.user.tenant_id)
for network in network_list:
ports.extend(
[(port.id, add_more_info_port_name(port, network))
for port in api.neutron.port_list_with_trunk_types(
request, network_id=network.id,
tenant_id=request.user.tenant_id)
if (not port.device_owner and
not isinstance(port, api.neutron.PortTrunkSubport))])
ports.sort(key=lambda obj: obj[1])
return ports | python | def port_field_data(request, with_network=False):
def add_more_info_port_name(port, network):
# add more info to the port for the display
port_name = "{} ({})".format(
port.name_or_id, ",".join(
[ip['ip_address'] for ip in port['fixed_ips']]))
if with_network and network:
port_name += " - {}".format(network.name_or_id)
return port_name
ports = []
if api.base.is_service_enabled(request, 'network'):
network_list = api.neutron.network_list_for_tenant(
request, request.user.tenant_id)
for network in network_list:
ports.extend(
[(port.id, add_more_info_port_name(port, network))
for port in api.neutron.port_list_with_trunk_types(
request, network_id=network.id,
tenant_id=request.user.tenant_id)
if (not port.device_owner and
not isinstance(port, api.neutron.PortTrunkSubport))])
ports.sort(key=lambda obj: obj[1])
return ports | [
"def",
"port_field_data",
"(",
"request",
",",
"with_network",
"=",
"False",
")",
":",
"def",
"add_more_info_port_name",
"(",
"port",
",",
"network",
")",
":",
"# add more info to the port for the display",
"port_name",
"=",
"\"{} ({})\"",
".",
"format",
"(",
"port"... | Returns a list of tuples of all ports available for the tenant.
Generates a list of ports that have no device_owner based on the networks
available to the tenant doing the request.
:param request: django http request object
:param with_network: include network name in field name
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"ports",
"available",
"for",
"the",
"tenant",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L194-L227 |
235,005 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | server_group_field_data | def server_group_field_data(request):
"""Returns a list of tuples of all server groups.
Generates a list of server groups available. And returns a list of
(id, name) tuples.
:param request: django http request object
:return: list of (id, name) tuples
"""
server_groups = server_group_list(request)
if server_groups:
server_groups_list = [(sg.id, sg.name) for sg in server_groups]
server_groups_list.sort(key=lambda obj: obj[1])
return [("", _("Select Server Group")), ] + server_groups_list
return [("", _("No server groups available")), ] | python | def server_group_field_data(request):
server_groups = server_group_list(request)
if server_groups:
server_groups_list = [(sg.id, sg.name) for sg in server_groups]
server_groups_list.sort(key=lambda obj: obj[1])
return [("", _("Select Server Group")), ] + server_groups_list
return [("", _("No server groups available")), ] | [
"def",
"server_group_field_data",
"(",
"request",
")",
":",
"server_groups",
"=",
"server_group_list",
"(",
"request",
")",
"if",
"server_groups",
":",
"server_groups_list",
"=",
"[",
"(",
"sg",
".",
"id",
",",
"sg",
".",
"name",
")",
"for",
"sg",
"in",
"s... | Returns a list of tuples of all server groups.
Generates a list of server groups available. And returns a list of
(id, name) tuples.
:param request: django http request object
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"server",
"groups",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L230-L245 |
235,006 | openstack/horizon | openstack_dashboard/dashboards/project/routers/extensions/extraroutes/tables.py | ExtraRoutesTable.get_object_display | def get_object_display(self, datum):
"""Display ExtraRoutes when deleted."""
return (super(ExtraRoutesTable, self).get_object_display(datum) or
datum.destination + " -> " + datum.nexthop) | python | def get_object_display(self, datum):
return (super(ExtraRoutesTable, self).get_object_display(datum) or
datum.destination + " -> " + datum.nexthop) | [
"def",
"get_object_display",
"(",
"self",
",",
"datum",
")",
":",
"return",
"(",
"super",
"(",
"ExtraRoutesTable",
",",
"self",
")",
".",
"get_object_display",
"(",
"datum",
")",
"or",
"datum",
".",
"destination",
"+",
"\" -> \"",
"+",
"datum",
".",
"nexth... | Display ExtraRoutes when deleted. | [
"Display",
"ExtraRoutes",
"when",
"deleted",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/routers/extensions/extraroutes/tables.py#L68-L71 |
235,007 | openstack/horizon | openstack_dashboard/api/rest/json_encoder.py | NaNJSONEncoder.iterencode | def iterencode(self, o, _one_shot=False):
"""JSON encoder with NaN and float inf support.
The sole purpose of defining a custom JSONEncoder class is to
override floatstr() inner function, or more specifically the
representation of NaN and +/-float('inf') values in a JSON. Although
Infinity values are not supported by JSON standard, we still can
convince Javascript JSON.parse() to create a Javascript Infinity
object if we feed a token `1e+999` to it.
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encoder.encode_basestring_ascii
else:
_encoder = encoder.encode_basestring
# On Python 3, JSONEncoder has no more encoding attribute, it produces
# an Unicode string
if six.PY2 and self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=float.__repr__,
_inf=encoder.INFINITY, _neginf=-encoder.INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.
# NOTE: In Python, NaN == NaN returns False and it can be used
# to detect NaN.
# pylint: disable=comparison-with-itself
if o != o:
text = self.nan_str
elif o == _inf:
text = self.inf_str
elif o == _neginf:
text = '-' + self.inf_str
else:
return _repr(o)
if not allow_nan:
raise ValueError(
_("Out of range float values are not JSON compliant: %r") %
o)
return text
_iterencode = json.encoder._make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0) | python | def iterencode(self, o, _one_shot=False):
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encoder.encode_basestring_ascii
else:
_encoder = encoder.encode_basestring
# On Python 3, JSONEncoder has no more encoding attribute, it produces
# an Unicode string
if six.PY2 and self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=float.__repr__,
_inf=encoder.INFINITY, _neginf=-encoder.INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.
# NOTE: In Python, NaN == NaN returns False and it can be used
# to detect NaN.
# pylint: disable=comparison-with-itself
if o != o:
text = self.nan_str
elif o == _inf:
text = self.inf_str
elif o == _neginf:
text = '-' + self.inf_str
else:
return _repr(o)
if not allow_nan:
raise ValueError(
_("Out of range float values are not JSON compliant: %r") %
o)
return text
_iterencode = json.encoder._make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0) | [
"def",
"iterencode",
"(",
"self",
",",
"o",
",",
"_one_shot",
"=",
"False",
")",
":",
"if",
"self",
".",
"check_circular",
":",
"markers",
"=",
"{",
"}",
"else",
":",
"markers",
"=",
"None",
"if",
"self",
".",
"ensure_ascii",
":",
"_encoder",
"=",
"e... | JSON encoder with NaN and float inf support.
The sole purpose of defining a custom JSONEncoder class is to
override floatstr() inner function, or more specifically the
representation of NaN and +/-float('inf') values in a JSON. Although
Infinity values are not supported by JSON standard, we still can
convince Javascript JSON.parse() to create a Javascript Infinity
object if we feed a token `1e+999` to it. | [
"JSON",
"encoder",
"with",
"NaN",
"and",
"float",
"inf",
"support",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/json_encoder.py#L27-L84 |
235,008 | openstack/horizon | openstack_dashboard/templatetags/context_selection.py | get_project_name | def get_project_name(project_id, projects):
"""Retrieves project name for given project id
Args:
projects: List of projects
project_id: project id
Returns: Project name or None if there is no match
"""
for project in projects:
if project_id == project.id:
return project.name | python | def get_project_name(project_id, projects):
for project in projects:
if project_id == project.id:
return project.name | [
"def",
"get_project_name",
"(",
"project_id",
",",
"projects",
")",
":",
"for",
"project",
"in",
"projects",
":",
"if",
"project_id",
"==",
"project",
".",
"id",
":",
"return",
"project",
".",
"name"
] | Retrieves project name for given project id
Args:
projects: List of projects
project_id: project id
Returns: Project name or None if there is no match | [
"Retrieves",
"project",
"name",
"for",
"given",
"project",
"id"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/templatetags/context_selection.py#L120-L131 |
235,009 | openstack/horizon | horizon/templatetags/parse_date.py | ParseDateNode.render | def render(self, datestring):
"""Parses a date-like string into a timezone aware Python datetime."""
formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
if datestring:
for format in formats:
try:
parsed = datetime.strptime(datestring, format)
if not timezone.is_aware(parsed):
parsed = timezone.make_aware(parsed, timezone.utc)
return parsed
except Exception:
pass
return None | python | def render(self, datestring):
formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
if datestring:
for format in formats:
try:
parsed = datetime.strptime(datestring, format)
if not timezone.is_aware(parsed):
parsed = timezone.make_aware(parsed, timezone.utc)
return parsed
except Exception:
pass
return None | [
"def",
"render",
"(",
"self",
",",
"datestring",
")",
":",
"formats",
"=",
"[",
"\"%Y-%m-%dT%H:%M:%S.%f\"",
",",
"\"%Y-%m-%d %H:%M:%S.%f\"",
",",
"\"%Y-%m-%dT%H:%M:%S\"",
",",
"\"%Y-%m-%d %H:%M:%S\"",
"]",
"if",
"datestring",
":",
"for",
"format",
"in",
"formats",
... | Parses a date-like string into a timezone aware Python datetime. | [
"Parses",
"a",
"date",
"-",
"like",
"string",
"into",
"a",
"timezone",
"aware",
"Python",
"datetime",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/parse_date.py#L33-L46 |
235,010 | openstack/horizon | horizon/utils/memoized.py | _try_weakref | def _try_weakref(arg, remove_callback):
"""Return a weak reference to arg if possible, or arg itself if not."""
try:
arg = weakref.ref(arg, remove_callback)
except TypeError:
# Not all types can have a weakref. That includes strings
# and floats and such, so just pass them through directly.
pass
return arg | python | def _try_weakref(arg, remove_callback):
try:
arg = weakref.ref(arg, remove_callback)
except TypeError:
# Not all types can have a weakref. That includes strings
# and floats and such, so just pass them through directly.
pass
return arg | [
"def",
"_try_weakref",
"(",
"arg",
",",
"remove_callback",
")",
":",
"try",
":",
"arg",
"=",
"weakref",
".",
"ref",
"(",
"arg",
",",
"remove_callback",
")",
"except",
"TypeError",
":",
"# Not all types can have a weakref. That includes strings",
"# and floats and such... | Return a weak reference to arg if possible, or arg itself if not. | [
"Return",
"a",
"weak",
"reference",
"to",
"arg",
"if",
"possible",
"or",
"arg",
"itself",
"if",
"not",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L28-L36 |
235,011 | openstack/horizon | horizon/utils/memoized.py | _get_key | def _get_key(args, kwargs, remove_callback):
"""Calculate the cache key, using weak references where possible."""
# Use tuples, because lists are not hashable.
weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args)
# Use a tuple of (key, values) pairs, because dict is not hashable.
# Sort it, so that we don't depend on the order of keys.
weak_kwargs = tuple(sorted(
(key, _try_weakref(value, remove_callback))
for (key, value) in kwargs.items()))
return weak_args, weak_kwargs | python | def _get_key(args, kwargs, remove_callback):
# Use tuples, because lists are not hashable.
weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args)
# Use a tuple of (key, values) pairs, because dict is not hashable.
# Sort it, so that we don't depend on the order of keys.
weak_kwargs = tuple(sorted(
(key, _try_weakref(value, remove_callback))
for (key, value) in kwargs.items()))
return weak_args, weak_kwargs | [
"def",
"_get_key",
"(",
"args",
",",
"kwargs",
",",
"remove_callback",
")",
":",
"# Use tuples, because lists are not hashable.",
"weak_args",
"=",
"tuple",
"(",
"_try_weakref",
"(",
"arg",
",",
"remove_callback",
")",
"for",
"arg",
"in",
"args",
")",
"# Use a tup... | Calculate the cache key, using weak references where possible. | [
"Calculate",
"the",
"cache",
"key",
"using",
"weak",
"references",
"where",
"possible",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L39-L48 |
235,012 | openstack/horizon | horizon/utils/memoized.py | memoized | def memoized(func=None, max_size=None):
"""Decorator that caches function calls.
Caches the decorated function's return value the first time it is called
with the given arguments. If called later with the same arguments, the
cached value is returned instead of calling the decorated function again.
It operates as a LRU cache and keeps up to the max_size value of cached
items, always clearing oldest items first.
The cache uses weak references to the passed arguments, so it doesn't keep
them alive in memory forever.
"""
def decorate(func):
# The dictionary in which all the data will be cached. This is a
# separate instance for every decorated function, and it's stored in a
# closure of the wrapped function.
cache = collections.OrderedDict()
locks = collections.defaultdict(threading.Lock)
if max_size:
max_cache_size = max_size
else:
max_cache_size = getattr(settings, 'MEMOIZED_MAX_SIZE_DEFAULT', 25)
@functools.wraps(func)
def wrapped(*args, **kwargs):
# We need to have defined key early, to be able to use it in the
# remove() function, but we calculate the actual value of the key
# later on, because we need the remove() function for that.
key = None
def remove(ref):
"""A callback to remove outdated items from cache."""
try:
# The key here is from closure, and is calculated later.
del cache[key]
del locks[key]
except KeyError:
# Some other weak reference might have already removed that
# key -- in that case we don't need to do anything.
pass
key = _get_key(args, kwargs, remove)
try:
with locks[key]:
try:
# We want cache hit to be as fast as possible, and
# don't really care much about the speed of a cache
# miss, because it will only happen once and likely
# calls some external API, database, or some other slow
# thing. That's why the hit is in straightforward code,
# and the miss is in an exception.
# We also want to pop the key and reset it to make sure
# the position it has in the order updates.
value = cache[key] = cache.pop(key)
except KeyError:
value = cache[key] = func(*args, **kwargs)
except TypeError:
# The calculated key may be unhashable when an unhashable
# object, such as a list, is passed as one of the arguments. In
# that case, we can't cache anything and simply always call the
# decorated function.
warnings.warn(
"The key of %s %s is not hashable and cannot be memoized: "
"%r\n" % (func.__module__, func.__name__, key),
UnhashableKeyWarning, 2)
value = func(*args, **kwargs)
while len(cache) > max_cache_size:
try:
popped_tuple = cache.popitem(last=False)
locks.pop(popped_tuple[0], None)
except KeyError:
pass
return value
return wrapped
if func and callable(func):
return decorate(func)
return decorate | python | def memoized(func=None, max_size=None):
def decorate(func):
# The dictionary in which all the data will be cached. This is a
# separate instance for every decorated function, and it's stored in a
# closure of the wrapped function.
cache = collections.OrderedDict()
locks = collections.defaultdict(threading.Lock)
if max_size:
max_cache_size = max_size
else:
max_cache_size = getattr(settings, 'MEMOIZED_MAX_SIZE_DEFAULT', 25)
@functools.wraps(func)
def wrapped(*args, **kwargs):
# We need to have defined key early, to be able to use it in the
# remove() function, but we calculate the actual value of the key
# later on, because we need the remove() function for that.
key = None
def remove(ref):
"""A callback to remove outdated items from cache."""
try:
# The key here is from closure, and is calculated later.
del cache[key]
del locks[key]
except KeyError:
# Some other weak reference might have already removed that
# key -- in that case we don't need to do anything.
pass
key = _get_key(args, kwargs, remove)
try:
with locks[key]:
try:
# We want cache hit to be as fast as possible, and
# don't really care much about the speed of a cache
# miss, because it will only happen once and likely
# calls some external API, database, or some other slow
# thing. That's why the hit is in straightforward code,
# and the miss is in an exception.
# We also want to pop the key and reset it to make sure
# the position it has in the order updates.
value = cache[key] = cache.pop(key)
except KeyError:
value = cache[key] = func(*args, **kwargs)
except TypeError:
# The calculated key may be unhashable when an unhashable
# object, such as a list, is passed as one of the arguments. In
# that case, we can't cache anything and simply always call the
# decorated function.
warnings.warn(
"The key of %s %s is not hashable and cannot be memoized: "
"%r\n" % (func.__module__, func.__name__, key),
UnhashableKeyWarning, 2)
value = func(*args, **kwargs)
while len(cache) > max_cache_size:
try:
popped_tuple = cache.popitem(last=False)
locks.pop(popped_tuple[0], None)
except KeyError:
pass
return value
return wrapped
if func and callable(func):
return decorate(func)
return decorate | [
"def",
"memoized",
"(",
"func",
"=",
"None",
",",
"max_size",
"=",
"None",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"# The dictionary in which all the data will be cached. This is a",
"# separate instance for every decorated function, and it's stored in a",
"# clos... | Decorator that caches function calls.
Caches the decorated function's return value the first time it is called
with the given arguments. If called later with the same arguments, the
cached value is returned instead of calling the decorated function again.
It operates as a LRU cache and keeps up to the max_size value of cached
items, always clearing oldest items first.
The cache uses weak references to the passed arguments, so it doesn't keep
them alive in memory forever. | [
"Decorator",
"that",
"caches",
"function",
"calls",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L51-L132 |
235,013 | openstack/horizon | openstack_dashboard/management/commands/make_web_conf.py | _getattr | def _getattr(obj, name, default):
"""Like getattr but return `default` if None or False.
By default, getattr(obj, name, default) returns default only if
attr does not exist, here, we return `default` even if attr evaluates to
None or False.
"""
value = getattr(obj, name, default)
if value:
return value
else:
return default | python | def _getattr(obj, name, default):
value = getattr(obj, name, default)
if value:
return value
else:
return default | [
"def",
"_getattr",
"(",
"obj",
",",
"name",
",",
"default",
")",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"name",
",",
"default",
")",
"if",
"value",
":",
"return",
"value",
"else",
":",
"return",
"default"
] | Like getattr but return `default` if None or False.
By default, getattr(obj, name, default) returns default only if
attr does not exist, here, we return `default` even if attr evaluates to
None or False. | [
"Like",
"getattr",
"but",
"return",
"default",
"if",
"None",
"or",
"False",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/make_web_conf.py#L56-L67 |
235,014 | openstack/horizon | openstack_dashboard/api/neutron.py | list_resources_with_long_filters | def list_resources_with_long_filters(list_method,
filter_attr, filter_values, **params):
"""List neutron resources with handling RequestURITooLong exception.
If filter parameters are long, list resources API request leads to
414 error (URL is too long). For such case, this method split
list parameters specified by a list_field argument into chunks
and call the specified list_method repeatedly.
:param list_method: Method used to retrieve resource list.
:param filter_attr: attribute name to be filtered. The value corresponding
to this attribute is specified by "filter_values".
If you want to specify more attributes for a filter condition,
pass them as keyword arguments like "attr2=values2".
:param filter_values: values of "filter_attr" to be filtered.
If filter_values are too long and the total URI length exceed the
maximum length supported by the neutron server, filter_values will
be split into sub lists if filter_values is a list.
:param params: parameters to pass a specified listing API call
without any changes. You can specify more filter conditions
in addition to a pair of filter_attr and filter_values.
"""
try:
params[filter_attr] = filter_values
return list_method(**params)
except neutron_exc.RequestURITooLong as uri_len_exc:
# The URI is too long because of too many filter values.
# Use the excess attribute of the exception to know how many
# filter values can be inserted into a single request.
# We consider only the filter condition from (filter_attr,
# filter_values) and do not consider other filter conditions
# which may be specified in **params.
if not isinstance(filter_values, (list, tuple, set, frozenset)):
filter_values = [filter_values]
# Length of each query filter is:
# <key>=<value>& (e.g., id=<uuid>)
# The length will be key_len + value_maxlen + 2
all_filter_len = sum(len(filter_attr) + len(val) + 2
for val in filter_values)
allowed_filter_len = all_filter_len - uri_len_exc.excess
val_maxlen = max(len(val) for val in filter_values)
filter_maxlen = len(filter_attr) + val_maxlen + 2
chunk_size = allowed_filter_len // filter_maxlen
resources = []
for i in range(0, len(filter_values), chunk_size):
params[filter_attr] = filter_values[i:i + chunk_size]
resources.extend(list_method(**params))
return resources | python | def list_resources_with_long_filters(list_method,
filter_attr, filter_values, **params):
try:
params[filter_attr] = filter_values
return list_method(**params)
except neutron_exc.RequestURITooLong as uri_len_exc:
# The URI is too long because of too many filter values.
# Use the excess attribute of the exception to know how many
# filter values can be inserted into a single request.
# We consider only the filter condition from (filter_attr,
# filter_values) and do not consider other filter conditions
# which may be specified in **params.
if not isinstance(filter_values, (list, tuple, set, frozenset)):
filter_values = [filter_values]
# Length of each query filter is:
# <key>=<value>& (e.g., id=<uuid>)
# The length will be key_len + value_maxlen + 2
all_filter_len = sum(len(filter_attr) + len(val) + 2
for val in filter_values)
allowed_filter_len = all_filter_len - uri_len_exc.excess
val_maxlen = max(len(val) for val in filter_values)
filter_maxlen = len(filter_attr) + val_maxlen + 2
chunk_size = allowed_filter_len // filter_maxlen
resources = []
for i in range(0, len(filter_values), chunk_size):
params[filter_attr] = filter_values[i:i + chunk_size]
resources.extend(list_method(**params))
return resources | [
"def",
"list_resources_with_long_filters",
"(",
"list_method",
",",
"filter_attr",
",",
"filter_values",
",",
"*",
"*",
"params",
")",
":",
"try",
":",
"params",
"[",
"filter_attr",
"]",
"=",
"filter_values",
"return",
"list_method",
"(",
"*",
"*",
"params",
"... | List neutron resources with handling RequestURITooLong exception.
If filter parameters are long, list resources API request leads to
414 error (URL is too long). For such case, this method split
list parameters specified by a list_field argument into chunks
and call the specified list_method repeatedly.
:param list_method: Method used to retrieve resource list.
:param filter_attr: attribute name to be filtered. The value corresponding
to this attribute is specified by "filter_values".
If you want to specify more attributes for a filter condition,
pass them as keyword arguments like "attr2=values2".
:param filter_values: values of "filter_attr" to be filtered.
If filter_values are too long and the total URI length exceed the
maximum length supported by the neutron server, filter_values will
be split into sub lists if filter_values is a list.
:param params: parameters to pass a specified listing API call
without any changes. You can specify more filter conditions
in addition to a pair of filter_attr and filter_values. | [
"List",
"neutron",
"resources",
"with",
"handling",
"RequestURITooLong",
"exception",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L821-L872 |
235,015 | openstack/horizon | openstack_dashboard/api/neutron.py | network_list_for_tenant | def network_list_for_tenant(request, tenant_id, include_external=False,
include_pre_auto_allocate=False,
**params):
"""Return a network list available for the tenant.
The list contains networks owned by the tenant and public networks.
If requested_networks specified, it searches requested_networks only.
"""
LOG.debug("network_list_for_tenant(): tenant_id=%(tenant_id)s, "
"params=%(params)s", {'tenant_id': tenant_id, 'params': params})
networks = []
shared = params.get('shared')
if shared is not None:
del params['shared']
if shared in (None, False):
# If a user has admin role, network list returned by Neutron API
# contains networks that do not belong to that tenant.
# So we need to specify tenant_id when calling network_list().
networks += network_list(request, tenant_id=tenant_id,
shared=False, **params)
if shared in (None, True):
# In the current Neutron API, there is no way to retrieve
# both owner networks and public networks in a single API call.
networks += network_list(request, shared=True, **params)
# Hack for auto allocated network
if include_pre_auto_allocate and not networks:
if _is_auto_allocated_network_supported(request):
networks.append(PreAutoAllocateNetwork(request))
params['router:external'] = params.get('router:external', True)
if params['router:external'] and include_external:
if shared is not None:
params['shared'] = shared
fetched_net_ids = [n.id for n in networks]
# Retrieves external networks when router:external is not specified
# in (filtering) params or router:external=True filter is specified.
# When router:external=False is specified there is no need to query
# networking API because apparently nothing will match the filter.
ext_nets = network_list(request, **params)
networks += [n for n in ext_nets if
n.id not in fetched_net_ids]
return networks | python | def network_list_for_tenant(request, tenant_id, include_external=False,
include_pre_auto_allocate=False,
**params):
LOG.debug("network_list_for_tenant(): tenant_id=%(tenant_id)s, "
"params=%(params)s", {'tenant_id': tenant_id, 'params': params})
networks = []
shared = params.get('shared')
if shared is not None:
del params['shared']
if shared in (None, False):
# If a user has admin role, network list returned by Neutron API
# contains networks that do not belong to that tenant.
# So we need to specify tenant_id when calling network_list().
networks += network_list(request, tenant_id=tenant_id,
shared=False, **params)
if shared in (None, True):
# In the current Neutron API, there is no way to retrieve
# both owner networks and public networks in a single API call.
networks += network_list(request, shared=True, **params)
# Hack for auto allocated network
if include_pre_auto_allocate and not networks:
if _is_auto_allocated_network_supported(request):
networks.append(PreAutoAllocateNetwork(request))
params['router:external'] = params.get('router:external', True)
if params['router:external'] and include_external:
if shared is not None:
params['shared'] = shared
fetched_net_ids = [n.id for n in networks]
# Retrieves external networks when router:external is not specified
# in (filtering) params or router:external=True filter is specified.
# When router:external=False is specified there is no need to query
# networking API because apparently nothing will match the filter.
ext_nets = network_list(request, **params)
networks += [n for n in ext_nets if
n.id not in fetched_net_ids]
return networks | [
"def",
"network_list_for_tenant",
"(",
"request",
",",
"tenant_id",
",",
"include_external",
"=",
"False",
",",
"include_pre_auto_allocate",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"LOG",
".",
"debug",
"(",
"\"network_list_for_tenant(): tenant_id=%(tenant_id)... | Return a network list available for the tenant.
The list contains networks owned by the tenant and public networks.
If requested_networks specified, it searches requested_networks only. | [
"Return",
"a",
"network",
"list",
"available",
"for",
"the",
"tenant",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1052-L1098 |
235,016 | openstack/horizon | openstack_dashboard/api/neutron.py | network_create | def network_create(request, **kwargs):
"""Create a network object.
:param request: request context
:param tenant_id: (optional) tenant id of the network created
:param name: (optional) name of the network created
:returns: Network object
"""
LOG.debug("network_create(): kwargs = %s", kwargs)
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body = {'network': kwargs}
network = neutronclient(request).create_network(body=body).get('network')
return Network(network) | python | def network_create(request, **kwargs):
LOG.debug("network_create(): kwargs = %s", kwargs)
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body = {'network': kwargs}
network = neutronclient(request).create_network(body=body).get('network')
return Network(network) | [
"def",
"network_create",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"network_create(): kwargs = %s\"",
",",
"kwargs",
")",
"if",
"'tenant_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'tenant_id'",
"]",
"=",
"request",... | Create a network object.
:param request: request context
:param tenant_id: (optional) tenant id of the network created
:param name: (optional) name of the network created
:returns: Network object | [
"Create",
"a",
"network",
"object",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1129-L1142 |
235,017 | openstack/horizon | openstack_dashboard/api/neutron.py | subnet_create | def subnet_create(request, network_id, **kwargs):
"""Create a subnet on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param cidr: (optional) subnet IP address range
:param ip_version: (optional) IP version (4 or 6)
:param gateway_ip: (optional) IP address of gateway
:param tenant_id: (optional) tenant id of the subnet created
:param name: (optional) name of the subnet created
:param subnetpool_id: (optional) subnetpool to allocate prefix from
:param prefixlen: (optional) length of prefix to allocate
:returns: Subnet object
Although both cidr+ip_version and subnetpool_id+preifxlen is listed as
optional you MUST pass along one of the combinations to get a successful
result.
"""
LOG.debug("subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s",
{'network_id': network_id, 'kwargs': kwargs})
body = {'subnet': {'network_id': network_id}}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['subnet'].update(kwargs)
subnet = neutronclient(request).create_subnet(body=body).get('subnet')
return Subnet(subnet) | python | def subnet_create(request, network_id, **kwargs):
LOG.debug("subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s",
{'network_id': network_id, 'kwargs': kwargs})
body = {'subnet': {'network_id': network_id}}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['subnet'].update(kwargs)
subnet = neutronclient(request).create_subnet(body=body).get('subnet')
return Subnet(subnet) | [
"def",
"subnet_create",
"(",
"request",
",",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s\"",
",",
"{",
"'network_id'",
":",
"network_id",
",",
"'kwargs'",
":",
"kwargs",
"}"... | Create a subnet on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param cidr: (optional) subnet IP address range
:param ip_version: (optional) IP version (4 or 6)
:param gateway_ip: (optional) IP address of gateway
:param tenant_id: (optional) tenant id of the subnet created
:param name: (optional) name of the subnet created
:param subnetpool_id: (optional) subnetpool to allocate prefix from
:param prefixlen: (optional) length of prefix to allocate
:returns: Subnet object
Although both cidr+ip_version and subnetpool_id+preifxlen is listed as
optional you MUST pass along one of the combinations to get a successful
result. | [
"Create",
"a",
"subnet",
"on",
"a",
"specified",
"network",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1179-L1204 |
235,018 | openstack/horizon | openstack_dashboard/api/neutron.py | subnetpool_create | def subnetpool_create(request, name, prefixes, **kwargs):
"""Create a subnetpool.
ip_version is auto-detected in back-end.
Parameters:
request -- Request context
name -- Name for subnetpool
prefixes -- List of prefixes for pool
Keyword Arguments (optional):
min_prefixlen -- Minimum prefix length for allocations from pool
max_prefixlen -- Maximum prefix length for allocations from pool
default_prefixlen -- Default prefix length for allocations from pool
default_quota -- Default quota for allocations from pool
shared -- Subnetpool should be shared (Admin-only)
tenant_id -- Owner of subnetpool
Returns:
SubnetPool object
"""
LOG.debug("subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, "
"kwargs=%(kwargs)s", {'name': name, 'prefixes': prefixes,
'kwargs': kwargs})
body = {'subnetpool':
{'name': name,
'prefixes': prefixes,
}
}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['subnetpool'].update(kwargs)
subnetpool = \
neutronclient(request).create_subnetpool(body=body).get('subnetpool')
return SubnetPool(subnetpool) | python | def subnetpool_create(request, name, prefixes, **kwargs):
LOG.debug("subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, "
"kwargs=%(kwargs)s", {'name': name, 'prefixes': prefixes,
'kwargs': kwargs})
body = {'subnetpool':
{'name': name,
'prefixes': prefixes,
}
}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['subnetpool'].update(kwargs)
subnetpool = \
neutronclient(request).create_subnetpool(body=body).get('subnetpool')
return SubnetPool(subnetpool) | [
"def",
"subnetpool_create",
"(",
"request",
",",
"name",
",",
"prefixes",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, \"",
"\"kwargs=%(kwargs)s\"",
",",
"{",
"'name'",
":",
"name",
",",
... | Create a subnetpool.
ip_version is auto-detected in back-end.
Parameters:
request -- Request context
name -- Name for subnetpool
prefixes -- List of prefixes for pool
Keyword Arguments (optional):
min_prefixlen -- Minimum prefix length for allocations from pool
max_prefixlen -- Maximum prefix length for allocations from pool
default_prefixlen -- Default prefix length for allocations from pool
default_quota -- Default quota for allocations from pool
shared -- Subnetpool should be shared (Admin-only)
tenant_id -- Owner of subnetpool
Returns:
SubnetPool object | [
"Create",
"a",
"subnetpool",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1243-L1277 |
235,019 | openstack/horizon | openstack_dashboard/api/neutron.py | port_list_with_trunk_types | def port_list_with_trunk_types(request, **params):
"""List neutron Ports for this tenant with possible TrunkPort indicated
:param request: request context
NOTE Performing two API calls is not atomic, but this is not worse
than the original idea when we call port_list repeatedly for
each network to perform identification run-time. We should
handle the inconsistencies caused by non-atomic API requests
gracefully.
"""
LOG.debug("port_list_with_trunk_types(): params=%s", params)
# When trunk feature is disabled in neutron, we have no need to fetch
# trunk information and port_list() is enough.
if not is_extension_supported(request, 'trunk'):
return port_list(request, **params)
ports = neutronclient(request).list_ports(**params)['ports']
trunk_filters = {}
if 'tenant_id' in params:
trunk_filters['tenant_id'] = params['tenant_id']
trunks = neutronclient(request).list_trunks(**trunk_filters)['trunks']
parent_ports = set(t['port_id'] for t in trunks)
# Create a dict map for child ports (port ID to trunk info)
child_ports = dict((s['port_id'],
{'trunk_id': t['id'],
'segmentation_type': s['segmentation_type'],
'segmentation_id': s['segmentation_id']})
for t in trunks
for s in t['sub_ports'])
def _get_port_info(port):
if port['id'] in parent_ports:
return PortTrunkParent(port)
elif port['id'] in child_ports:
return PortTrunkSubport(port, child_ports[port['id']])
else:
return Port(port)
return [_get_port_info(p) for p in ports] | python | def port_list_with_trunk_types(request, **params):
LOG.debug("port_list_with_trunk_types(): params=%s", params)
# When trunk feature is disabled in neutron, we have no need to fetch
# trunk information and port_list() is enough.
if not is_extension_supported(request, 'trunk'):
return port_list(request, **params)
ports = neutronclient(request).list_ports(**params)['ports']
trunk_filters = {}
if 'tenant_id' in params:
trunk_filters['tenant_id'] = params['tenant_id']
trunks = neutronclient(request).list_trunks(**trunk_filters)['trunks']
parent_ports = set(t['port_id'] for t in trunks)
# Create a dict map for child ports (port ID to trunk info)
child_ports = dict((s['port_id'],
{'trunk_id': t['id'],
'segmentation_type': s['segmentation_type'],
'segmentation_id': s['segmentation_id']})
for t in trunks
for s in t['sub_ports'])
def _get_port_info(port):
if port['id'] in parent_ports:
return PortTrunkParent(port)
elif port['id'] in child_ports:
return PortTrunkSubport(port, child_ports[port['id']])
else:
return Port(port)
return [_get_port_info(p) for p in ports] | [
"def",
"port_list_with_trunk_types",
"(",
"request",
",",
"*",
"*",
"params",
")",
":",
"LOG",
".",
"debug",
"(",
"\"port_list_with_trunk_types(): params=%s\"",
",",
"params",
")",
"# When trunk feature is disabled in neutron, we have no need to fetch",
"# trunk information and... | List neutron Ports for this tenant with possible TrunkPort indicated
:param request: request context
NOTE Performing two API calls is not atomic, but this is not worse
than the original idea when we call port_list repeatedly for
each network to perform identification run-time. We should
handle the inconsistencies caused by non-atomic API requests
gracefully. | [
"List",
"neutron",
"Ports",
"for",
"this",
"tenant",
"with",
"possible",
"TrunkPort",
"indicated"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1308-L1348 |
235,020 | openstack/horizon | openstack_dashboard/api/neutron.py | port_create | def port_create(request, network_id, **kwargs):
"""Create a port on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param device_id: (optional) device id attached to the port
:param tenant_id: (optional) tenant id of the port created
:param name: (optional) name of the port created
:returns: Port object
"""
LOG.debug("port_create(): netid=%(network_id)s, kwargs=%(kwargs)s",
{'network_id': network_id, 'kwargs': kwargs})
kwargs = unescape_port_kwargs(**kwargs)
body = {'port': {'network_id': network_id}}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['port'].update(kwargs)
port = neutronclient(request).create_port(body=body).get('port')
return Port(port) | python | def port_create(request, network_id, **kwargs):
LOG.debug("port_create(): netid=%(network_id)s, kwargs=%(kwargs)s",
{'network_id': network_id, 'kwargs': kwargs})
kwargs = unescape_port_kwargs(**kwargs)
body = {'port': {'network_id': network_id}}
if 'tenant_id' not in kwargs:
kwargs['tenant_id'] = request.user.project_id
body['port'].update(kwargs)
port = neutronclient(request).create_port(body=body).get('port')
return Port(port) | [
"def",
"port_create",
"(",
"request",
",",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"port_create(): netid=%(network_id)s, kwargs=%(kwargs)s\"",
",",
"{",
"'network_id'",
":",
"network_id",
",",
"'kwargs'",
":",
"kwargs",
"}",
... | Create a port on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param device_id: (optional) device id attached to the port
:param tenant_id: (optional) tenant id of the port created
:param name: (optional) name of the port created
:returns: Port object | [
"Create",
"a",
"port",
"on",
"a",
"specified",
"network",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1367-L1385 |
235,021 | openstack/horizon | openstack_dashboard/api/neutron.py | list_extensions | def list_extensions(request):
"""List neutron extensions.
:param request: django request object
"""
neutron_api = neutronclient(request)
try:
extensions_list = neutron_api.list_extensions()
except exceptions.ServiceCatalogException:
return {}
if 'extensions' in extensions_list:
return tuple(extensions_list['extensions'])
else:
return () | python | def list_extensions(request):
neutron_api = neutronclient(request)
try:
extensions_list = neutron_api.list_extensions()
except exceptions.ServiceCatalogException:
return {}
if 'extensions' in extensions_list:
return tuple(extensions_list['extensions'])
else:
return () | [
"def",
"list_extensions",
"(",
"request",
")",
":",
"neutron_api",
"=",
"neutronclient",
"(",
"request",
")",
"try",
":",
"extensions_list",
"=",
"neutron_api",
".",
"list_extensions",
"(",
")",
"except",
"exceptions",
".",
"ServiceCatalogException",
":",
"return"... | List neutron extensions.
:param request: django request object | [
"List",
"neutron",
"extensions",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1795-L1808 |
235,022 | openstack/horizon | openstack_dashboard/api/neutron.py | is_extension_supported | def is_extension_supported(request, extension_alias):
"""Check if a specified extension is supported.
:param request: django request object
:param extension_alias: neutron extension alias
"""
extensions = list_extensions(request)
for extension in extensions:
if extension['alias'] == extension_alias:
return True
else:
return False | python | def is_extension_supported(request, extension_alias):
extensions = list_extensions(request)
for extension in extensions:
if extension['alias'] == extension_alias:
return True
else:
return False | [
"def",
"is_extension_supported",
"(",
"request",
",",
"extension_alias",
")",
":",
"extensions",
"=",
"list_extensions",
"(",
"request",
")",
"for",
"extension",
"in",
"extensions",
":",
"if",
"extension",
"[",
"'alias'",
"]",
"==",
"extension_alias",
":",
"retu... | Check if a specified extension is supported.
:param request: django request object
:param extension_alias: neutron extension alias | [
"Check",
"if",
"a",
"specified",
"extension",
"is",
"supported",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1812-L1823 |
235,023 | openstack/horizon | openstack_dashboard/api/neutron.py | get_feature_permission | def get_feature_permission(request, feature, operation=None):
"""Check if a feature-specific field can be displayed.
This method check a permission for a feature-specific field.
Such field is usually provided through Neutron extension.
:param request: Request Object
:param feature: feature name defined in FEATURE_MAP
:param operation (optional): Operation type. The valid value should be
defined in FEATURE_MAP[feature]['policies']
It must be specified if FEATURE_MAP[feature] has 'policies'.
"""
network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {})
feature_info = FEATURE_MAP.get(feature)
if not feature_info:
raise ValueError("The requested feature '%(feature)s' is unknown. "
"Please make sure to specify a feature defined "
"in FEATURE_MAP.")
# Check dashboard settings
feature_config = feature_info.get('config')
if feature_config:
if not network_config.get(feature_config['name'],
feature_config['default']):
return False
# Check policy
feature_policies = feature_info.get('policies')
if feature_policies:
policy_name = feature_policies.get(operation)
if not policy_name:
raise ValueError("The 'operation' parameter for "
"get_feature_permission '%(feature)s' "
"is invalid. It should be one of %(allowed)s"
% {'feature': feature,
'allowed': ' '.join(feature_policies.keys())})
role = (('network', policy_name),)
if not policy.check(role, request):
return False
# Check if a required extension is enabled
feature_extension = feature_info.get('extension')
if feature_extension:
try:
return is_extension_supported(request, feature_extension)
except Exception:
LOG.info("Failed to check Neutron '%s' extension is not supported",
feature_extension)
return False
# If all checks are passed, now a given feature is allowed.
return True | python | def get_feature_permission(request, feature, operation=None):
network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {})
feature_info = FEATURE_MAP.get(feature)
if not feature_info:
raise ValueError("The requested feature '%(feature)s' is unknown. "
"Please make sure to specify a feature defined "
"in FEATURE_MAP.")
# Check dashboard settings
feature_config = feature_info.get('config')
if feature_config:
if not network_config.get(feature_config['name'],
feature_config['default']):
return False
# Check policy
feature_policies = feature_info.get('policies')
if feature_policies:
policy_name = feature_policies.get(operation)
if not policy_name:
raise ValueError("The 'operation' parameter for "
"get_feature_permission '%(feature)s' "
"is invalid. It should be one of %(allowed)s"
% {'feature': feature,
'allowed': ' '.join(feature_policies.keys())})
role = (('network', policy_name),)
if not policy.check(role, request):
return False
# Check if a required extension is enabled
feature_extension = feature_info.get('extension')
if feature_extension:
try:
return is_extension_supported(request, feature_extension)
except Exception:
LOG.info("Failed to check Neutron '%s' extension is not supported",
feature_extension)
return False
# If all checks are passed, now a given feature is allowed.
return True | [
"def",
"get_feature_permission",
"(",
"request",
",",
"feature",
",",
"operation",
"=",
"None",
")",
":",
"network_config",
"=",
"getattr",
"(",
"settings",
",",
"'OPENSTACK_NEUTRON_NETWORK'",
",",
"{",
"}",
")",
"feature_info",
"=",
"FEATURE_MAP",
".",
"get",
... | Check if a feature-specific field can be displayed.
This method check a permission for a feature-specific field.
Such field is usually provided through Neutron extension.
:param request: Request Object
:param feature: feature name defined in FEATURE_MAP
:param operation (optional): Operation type. The valid value should be
defined in FEATURE_MAP[feature]['policies']
It must be specified if FEATURE_MAP[feature] has 'policies'. | [
"Check",
"if",
"a",
"feature",
"-",
"specific",
"field",
"can",
"be",
"displayed",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1889-L1940 |
235,024 | openstack/horizon | openstack_dashboard/api/neutron.py | policy_create | def policy_create(request, **kwargs):
"""Create a QoS Policy.
:param request: request context
:param name: name of the policy
:param description: description of policy
:param shared: boolean (true or false)
:return: QoSPolicy object
"""
body = {'policy': kwargs}
policy = neutronclient(request).create_qos_policy(body=body).get('policy')
return QoSPolicy(policy) | python | def policy_create(request, **kwargs):
body = {'policy': kwargs}
policy = neutronclient(request).create_qos_policy(body=body).get('policy')
return QoSPolicy(policy) | [
"def",
"policy_create",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"{",
"'policy'",
":",
"kwargs",
"}",
"policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"create_qos_policy",
"(",
"body",
"=",
"body",
")",
".",
"get",
"(",
... | Create a QoS Policy.
:param request: request context
:param name: name of the policy
:param description: description of policy
:param shared: boolean (true or false)
:return: QoSPolicy object | [
"Create",
"a",
"QoS",
"Policy",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1950-L1961 |
235,025 | openstack/horizon | openstack_dashboard/api/neutron.py | policy_list | def policy_list(request, **kwargs):
"""List of QoS Policies."""
policies = neutronclient(request).list_qos_policies(
**kwargs).get('policies')
return [QoSPolicy(p) for p in policies] | python | def policy_list(request, **kwargs):
policies = neutronclient(request).list_qos_policies(
**kwargs).get('policies')
return [QoSPolicy(p) for p in policies] | [
"def",
"policy_list",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"policies",
"=",
"neutronclient",
"(",
"request",
")",
".",
"list_qos_policies",
"(",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"'policies'",
")",
"return",
"[",
"QoSPolicy",
"(",
... | List of QoS Policies. | [
"List",
"of",
"QoS",
"Policies",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1964-L1968 |
235,026 | openstack/horizon | openstack_dashboard/api/neutron.py | policy_get | def policy_get(request, policy_id, **kwargs):
"""Get QoS policy for a given policy id."""
policy = neutronclient(request).show_qos_policy(
policy_id, **kwargs).get('policy')
return QoSPolicy(policy) | python | def policy_get(request, policy_id, **kwargs):
policy = neutronclient(request).show_qos_policy(
policy_id, **kwargs).get('policy')
return QoSPolicy(policy) | [
"def",
"policy_get",
"(",
"request",
",",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
":",
"policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"show_qos_policy",
"(",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"'policy'",
")",
"re... | Get QoS policy for a given policy id. | [
"Get",
"QoS",
"policy",
"for",
"a",
"given",
"policy",
"id",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1972-L1976 |
235,027 | openstack/horizon | openstack_dashboard/api/neutron.py | rbac_policy_create | def rbac_policy_create(request, **kwargs):
"""Create a RBAC Policy.
:param request: request context
:param target_tenant: target tenant of the policy
:param tenant_id: owner tenant of the policy(Not recommended)
:param object_type: network or qos_policy
:param object_id: object id of policy
:param action: access_as_shared or access_as_external
:return: RBACPolicy object
"""
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(request).create_rbac_policy(
body=body).get('rbac_policy')
return RBACPolicy(rbac_policy) | python | def rbac_policy_create(request, **kwargs):
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(request).create_rbac_policy(
body=body).get('rbac_policy')
return RBACPolicy(rbac_policy) | [
"def",
"rbac_policy_create",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"{",
"'rbac_policy'",
":",
"kwargs",
"}",
"rbac_policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"create_rbac_policy",
"(",
"body",
"=",
"body",
")",
".",
... | Create a RBAC Policy.
:param request: request context
:param target_tenant: target tenant of the policy
:param tenant_id: owner tenant of the policy(Not recommended)
:param object_type: network or qos_policy
:param object_id: object id of policy
:param action: access_as_shared or access_as_external
:return: RBACPolicy object | [
"Create",
"a",
"RBAC",
"Policy",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2001-L2015 |
235,028 | openstack/horizon | openstack_dashboard/api/neutron.py | rbac_policy_list | def rbac_policy_list(request, **kwargs):
"""List of RBAC Policies."""
policies = neutronclient(request).list_rbac_policies(
**kwargs).get('rbac_policies')
return [RBACPolicy(p) for p in policies] | python | def rbac_policy_list(request, **kwargs):
policies = neutronclient(request).list_rbac_policies(
**kwargs).get('rbac_policies')
return [RBACPolicy(p) for p in policies] | [
"def",
"rbac_policy_list",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"policies",
"=",
"neutronclient",
"(",
"request",
")",
".",
"list_rbac_policies",
"(",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"'rbac_policies'",
")",
"return",
"[",
"RBACPolic... | List of RBAC Policies. | [
"List",
"of",
"RBAC",
"Policies",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2018-L2022 |
235,029 | openstack/horizon | openstack_dashboard/api/neutron.py | rbac_policy_update | def rbac_policy_update(request, policy_id, **kwargs):
"""Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object
"""
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(request).update_rbac_policy(
policy_id, body=body).get('rbac_policy')
return RBACPolicy(rbac_policy) | python | def rbac_policy_update(request, policy_id, **kwargs):
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(request).update_rbac_policy(
policy_id, body=body).get('rbac_policy')
return RBACPolicy(rbac_policy) | [
"def",
"rbac_policy_update",
"(",
"request",
",",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"{",
"'rbac_policy'",
":",
"kwargs",
"}",
"rbac_policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"update_rbac_policy",
"(",
"policy_id",
",... | Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object | [
"Update",
"a",
"RBAC",
"Policy",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2025-L2036 |
235,030 | openstack/horizon | openstack_dashboard/api/neutron.py | rbac_policy_get | def rbac_policy_get(request, policy_id, **kwargs):
"""Get RBAC policy for a given policy id."""
policy = neutronclient(request).show_rbac_policy(
policy_id, **kwargs).get('rbac_policy')
return RBACPolicy(policy) | python | def rbac_policy_get(request, policy_id, **kwargs):
policy = neutronclient(request).show_rbac_policy(
policy_id, **kwargs).get('rbac_policy')
return RBACPolicy(policy) | [
"def",
"rbac_policy_get",
"(",
"request",
",",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
":",
"policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"show_rbac_policy",
"(",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"'rbac_policy'",
... | Get RBAC policy for a given policy id. | [
"Get",
"RBAC",
"policy",
"for",
"a",
"given",
"policy",
"id",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2040-L2044 |
235,031 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager.list | def list(self, **params):
"""Fetches a list all security groups.
:returns: List of SecurityGroup objects
"""
# This is to ensure tenant_id key is not populated
# if tenant_id=None is specified.
tenant_id = params.pop('tenant_id', self.request.user.tenant_id)
if tenant_id:
params['tenant_id'] = tenant_id
return self._list(**params) | python | def list(self, **params):
# This is to ensure tenant_id key is not populated
# if tenant_id=None is specified.
tenant_id = params.pop('tenant_id', self.request.user.tenant_id)
if tenant_id:
params['tenant_id'] = tenant_id
return self._list(**params) | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# This is to ensure tenant_id key is not populated",
"# if tenant_id=None is specified.",
"tenant_id",
"=",
"params",
".",
"pop",
"(",
"'tenant_id'",
",",
"self",
".",
"request",
".",
"user",
".",
"te... | Fetches a list all security groups.
:returns: List of SecurityGroup objects | [
"Fetches",
"a",
"list",
"all",
"security",
"groups",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L361-L371 |
235,032 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager._sg_name_dict | def _sg_name_dict(self, sg_id, rules):
"""Create a mapping dict from secgroup id to its name."""
related_ids = set([sg_id])
related_ids |= set(filter(None, [r['remote_group_id'] for r in rules]))
related_sgs = self.client.list_security_groups(id=related_ids,
fields=['id', 'name'])
related_sgs = related_sgs.get('security_groups')
return dict((sg['id'], sg['name']) for sg in related_sgs) | python | def _sg_name_dict(self, sg_id, rules):
related_ids = set([sg_id])
related_ids |= set(filter(None, [r['remote_group_id'] for r in rules]))
related_sgs = self.client.list_security_groups(id=related_ids,
fields=['id', 'name'])
related_sgs = related_sgs.get('security_groups')
return dict((sg['id'], sg['name']) for sg in related_sgs) | [
"def",
"_sg_name_dict",
"(",
"self",
",",
"sg_id",
",",
"rules",
")",
":",
"related_ids",
"=",
"set",
"(",
"[",
"sg_id",
"]",
")",
"related_ids",
"|=",
"set",
"(",
"filter",
"(",
"None",
",",
"[",
"r",
"[",
"'remote_group_id'",
"]",
"for",
"r",
"in",... | Create a mapping dict from secgroup id to its name. | [
"Create",
"a",
"mapping",
"dict",
"from",
"secgroup",
"id",
"to",
"its",
"name",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L373-L380 |
235,033 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager.get | def get(self, sg_id):
"""Fetches the security group.
:returns: SecurityGroup object corresponding to sg_id
"""
secgroup = self.client.show_security_group(sg_id).get('security_group')
sg_dict = self._sg_name_dict(sg_id, secgroup['security_group_rules'])
return SecurityGroup(secgroup, sg_dict) | python | def get(self, sg_id):
secgroup = self.client.show_security_group(sg_id).get('security_group')
sg_dict = self._sg_name_dict(sg_id, secgroup['security_group_rules'])
return SecurityGroup(secgroup, sg_dict) | [
"def",
"get",
"(",
"self",
",",
"sg_id",
")",
":",
"secgroup",
"=",
"self",
".",
"client",
".",
"show_security_group",
"(",
"sg_id",
")",
".",
"get",
"(",
"'security_group'",
")",
"sg_dict",
"=",
"self",
".",
"_sg_name_dict",
"(",
"sg_id",
",",
"secgroup... | Fetches the security group.
:returns: SecurityGroup object corresponding to sg_id | [
"Fetches",
"the",
"security",
"group",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L383-L390 |
235,034 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager.rule_create | def rule_create(self, parent_group_id,
direction=None, ethertype=None,
ip_protocol=None, from_port=None, to_port=None,
cidr=None, group_id=None, description=None):
"""Create a new security group rule.
:param parent_group_id: security group id a rule is created to
:param direction: ``ingress`` or ``egress``
:param ethertype: ``IPv4`` or ``IPv6``
:param ip_protocol: tcp, udp, icmp
:param from_port: L4 port range min
:param to_port: L4 port range max
:param cidr: Remote IP CIDR
:param group_id: ID of Source Security Group
:returns: SecurityGroupRule object
"""
if not cidr:
cidr = None
if isinstance(from_port, int) and from_port < 0:
from_port = None
if isinstance(to_port, int) and to_port < 0:
to_port = None
if isinstance(ip_protocol, int) and ip_protocol < 0:
ip_protocol = None
params = {'security_group_id': parent_group_id,
'direction': direction,
'ethertype': ethertype,
'protocol': ip_protocol,
'port_range_min': from_port,
'port_range_max': to_port,
'remote_ip_prefix': cidr,
'remote_group_id': group_id}
if description is not None:
params['description'] = description
body = {'security_group_rule': params}
try:
rule = self.client.create_security_group_rule(body)
except neutron_exc.OverQuotaClient:
raise exceptions.Conflict(
_('Security group rule quota exceeded.'))
except neutron_exc.Conflict:
raise exceptions.Conflict(
_('Security group rule already exists.'))
rule = rule.get('security_group_rule')
sg_dict = self._sg_name_dict(parent_group_id, [rule])
return SecurityGroupRule(rule, sg_dict) | python | def rule_create(self, parent_group_id,
direction=None, ethertype=None,
ip_protocol=None, from_port=None, to_port=None,
cidr=None, group_id=None, description=None):
if not cidr:
cidr = None
if isinstance(from_port, int) and from_port < 0:
from_port = None
if isinstance(to_port, int) and to_port < 0:
to_port = None
if isinstance(ip_protocol, int) and ip_protocol < 0:
ip_protocol = None
params = {'security_group_id': parent_group_id,
'direction': direction,
'ethertype': ethertype,
'protocol': ip_protocol,
'port_range_min': from_port,
'port_range_max': to_port,
'remote_ip_prefix': cidr,
'remote_group_id': group_id}
if description is not None:
params['description'] = description
body = {'security_group_rule': params}
try:
rule = self.client.create_security_group_rule(body)
except neutron_exc.OverQuotaClient:
raise exceptions.Conflict(
_('Security group rule quota exceeded.'))
except neutron_exc.Conflict:
raise exceptions.Conflict(
_('Security group rule already exists.'))
rule = rule.get('security_group_rule')
sg_dict = self._sg_name_dict(parent_group_id, [rule])
return SecurityGroupRule(rule, sg_dict) | [
"def",
"rule_create",
"(",
"self",
",",
"parent_group_id",
",",
"direction",
"=",
"None",
",",
"ethertype",
"=",
"None",
",",
"ip_protocol",
"=",
"None",
",",
"from_port",
"=",
"None",
",",
"to_port",
"=",
"None",
",",
"cidr",
"=",
"None",
",",
"group_id... | Create a new security group rule.
:param parent_group_id: security group id a rule is created to
:param direction: ``ingress`` or ``egress``
:param ethertype: ``IPv4`` or ``IPv6``
:param ip_protocol: tcp, udp, icmp
:param from_port: L4 port range min
:param to_port: L4 port range max
:param cidr: Remote IP CIDR
:param group_id: ID of Source Security Group
:returns: SecurityGroupRule object | [
"Create",
"a",
"new",
"security",
"group",
"rule",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L417-L463 |
235,035 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager.list_by_instance | def list_by_instance(self, instance_id):
"""Gets security groups of an instance.
:returns: List of SecurityGroup objects associated with the instance
"""
ports = port_list(self.request, device_id=instance_id)
sg_ids = []
for p in ports:
sg_ids += p.security_groups
return self._list(id=set(sg_ids)) if sg_ids else [] | python | def list_by_instance(self, instance_id):
ports = port_list(self.request, device_id=instance_id)
sg_ids = []
for p in ports:
sg_ids += p.security_groups
return self._list(id=set(sg_ids)) if sg_ids else [] | [
"def",
"list_by_instance",
"(",
"self",
",",
"instance_id",
")",
":",
"ports",
"=",
"port_list",
"(",
"self",
".",
"request",
",",
"device_id",
"=",
"instance_id",
")",
"sg_ids",
"=",
"[",
"]",
"for",
"p",
"in",
"ports",
":",
"sg_ids",
"+=",
"p",
".",
... | Gets security groups of an instance.
:returns: List of SecurityGroup objects associated with the instance | [
"Gets",
"security",
"groups",
"of",
"an",
"instance",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L471-L480 |
235,036 | openstack/horizon | openstack_dashboard/api/neutron.py | SecurityGroupManager.update_instance_security_group | def update_instance_security_group(self, instance_id,
new_security_group_ids):
"""Update security groups of a specified instance."""
ports = port_list(self.request, device_id=instance_id)
for p in ports:
params = {'security_groups': new_security_group_ids}
port_update(self.request, p.id, **params) | python | def update_instance_security_group(self, instance_id,
new_security_group_ids):
ports = port_list(self.request, device_id=instance_id)
for p in ports:
params = {'security_groups': new_security_group_ids}
port_update(self.request, p.id, **params) | [
"def",
"update_instance_security_group",
"(",
"self",
",",
"instance_id",
",",
"new_security_group_ids",
")",
":",
"ports",
"=",
"port_list",
"(",
"self",
".",
"request",
",",
"device_id",
"=",
"instance_id",
")",
"for",
"p",
"in",
"ports",
":",
"params",
"=",... | Update security groups of a specified instance. | [
"Update",
"security",
"groups",
"of",
"a",
"specified",
"instance",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L483-L489 |
235,037 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.list_pools | def list_pools(self):
"""Fetches a list of all floating IP pools.
:returns: List of FloatingIpPool objects
"""
search_opts = {'router:external': True}
return [FloatingIpPool(pool) for pool
in self.client.list_networks(**search_opts).get('networks')] | python | def list_pools(self):
search_opts = {'router:external': True}
return [FloatingIpPool(pool) for pool
in self.client.list_networks(**search_opts).get('networks')] | [
"def",
"list_pools",
"(",
"self",
")",
":",
"search_opts",
"=",
"{",
"'router:external'",
":",
"True",
"}",
"return",
"[",
"FloatingIpPool",
"(",
"pool",
")",
"for",
"pool",
"in",
"self",
".",
"client",
".",
"list_networks",
"(",
"*",
"*",
"search_opts",
... | Fetches a list of all floating IP pools.
:returns: List of FloatingIpPool objects | [
"Fetches",
"a",
"list",
"of",
"all",
"floating",
"IP",
"pools",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L553-L560 |
235,038 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.list | def list(self, all_tenants=False, **search_opts):
"""Fetches a list of all floating IPs.
:returns: List of FloatingIp object
"""
if not all_tenants:
tenant_id = self.request.user.tenant_id
# In Neutron, list_floatingips returns Floating IPs from
# all tenants when the API is called with admin role, so
# we need to filter them with tenant_id.
search_opts['tenant_id'] = tenant_id
port_search_opts = {'tenant_id': tenant_id}
else:
port_search_opts = {}
fips = self.client.list_floatingips(**search_opts)
fips = fips.get('floatingips')
# Get port list to add instance_id to floating IP list
# instance_id is stored in device_id attribute
ports = port_list(self.request, **port_search_opts)
port_dict = collections.OrderedDict([(p['id'], p) for p in ports])
for fip in fips:
self._set_instance_info(fip, port_dict.get(fip['port_id']))
return [FloatingIp(fip) for fip in fips] | python | def list(self, all_tenants=False, **search_opts):
if not all_tenants:
tenant_id = self.request.user.tenant_id
# In Neutron, list_floatingips returns Floating IPs from
# all tenants when the API is called with admin role, so
# we need to filter them with tenant_id.
search_opts['tenant_id'] = tenant_id
port_search_opts = {'tenant_id': tenant_id}
else:
port_search_opts = {}
fips = self.client.list_floatingips(**search_opts)
fips = fips.get('floatingips')
# Get port list to add instance_id to floating IP list
# instance_id is stored in device_id attribute
ports = port_list(self.request, **port_search_opts)
port_dict = collections.OrderedDict([(p['id'], p) for p in ports])
for fip in fips:
self._set_instance_info(fip, port_dict.get(fip['port_id']))
return [FloatingIp(fip) for fip in fips] | [
"def",
"list",
"(",
"self",
",",
"all_tenants",
"=",
"False",
",",
"*",
"*",
"search_opts",
")",
":",
"if",
"not",
"all_tenants",
":",
"tenant_id",
"=",
"self",
".",
"request",
".",
"user",
".",
"tenant_id",
"# In Neutron, list_floatingips returns Floating IPs f... | Fetches a list of all floating IPs.
:returns: List of FloatingIp object | [
"Fetches",
"a",
"list",
"of",
"all",
"floating",
"IPs",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L580-L602 |
235,039 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.get | def get(self, floating_ip_id):
"""Fetches the floating IP.
:returns: FloatingIp object corresponding to floating_ip_id
"""
fip = self.client.show_floatingip(floating_ip_id).get('floatingip')
self._set_instance_info(fip)
return FloatingIp(fip) | python | def get(self, floating_ip_id):
fip = self.client.show_floatingip(floating_ip_id).get('floatingip')
self._set_instance_info(fip)
return FloatingIp(fip) | [
"def",
"get",
"(",
"self",
",",
"floating_ip_id",
")",
":",
"fip",
"=",
"self",
".",
"client",
".",
"show_floatingip",
"(",
"floating_ip_id",
")",
".",
"get",
"(",
"'floatingip'",
")",
"self",
".",
"_set_instance_info",
"(",
"fip",
")",
"return",
"Floating... | Fetches the floating IP.
:returns: FloatingIp object corresponding to floating_ip_id | [
"Fetches",
"the",
"floating",
"IP",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L605-L612 |
235,040 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.allocate | def allocate(self, pool, tenant_id=None, **params):
"""Allocates a floating IP to the tenant.
You must provide a pool name or id for which you would like to
allocate a floating IP.
:returns: FloatingIp object corresponding to an allocated floating IP
"""
if not tenant_id:
tenant_id = self.request.user.project_id
create_dict = {'floating_network_id': pool,
'tenant_id': tenant_id}
if 'subnet_id' in params:
create_dict['subnet_id'] = params['subnet_id']
if 'floating_ip_address' in params:
create_dict['floating_ip_address'] = params['floating_ip_address']
if 'description' in params:
create_dict['description'] = params['description']
if 'dns_domain' in params:
create_dict['dns_domain'] = params['dns_domain']
if 'dns_name' in params:
create_dict['dns_name'] = params['dns_name']
fip = self.client.create_floatingip(
{'floatingip': create_dict}).get('floatingip')
self._set_instance_info(fip)
return FloatingIp(fip) | python | def allocate(self, pool, tenant_id=None, **params):
if not tenant_id:
tenant_id = self.request.user.project_id
create_dict = {'floating_network_id': pool,
'tenant_id': tenant_id}
if 'subnet_id' in params:
create_dict['subnet_id'] = params['subnet_id']
if 'floating_ip_address' in params:
create_dict['floating_ip_address'] = params['floating_ip_address']
if 'description' in params:
create_dict['description'] = params['description']
if 'dns_domain' in params:
create_dict['dns_domain'] = params['dns_domain']
if 'dns_name' in params:
create_dict['dns_name'] = params['dns_name']
fip = self.client.create_floatingip(
{'floatingip': create_dict}).get('floatingip')
self._set_instance_info(fip)
return FloatingIp(fip) | [
"def",
"allocate",
"(",
"self",
",",
"pool",
",",
"tenant_id",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"tenant_id",
":",
"tenant_id",
"=",
"self",
".",
"request",
".",
"user",
".",
"project_id",
"create_dict",
"=",
"{",
"'floating_... | Allocates a floating IP to the tenant.
You must provide a pool name or id for which you would like to
allocate a floating IP.
:returns: FloatingIp object corresponding to an allocated floating IP | [
"Allocates",
"a",
"floating",
"IP",
"to",
"the",
"tenant",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L615-L640 |
235,041 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.associate | def associate(self, floating_ip_id, port_id):
"""Associates the floating IP to the port.
``port_id`` represents a VNIC of an instance.
``port_id`` argument is different from a normal neutron port ID.
A value passed as ``port_id`` must be one of target_id returned by
``list_targets``, ``get_target_by_instance`` or
``list_targets_by_instance`` method.
"""
# NOTE: In Neutron Horizon floating IP support, port_id is
# "<port_id>_<ip_address>" format to identify multiple ports.
pid, ip_address = port_id.split('_', 1)
update_dict = {'port_id': pid,
'fixed_ip_address': ip_address}
self.client.update_floatingip(floating_ip_id,
{'floatingip': update_dict}) | python | def associate(self, floating_ip_id, port_id):
# NOTE: In Neutron Horizon floating IP support, port_id is
# "<port_id>_<ip_address>" format to identify multiple ports.
pid, ip_address = port_id.split('_', 1)
update_dict = {'port_id': pid,
'fixed_ip_address': ip_address}
self.client.update_floatingip(floating_ip_id,
{'floatingip': update_dict}) | [
"def",
"associate",
"(",
"self",
",",
"floating_ip_id",
",",
"port_id",
")",
":",
"# NOTE: In Neutron Horizon floating IP support, port_id is",
"# \"<port_id>_<ip_address>\" format to identify multiple ports.",
"pid",
",",
"ip_address",
"=",
"port_id",
".",
"split",
"(",
"'_'... | Associates the floating IP to the port.
``port_id`` represents a VNIC of an instance.
``port_id`` argument is different from a normal neutron port ID.
A value passed as ``port_id`` must be one of target_id returned by
``list_targets``, ``get_target_by_instance`` or
``list_targets_by_instance`` method. | [
"Associates",
"the",
"floating",
"IP",
"to",
"the",
"port",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L648-L663 |
235,042 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.list_targets | def list_targets(self):
"""Returns a list of association targets of instance VIFs.
Each association target is represented as FloatingIpTarget object.
FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and
'id' and 'name' attributes must be defined in each object.
FloatingIpTarget.id can be passed as port_id in associate().
FloatingIpTarget.name is displayed in Floating Ip Association Form.
"""
tenant_id = self.request.user.tenant_id
ports = port_list(self.request, tenant_id=tenant_id)
servers, has_more = nova.server_list(self.request, detailed=False)
server_dict = collections.OrderedDict(
[(s.id, s.name) for s in servers])
reachable_subnets = self._get_reachable_subnets(ports)
targets = []
for p in ports:
# Remove network ports from Floating IP targets
if p.device_owner.startswith('network:'):
continue
server_name = server_dict.get(p.device_id)
for ip in p.fixed_ips:
if ip['subnet_id'] not in reachable_subnets:
continue
# Floating IPs can only target IPv4 addresses.
if netaddr.IPAddress(ip['ip_address']).version != 4:
continue
targets.append(FloatingIpTarget(p, ip['ip_address'],
server_name))
return targets | python | def list_targets(self):
tenant_id = self.request.user.tenant_id
ports = port_list(self.request, tenant_id=tenant_id)
servers, has_more = nova.server_list(self.request, detailed=False)
server_dict = collections.OrderedDict(
[(s.id, s.name) for s in servers])
reachable_subnets = self._get_reachable_subnets(ports)
targets = []
for p in ports:
# Remove network ports from Floating IP targets
if p.device_owner.startswith('network:'):
continue
server_name = server_dict.get(p.device_id)
for ip in p.fixed_ips:
if ip['subnet_id'] not in reachable_subnets:
continue
# Floating IPs can only target IPv4 addresses.
if netaddr.IPAddress(ip['ip_address']).version != 4:
continue
targets.append(FloatingIpTarget(p, ip['ip_address'],
server_name))
return targets | [
"def",
"list_targets",
"(",
"self",
")",
":",
"tenant_id",
"=",
"self",
".",
"request",
".",
"user",
".",
"tenant_id",
"ports",
"=",
"port_list",
"(",
"self",
".",
"request",
",",
"tenant_id",
"=",
"tenant_id",
")",
"servers",
",",
"has_more",
"=",
"nova... | Returns a list of association targets of instance VIFs.
Each association target is represented as FloatingIpTarget object.
FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and
'id' and 'name' attributes must be defined in each object.
FloatingIpTarget.id can be passed as port_id in associate().
FloatingIpTarget.name is displayed in Floating Ip Association Form. | [
"Returns",
"a",
"list",
"of",
"association",
"targets",
"of",
"instance",
"VIFs",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L700-L731 |
235,043 | openstack/horizon | openstack_dashboard/api/neutron.py | FloatingIpManager.list_targets_by_instance | def list_targets_by_instance(self, instance_id, target_list=None):
"""Returns a list of FloatingIpTarget objects of FIP association.
:param instance_id: ID of target VM instance
:param target_list: (optional) a list returned by list_targets().
If specified, looking up is done against the specified list
to save extra API calls to a back-end. Otherwise target list
is retrieved from a back-end inside the method.
"""
if target_list is not None:
# We assume that target_list was returned by list_targets()
# so we can assume checks for subnet reachability and IP version
# have been done already. We skip all checks here.
return [target for target in target_list
if target['instance_id'] == instance_id]
else:
ports = self._target_ports_by_instance(instance_id)
reachable_subnets = self._get_reachable_subnets(
ports, fetch_router_ports=True)
name = self._get_server_name(instance_id)
targets = []
for p in ports:
for ip in p.fixed_ips:
if ip['subnet_id'] not in reachable_subnets:
continue
# Floating IPs can only target IPv4 addresses.
if netaddr.IPAddress(ip['ip_address']).version != 4:
continue
targets.append(FloatingIpTarget(p, ip['ip_address'], name))
return targets | python | def list_targets_by_instance(self, instance_id, target_list=None):
if target_list is not None:
# We assume that target_list was returned by list_targets()
# so we can assume checks for subnet reachability and IP version
# have been done already. We skip all checks here.
return [target for target in target_list
if target['instance_id'] == instance_id]
else:
ports = self._target_ports_by_instance(instance_id)
reachable_subnets = self._get_reachable_subnets(
ports, fetch_router_ports=True)
name = self._get_server_name(instance_id)
targets = []
for p in ports:
for ip in p.fixed_ips:
if ip['subnet_id'] not in reachable_subnets:
continue
# Floating IPs can only target IPv4 addresses.
if netaddr.IPAddress(ip['ip_address']).version != 4:
continue
targets.append(FloatingIpTarget(p, ip['ip_address'], name))
return targets | [
"def",
"list_targets_by_instance",
"(",
"self",
",",
"instance_id",
",",
"target_list",
"=",
"None",
")",
":",
"if",
"target_list",
"is",
"not",
"None",
":",
"# We assume that target_list was returned by list_targets()",
"# so we can assume checks for subnet reachability and IP... | Returns a list of FloatingIpTarget objects of FIP association.
:param instance_id: ID of target VM instance
:param target_list: (optional) a list returned by list_targets().
If specified, looking up is done against the specified list
to save extra API calls to a back-end. Otherwise target list
is retrieved from a back-end inside the method. | [
"Returns",
"a",
"list",
"of",
"FloatingIpTarget",
"objects",
"of",
"FIP",
"association",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L740-L769 |
235,044 | openstack/horizon | horizon/decorators.py | require_perms | def require_perms(view_func, required):
"""Enforces permission-based access controls.
:param list required: A tuple of permission names, all of which the request
user must possess in order access the decorated view.
Example usage::
from horizon.decorators import require_perms
@require_perms(['foo.admin', 'foo.member'])
def my_view(request):
...
Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the
requirements are not met.
"""
from horizon.exceptions import NotAuthorized
# We only need to check each permission once for a view, so we'll use a set
current_perms = getattr(view_func, '_required_perms', set([]))
view_func._required_perms = current_perms | set(required)
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if request.user.is_authenticated:
if request.user.has_perms(view_func._required_perms):
return view_func(request, *args, **kwargs)
raise NotAuthorized(_("You are not authorized to access %s")
% request.path)
# If we don't have any permissions, just return the original view.
if required:
return dec
else:
return view_func | python | def require_perms(view_func, required):
from horizon.exceptions import NotAuthorized
# We only need to check each permission once for a view, so we'll use a set
current_perms = getattr(view_func, '_required_perms', set([]))
view_func._required_perms = current_perms | set(required)
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if request.user.is_authenticated:
if request.user.has_perms(view_func._required_perms):
return view_func(request, *args, **kwargs)
raise NotAuthorized(_("You are not authorized to access %s")
% request.path)
# If we don't have any permissions, just return the original view.
if required:
return dec
else:
return view_func | [
"def",
"require_perms",
"(",
"view_func",
",",
"required",
")",
":",
"from",
"horizon",
".",
"exceptions",
"import",
"NotAuthorized",
"# We only need to check each permission once for a view, so we'll use a set",
"current_perms",
"=",
"getattr",
"(",
"view_func",
",",
"'_re... | Enforces permission-based access controls.
:param list required: A tuple of permission names, all of which the request
user must possess in order access the decorated view.
Example usage::
from horizon.decorators import require_perms
@require_perms(['foo.admin', 'foo.member'])
def my_view(request):
...
Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the
requirements are not met. | [
"Enforces",
"permission",
"-",
"based",
"access",
"controls",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/decorators.py#L57-L92 |
235,045 | openstack/horizon | horizon/decorators.py | require_component_access | def require_component_access(view_func, component):
"""Perform component can_access check to access the view.
:param component containing the view (panel or dashboard).
Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the
user cannot access the component containing the view.
By example the check of component policy rules will be applied to its
views.
"""
from horizon.exceptions import NotAuthorized
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if not component.can_access({'request': request}):
raise NotAuthorized(_("You are not authorized to access %s")
% request.path)
return view_func(request, *args, **kwargs)
return dec | python | def require_component_access(view_func, component):
from horizon.exceptions import NotAuthorized
@functools.wraps(view_func, assigned=available_attrs(view_func))
def dec(request, *args, **kwargs):
if not component.can_access({'request': request}):
raise NotAuthorized(_("You are not authorized to access %s")
% request.path)
return view_func(request, *args, **kwargs)
return dec | [
"def",
"require_component_access",
"(",
"view_func",
",",
"component",
")",
":",
"from",
"horizon",
".",
"exceptions",
"import",
"NotAuthorized",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")... | Perform component can_access check to access the view.
:param component containing the view (panel or dashboard).
Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the
user cannot access the component containing the view.
By example the check of component policy rules will be applied to its
views. | [
"Perform",
"component",
"can_access",
"check",
"to",
"access",
"the",
"view",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/decorators.py#L95-L115 |
235,046 | openstack/horizon | openstack_dashboard/api/glance.py | image_get | def image_get(request, image_id):
"""Returns an Image object populated with metadata for a given image."""
image = glanceclient(request).images.get(image_id)
return Image(image) | python | def image_get(request, image_id):
image = glanceclient(request).images.get(image_id)
return Image(image) | [
"def",
"image_get",
"(",
"request",
",",
"image_id",
")",
":",
"image",
"=",
"glanceclient",
"(",
"request",
")",
".",
"images",
".",
"get",
"(",
"image_id",
")",
"return",
"Image",
"(",
"image",
")"
] | Returns an Image object populated with metadata for a given image. | [
"Returns",
"an",
"Image",
"object",
"populated",
"with",
"metadata",
"for",
"a",
"given",
"image",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L263-L266 |
235,047 | openstack/horizon | openstack_dashboard/api/glance.py | image_list_detailed | def image_list_detailed(request, marker=None, sort_dir='desc',
sort_key='created_at', filters=None, paginate=False,
reversed_order=False, **kwargs):
"""Thin layer above glanceclient, for handling pagination issues.
It provides iterating both forward and backward on top of ascetic
OpenStack pagination API - which natively supports only iterating forward
through the entries. Thus in order to retrieve list of objects at previous
page, a request with the reverse entries order had to be made to Glance,
using the first object id on current page as the marker - restoring
the original items ordering before sending them back to the UI.
:param request:
The request object coming from browser to be passed further into
Glance service.
:param marker:
The id of an object which defines a starting point of a query sent to
Glance service.
:param sort_dir:
The direction by which the resulting image list throughout all pages
(if pagination is enabled) will be sorted. Could be either 'asc'
(ascending) or 'desc' (descending), defaults to 'desc'.
:param sort_key:
The name of key by by which the resulting image list throughout all
pages (if pagination is enabled) will be sorted. Defaults to
'created_at'.
:param filters:
A dictionary of filters passed as is to Glance service.
:param paginate:
Whether the pagination is enabled. If it is, then the number of
entries on a single page of images table is limited to the specific
number stored in browser cookies.
:param reversed_order:
Set this flag to True when it's necessary to get a reversed list of
images from Glance (used for navigating the images list back in UI).
"""
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
_normalize_list_input(filters, **kwargs)
kwargs = {'filters': filters or {}}
if marker:
kwargs['marker'] = marker
kwargs['sort_key'] = sort_key
if not reversed_order:
kwargs['sort_dir'] = sort_dir
else:
kwargs['sort_dir'] = 'desc' if sort_dir == 'asc' else 'asc'
images_iter = glanceclient(request).images.list(page_size=request_size,
limit=limit,
**kwargs)
has_prev_data = False
has_more_data = False
if paginate:
images = list(itertools.islice(images_iter, request_size))
# first and middle page condition
if len(images) > page_size:
images.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif reversed_order and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
# restore the original ordering here
if reversed_order:
images = sorted(images, key=lambda image:
(getattr(image, sort_key) or '').lower(),
reverse=(sort_dir == 'desc'))
else:
images = list(images_iter)
# TODO(jpichon): Do it better
wrapped_images = []
for image in images:
wrapped_images.append(Image(image))
return wrapped_images, has_more_data, has_prev_data | python | def image_list_detailed(request, marker=None, sort_dir='desc',
sort_key='created_at', filters=None, paginate=False,
reversed_order=False, **kwargs):
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
_normalize_list_input(filters, **kwargs)
kwargs = {'filters': filters or {}}
if marker:
kwargs['marker'] = marker
kwargs['sort_key'] = sort_key
if not reversed_order:
kwargs['sort_dir'] = sort_dir
else:
kwargs['sort_dir'] = 'desc' if sort_dir == 'asc' else 'asc'
images_iter = glanceclient(request).images.list(page_size=request_size,
limit=limit,
**kwargs)
has_prev_data = False
has_more_data = False
if paginate:
images = list(itertools.islice(images_iter, request_size))
# first and middle page condition
if len(images) > page_size:
images.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif reversed_order and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
# restore the original ordering here
if reversed_order:
images = sorted(images, key=lambda image:
(getattr(image, sort_key) or '').lower(),
reverse=(sort_dir == 'desc'))
else:
images = list(images_iter)
# TODO(jpichon): Do it better
wrapped_images = []
for image in images:
wrapped_images.append(Image(image))
return wrapped_images, has_more_data, has_prev_data | [
"def",
"image_list_detailed",
"(",
"request",
",",
"marker",
"=",
"None",
",",
"sort_dir",
"=",
"'desc'",
",",
"sort_key",
"=",
"'created_at'",
",",
"filters",
"=",
"None",
",",
"paginate",
"=",
"False",
",",
"reversed_order",
"=",
"False",
",",
"*",
"*",
... | Thin layer above glanceclient, for handling pagination issues.
It provides iterating both forward and backward on top of ascetic
OpenStack pagination API - which natively supports only iterating forward
through the entries. Thus in order to retrieve list of objects at previous
page, a request with the reverse entries order had to be made to Glance,
using the first object id on current page as the marker - restoring
the original items ordering before sending them back to the UI.
:param request:
The request object coming from browser to be passed further into
Glance service.
:param marker:
The id of an object which defines a starting point of a query sent to
Glance service.
:param sort_dir:
The direction by which the resulting image list throughout all pages
(if pagination is enabled) will be sorted. Could be either 'asc'
(ascending) or 'desc' (descending), defaults to 'desc'.
:param sort_key:
The name of key by by which the resulting image list throughout all
pages (if pagination is enabled) will be sorted. Defaults to
'created_at'.
:param filters:
A dictionary of filters passed as is to Glance service.
:param paginate:
Whether the pagination is enabled. If it is, then the number of
entries on a single page of images table is limited to the specific
number stored in browser cookies.
:param reversed_order:
Set this flag to True when it's necessary to get a reversed list of
images from Glance (used for navigating the images list back in UI). | [
"Thin",
"layer",
"above",
"glanceclient",
"for",
"handling",
"pagination",
"issues",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L283-L386 |
235,048 | openstack/horizon | openstack_dashboard/api/glance.py | create_image_metadata | def create_image_metadata(data):
"""Generate metadata dict for a new image from a given form data."""
# Default metadata
meta = {'protected': data.get('protected', False),
'disk_format': data.get('disk_format', 'raw'),
'container_format': data.get('container_format', 'bare'),
'min_disk': data.get('min_disk') or 0,
'min_ram': data.get('min_ram') or 0,
'name': data.get('name', '')}
# Glance does not really do anything with container_format at the
# moment. It requires it is set to the same disk_format for the three
# Amazon image types, otherwise it just treats them as 'bare.' As such
# we will just set that to be that here instead of bothering the user
# with asking them for information we can already determine.
if meta['disk_format'] in ('ami', 'aki', 'ari',):
meta['container_format'] = meta['disk_format']
elif meta['disk_format'] == 'docker':
# To support docker containers we allow the user to specify
# 'docker' as the format. In that case we really want to use
# 'raw' as the disk format and 'docker' as the container format.
meta['disk_format'] = 'raw'
meta['container_format'] = 'docker'
elif meta['disk_format'] == 'ova':
# If the user wishes to upload an OVA using Horizon, then
# 'ova' must be the container format and 'vmdk' must be the disk
# format.
meta['container_format'] = 'ova'
meta['disk_format'] = 'vmdk'
properties = {}
for prop, key in [('description', 'description'),
('kernel_id', 'kernel'),
('ramdisk_id', 'ramdisk'),
('architecture', 'architecture')]:
if data.get(key):
properties[prop] = data[key]
_handle_unknown_properties(data, properties)
if ('visibility' in data and
data['visibility'] not in ['public', 'private', 'community',
'shared']):
raise KeyError('invalid visibility option: %s' % data['visibility'])
_normalize_is_public_filter(data)
if VERSIONS.active < 2:
meta['properties'] = properties
meta['is_public'] = data.get('is_public', False)
else:
meta['visibility'] = data.get('visibility', 'private')
meta.update(properties)
return meta | python | def create_image_metadata(data):
# Default metadata
meta = {'protected': data.get('protected', False),
'disk_format': data.get('disk_format', 'raw'),
'container_format': data.get('container_format', 'bare'),
'min_disk': data.get('min_disk') or 0,
'min_ram': data.get('min_ram') or 0,
'name': data.get('name', '')}
# Glance does not really do anything with container_format at the
# moment. It requires it is set to the same disk_format for the three
# Amazon image types, otherwise it just treats them as 'bare.' As such
# we will just set that to be that here instead of bothering the user
# with asking them for information we can already determine.
if meta['disk_format'] in ('ami', 'aki', 'ari',):
meta['container_format'] = meta['disk_format']
elif meta['disk_format'] == 'docker':
# To support docker containers we allow the user to specify
# 'docker' as the format. In that case we really want to use
# 'raw' as the disk format and 'docker' as the container format.
meta['disk_format'] = 'raw'
meta['container_format'] = 'docker'
elif meta['disk_format'] == 'ova':
# If the user wishes to upload an OVA using Horizon, then
# 'ova' must be the container format and 'vmdk' must be the disk
# format.
meta['container_format'] = 'ova'
meta['disk_format'] = 'vmdk'
properties = {}
for prop, key in [('description', 'description'),
('kernel_id', 'kernel'),
('ramdisk_id', 'ramdisk'),
('architecture', 'architecture')]:
if data.get(key):
properties[prop] = data[key]
_handle_unknown_properties(data, properties)
if ('visibility' in data and
data['visibility'] not in ['public', 'private', 'community',
'shared']):
raise KeyError('invalid visibility option: %s' % data['visibility'])
_normalize_is_public_filter(data)
if VERSIONS.active < 2:
meta['properties'] = properties
meta['is_public'] = data.get('is_public', False)
else:
meta['visibility'] = data.get('visibility', 'private')
meta.update(properties)
return meta | [
"def",
"create_image_metadata",
"(",
"data",
")",
":",
"# Default metadata",
"meta",
"=",
"{",
"'protected'",
":",
"data",
".",
"get",
"(",
"'protected'",
",",
"False",
")",
",",
"'disk_format'",
":",
"data",
".",
"get",
"(",
"'disk_format'",
",",
"'raw'",
... | Generate metadata dict for a new image from a given form data. | [
"Generate",
"metadata",
"dict",
"for",
"a",
"new",
"image",
"from",
"a",
"given",
"form",
"data",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L451-L506 |
235,049 | openstack/horizon | openstack_dashboard/api/glance.py | image_create | def image_create(request, **kwargs):
"""Create image.
:param kwargs:
* copy_from: URL from which Glance server should immediately copy
the data and store it in its configured image store.
* data: Form data posted from client.
* location: URL where the data for this image already resides.
In the case of 'copy_from' and 'location', the Glance server
will give us a immediate response from create and handle the data
asynchronously.
In the case of 'data' the process of uploading the data may take
some time and is handed off to a separate thread.
"""
data = kwargs.pop('data', None)
location = None
if VERSIONS.active >= 2:
location = kwargs.pop('location', None)
image = glanceclient(request).images.create(**kwargs)
if location is not None:
glanceclient(request).images.add_location(image.id, location, {})
if data:
if isinstance(data, six.string_types):
# The image data is meant to be uploaded externally, return a
# special wrapper to bypass the web server in a subsequent upload
return ExternallyUploadedImage(image, request)
elif isinstance(data, TemporaryUploadedFile):
# Hack to fool Django, so we can keep file open in the new thread.
if six.PY2:
data.file.close_called = True
else:
data.file._closer.close_called = True
elif isinstance(data, InMemoryUploadedFile):
# Clone a new file for InMemeoryUploadedFile.
# Because the old one will be closed by Django.
data = SimpleUploadedFile(data.name,
data.read(),
data.content_type)
if VERSIONS.active < 2:
thread.start_new_thread(image_update,
(request, image.id),
{'data': data})
else:
def upload():
try:
return glanceclient(request).images.upload(image.id, data)
finally:
filename = str(data.file.name)
try:
os.remove(filename)
except OSError as e:
LOG.warning('Failed to remove temporary image file '
'%(file)s (%(e)s)',
{'file': filename, 'e': e})
thread.start_new_thread(upload, ())
return Image(image) | python | def image_create(request, **kwargs):
data = kwargs.pop('data', None)
location = None
if VERSIONS.active >= 2:
location = kwargs.pop('location', None)
image = glanceclient(request).images.create(**kwargs)
if location is not None:
glanceclient(request).images.add_location(image.id, location, {})
if data:
if isinstance(data, six.string_types):
# The image data is meant to be uploaded externally, return a
# special wrapper to bypass the web server in a subsequent upload
return ExternallyUploadedImage(image, request)
elif isinstance(data, TemporaryUploadedFile):
# Hack to fool Django, so we can keep file open in the new thread.
if six.PY2:
data.file.close_called = True
else:
data.file._closer.close_called = True
elif isinstance(data, InMemoryUploadedFile):
# Clone a new file for InMemeoryUploadedFile.
# Because the old one will be closed by Django.
data = SimpleUploadedFile(data.name,
data.read(),
data.content_type)
if VERSIONS.active < 2:
thread.start_new_thread(image_update,
(request, image.id),
{'data': data})
else:
def upload():
try:
return glanceclient(request).images.upload(image.id, data)
finally:
filename = str(data.file.name)
try:
os.remove(filename)
except OSError as e:
LOG.warning('Failed to remove temporary image file '
'%(file)s (%(e)s)',
{'file': filename, 'e': e})
thread.start_new_thread(upload, ())
return Image(image) | [
"def",
"image_create",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"pop",
"(",
"'data'",
",",
"None",
")",
"location",
"=",
"None",
"if",
"VERSIONS",
".",
"active",
">=",
"2",
":",
"location",
"=",
"kwargs",
".",
... | Create image.
:param kwargs:
* copy_from: URL from which Glance server should immediately copy
the data and store it in its configured image store.
* data: Form data posted from client.
* location: URL where the data for this image already resides.
In the case of 'copy_from' and 'location', the Glance server
will give us a immediate response from create and handle the data
asynchronously.
In the case of 'data' the process of uploading the data may take
some time and is handed off to a separate thread. | [
"Create",
"image",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L521-L581 |
235,050 | openstack/horizon | openstack_dashboard/api/glance.py | image_update_properties | def image_update_properties(request, image_id, remove_props=None, **kwargs):
"""Add or update a custom property of an image."""
return glanceclient(request, '2').images.update(image_id,
remove_props,
**kwargs) | python | def image_update_properties(request, image_id, remove_props=None, **kwargs):
return glanceclient(request, '2').images.update(image_id,
remove_props,
**kwargs) | [
"def",
"image_update_properties",
"(",
"request",
",",
"image_id",
",",
"remove_props",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"glanceclient",
"(",
"request",
",",
"'2'",
")",
".",
"images",
".",
"update",
"(",
"image_id",
",",
"remove_p... | Add or update a custom property of an image. | [
"Add",
"or",
"update",
"a",
"custom",
"property",
"of",
"an",
"image",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L585-L589 |
235,051 | openstack/horizon | openstack_dashboard/api/glance.py | image_delete_properties | def image_delete_properties(request, image_id, keys):
"""Delete custom properties for an image."""
return glanceclient(request, '2').images.update(image_id, keys) | python | def image_delete_properties(request, image_id, keys):
return glanceclient(request, '2').images.update(image_id, keys) | [
"def",
"image_delete_properties",
"(",
"request",
",",
"image_id",
",",
"keys",
")",
":",
"return",
"glanceclient",
"(",
"request",
",",
"'2'",
")",
".",
"images",
".",
"update",
"(",
"image_id",
",",
"keys",
")"
] | Delete custom properties for an image. | [
"Delete",
"custom",
"properties",
"for",
"an",
"image",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L593-L595 |
235,052 | openstack/horizon | openstack_dashboard/api/glance.py | filter_properties_target | def filter_properties_target(namespaces_iter,
resource_types,
properties_target):
"""Filter metadata namespaces.
Filtering is done based ongiven resource types and a properties target.
:param namespaces_iter: Metadata namespaces iterable.
:param resource_types: List of resource type names.
:param properties_target: Name of the properties target.
"""
def filter_namespace(namespace):
for asn in namespace.get('resource_type_associations'):
if (asn.get('name') in resource_types and
asn.get('properties_target') == properties_target):
return True
return False
return filter(filter_namespace, namespaces_iter) | python | def filter_properties_target(namespaces_iter,
resource_types,
properties_target):
def filter_namespace(namespace):
for asn in namespace.get('resource_type_associations'):
if (asn.get('name') in resource_types and
asn.get('properties_target') == properties_target):
return True
return False
return filter(filter_namespace, namespaces_iter) | [
"def",
"filter_properties_target",
"(",
"namespaces_iter",
",",
"resource_types",
",",
"properties_target",
")",
":",
"def",
"filter_namespace",
"(",
"namespace",
")",
":",
"for",
"asn",
"in",
"namespace",
".",
"get",
"(",
"'resource_type_associations'",
")",
":",
... | Filter metadata namespaces.
Filtering is done based ongiven resource types and a properties target.
:param namespaces_iter: Metadata namespaces iterable.
:param resource_types: List of resource type names.
:param properties_target: Name of the properties target. | [
"Filter",
"metadata",
"namespaces",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L634-L651 |
235,053 | openstack/horizon | openstack_dashboard/api/glance.py | metadefs_namespace_list | def metadefs_namespace_list(request,
filters=None,
sort_dir='asc',
sort_key='namespace',
marker=None,
paginate=False):
"""Retrieve a listing of Namespaces
:param paginate: If true will perform pagination based on settings.
:param marker: Specifies the namespace of the last-seen namespace.
The typical pattern of limit and marker is to make an
initial limited request and then to use the last
namespace from the response as the marker parameter
in a subsequent limited request. With paginate, limit
is automatically set.
:param sort_dir: The sort direction ('asc' or 'desc').
:param sort_key: The field to sort on (for example, 'created_at'). Default
is namespace. The way base namespaces are loaded into glance
typically at first deployment is done in a single transaction
giving them a potentially unpredictable sort result when using
create_at.
:param filters: specifies addition fields to filter on such as
resource_types.
:returns A tuple of three values:
1) Current page results
2) A boolean of whether or not there are previous page(s).
3) A boolean of whether or not there are more page(s).
"""
# Listing namespaces requires the v2 API. If not supported we return an
# empty array so callers don't need to worry about version checking.
if get_version() < 2:
return [], False, False
if filters is None:
filters = {}
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
kwargs = {'filters': filters}
if marker:
kwargs['marker'] = marker
kwargs['sort_dir'] = sort_dir
kwargs['sort_key'] = sort_key
namespaces_iter = glanceclient(request, '2').metadefs_namespace.list(
page_size=request_size, limit=limit, **kwargs)
# Filter the namespaces based on the provided properties_target since this
# is not supported by the metadata namespaces API.
resource_types = filters.get('resource_types')
properties_target = filters.get('properties_target')
if resource_types and properties_target:
namespaces_iter = filter_properties_target(namespaces_iter,
resource_types,
properties_target)
has_prev_data = False
has_more_data = False
if paginate:
namespaces = list(itertools.islice(namespaces_iter, request_size))
# first and middle page condition
if len(namespaces) > page_size:
namespaces.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif sort_dir == 'desc' and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
else:
namespaces = list(namespaces_iter)
namespaces = [Namespace(namespace) for namespace in namespaces]
return namespaces, has_more_data, has_prev_data | python | def metadefs_namespace_list(request,
filters=None,
sort_dir='asc',
sort_key='namespace',
marker=None,
paginate=False):
# Listing namespaces requires the v2 API. If not supported we return an
# empty array so callers don't need to worry about version checking.
if get_version() < 2:
return [], False, False
if filters is None:
filters = {}
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
kwargs = {'filters': filters}
if marker:
kwargs['marker'] = marker
kwargs['sort_dir'] = sort_dir
kwargs['sort_key'] = sort_key
namespaces_iter = glanceclient(request, '2').metadefs_namespace.list(
page_size=request_size, limit=limit, **kwargs)
# Filter the namespaces based on the provided properties_target since this
# is not supported by the metadata namespaces API.
resource_types = filters.get('resource_types')
properties_target = filters.get('properties_target')
if resource_types and properties_target:
namespaces_iter = filter_properties_target(namespaces_iter,
resource_types,
properties_target)
has_prev_data = False
has_more_data = False
if paginate:
namespaces = list(itertools.islice(namespaces_iter, request_size))
# first and middle page condition
if len(namespaces) > page_size:
namespaces.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif sort_dir == 'desc' and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
else:
namespaces = list(namespaces_iter)
namespaces = [Namespace(namespace) for namespace in namespaces]
return namespaces, has_more_data, has_prev_data | [
"def",
"metadefs_namespace_list",
"(",
"request",
",",
"filters",
"=",
"None",
",",
"sort_dir",
"=",
"'asc'",
",",
"sort_key",
"=",
"'namespace'",
",",
"marker",
"=",
"None",
",",
"paginate",
"=",
"False",
")",
":",
"# Listing namespaces requires the v2 API. If no... | Retrieve a listing of Namespaces
:param paginate: If true will perform pagination based on settings.
:param marker: Specifies the namespace of the last-seen namespace.
The typical pattern of limit and marker is to make an
initial limited request and then to use the last
namespace from the response as the marker parameter
in a subsequent limited request. With paginate, limit
is automatically set.
:param sort_dir: The sort direction ('asc' or 'desc').
:param sort_key: The field to sort on (for example, 'created_at'). Default
is namespace. The way base namespaces are loaded into glance
typically at first deployment is done in a single transaction
giving them a potentially unpredictable sort result when using
create_at.
:param filters: specifies addition fields to filter on such as
resource_types.
:returns A tuple of three values:
1) Current page results
2) A boolean of whether or not there are previous page(s).
3) A boolean of whether or not there are more page(s). | [
"Retrieve",
"a",
"listing",
"of",
"Namespaces"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L668-L751 |
235,054 | openstack/horizon | horizon/utils/file_discovery.py | discover_files | def discover_files(base_path, sub_path='', ext='', trim_base_path=False):
"""Discovers all files with certain extension in given paths."""
file_list = []
for root, dirs, files in walk(path.join(base_path, sub_path)):
if trim_base_path:
root = path.relpath(root, base_path)
file_list.extend([path.join(root, file_name)
for file_name in files
if file_name.endswith(ext)])
return sorted(file_list) | python | def discover_files(base_path, sub_path='', ext='', trim_base_path=False):
file_list = []
for root, dirs, files in walk(path.join(base_path, sub_path)):
if trim_base_path:
root = path.relpath(root, base_path)
file_list.extend([path.join(root, file_name)
for file_name in files
if file_name.endswith(ext)])
return sorted(file_list) | [
"def",
"discover_files",
"(",
"base_path",
",",
"sub_path",
"=",
"''",
",",
"ext",
"=",
"''",
",",
"trim_base_path",
"=",
"False",
")",
":",
"file_list",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"walk",
"(",
"path",
".",
"join",... | Discovers all files with certain extension in given paths. | [
"Discovers",
"all",
"files",
"with",
"certain",
"extension",
"in",
"given",
"paths",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L25-L34 |
235,055 | openstack/horizon | horizon/utils/file_discovery.py | sort_js_files | def sort_js_files(js_files):
"""Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be listed in the below order:
- First, all the that defines the other application's angular module.
Those files have extension of `.module.js`. The order among them is
not significant.
- Followed by all other source code files. The order among them
is not significant.
* mocks: mock files provide mock data/services for tests. They have
extension of `.mock.js`. The order among them is not significant.
* specs: spec files for testing. They have extension of `.spec.js`.
The order among them is not significant.
"""
modules = [f for f in js_files if f.endswith(MODULE_EXT)]
mocks = [f for f in js_files if f.endswith(MOCK_EXT)]
specs = [f for f in js_files if f.endswith(SPEC_EXT)]
other_sources = [f for f in js_files
if (not f.endswith(MODULE_EXT) and
not f.endswith(MOCK_EXT) and
not f.endswith(SPEC_EXT))]
sources = modules + other_sources
return sources, mocks, specs | python | def sort_js_files(js_files):
modules = [f for f in js_files if f.endswith(MODULE_EXT)]
mocks = [f for f in js_files if f.endswith(MOCK_EXT)]
specs = [f for f in js_files if f.endswith(SPEC_EXT)]
other_sources = [f for f in js_files
if (not f.endswith(MODULE_EXT) and
not f.endswith(MOCK_EXT) and
not f.endswith(SPEC_EXT))]
sources = modules + other_sources
return sources, mocks, specs | [
"def",
"sort_js_files",
"(",
"js_files",
")",
":",
"modules",
"=",
"[",
"f",
"for",
"f",
"in",
"js_files",
"if",
"f",
".",
"endswith",
"(",
"MODULE_EXT",
")",
"]",
"mocks",
"=",
"[",
"f",
"for",
"f",
"in",
"js_files",
"if",
"f",
".",
"endswith",
"(... | Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be listed in the below order:
- First, all the that defines the other application's angular module.
Those files have extension of `.module.js`. The order among them is
not significant.
- Followed by all other source code files. The order among them
is not significant.
* mocks: mock files provide mock data/services for tests. They have
extension of `.mock.js`. The order among them is not significant.
* specs: spec files for testing. They have extension of `.spec.js`.
The order among them is not significant. | [
"Sorts",
"JavaScript",
"files",
"in",
"js_files",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L37-L72 |
235,056 | openstack/horizon | horizon/utils/file_discovery.py | discover_static_files | def discover_static_files(base_path, sub_path=''):
"""Discovers static files in given paths.
It returns JavaScript sources, mocks, specs and HTML templates,
all grouped in lists.
"""
js_files = discover_files(base_path, sub_path=sub_path,
ext='.js', trim_base_path=True)
sources, mocks, specs = sort_js_files(js_files)
html_files = discover_files(base_path, sub_path=sub_path,
ext='.html', trim_base_path=True)
p = path.join(base_path, sub_path)
_log(sources, 'JavaScript source', p)
_log(mocks, 'JavaScript mock', p)
_log(specs, 'JavaScript spec', p)
_log(html_files, 'HTML template', p)
return sources, mocks, specs, html_files | python | def discover_static_files(base_path, sub_path=''):
js_files = discover_files(base_path, sub_path=sub_path,
ext='.js', trim_base_path=True)
sources, mocks, specs = sort_js_files(js_files)
html_files = discover_files(base_path, sub_path=sub_path,
ext='.html', trim_base_path=True)
p = path.join(base_path, sub_path)
_log(sources, 'JavaScript source', p)
_log(mocks, 'JavaScript mock', p)
_log(specs, 'JavaScript spec', p)
_log(html_files, 'HTML template', p)
return sources, mocks, specs, html_files | [
"def",
"discover_static_files",
"(",
"base_path",
",",
"sub_path",
"=",
"''",
")",
":",
"js_files",
"=",
"discover_files",
"(",
"base_path",
",",
"sub_path",
"=",
"sub_path",
",",
"ext",
"=",
"'.js'",
",",
"trim_base_path",
"=",
"True",
")",
"sources",
",",
... | Discovers static files in given paths.
It returns JavaScript sources, mocks, specs and HTML templates,
all grouped in lists. | [
"Discovers",
"static",
"files",
"in",
"given",
"paths",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L75-L93 |
235,057 | openstack/horizon | horizon/utils/file_discovery.py | _log | def _log(file_list, list_name, in_path):
"""Logs result at debug level"""
file_names = '\n'.join(file_list)
LOG.debug("\nDiscovered %(size)d %(name)s file(s) in %(path)s:\n"
"%(files)s\n",
{'size': len(file_list), 'name': list_name, 'path': in_path,
'files': file_names}) | python | def _log(file_list, list_name, in_path):
file_names = '\n'.join(file_list)
LOG.debug("\nDiscovered %(size)d %(name)s file(s) in %(path)s:\n"
"%(files)s\n",
{'size': len(file_list), 'name': list_name, 'path': in_path,
'files': file_names}) | [
"def",
"_log",
"(",
"file_list",
",",
"list_name",
",",
"in_path",
")",
":",
"file_names",
"=",
"'\\n'",
".",
"join",
"(",
"file_list",
")",
"LOG",
".",
"debug",
"(",
"\"\\nDiscovered %(size)d %(name)s file(s) in %(path)s:\\n\"",
"\"%(files)s\\n\"",
",",
"{",
"'si... | Logs result at debug level | [
"Logs",
"result",
"at",
"debug",
"level"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L110-L116 |
235,058 | openstack/horizon | horizon/browsers/base.py | ResourceBrowser.set_tables | def set_tables(self, tables):
"""Sets the table instances on the browser.
``tables`` argument specifies tables to be set.
It is a dictionary mapping table names to table instances
(as constructed by MultiTableView).
"""
self.navigation_table = tables[self.navigation_table_class._meta.name]
self.content_table = tables[self.content_table_class._meta.name]
navigation_item = self.kwargs.get(self.navigation_kwarg_name)
content_path = self.kwargs.get(self.content_kwarg_name)
if self.has_breadcrumb:
self.prepare_breadcrumb(tables, navigation_item, content_path) | python | def set_tables(self, tables):
self.navigation_table = tables[self.navigation_table_class._meta.name]
self.content_table = tables[self.content_table_class._meta.name]
navigation_item = self.kwargs.get(self.navigation_kwarg_name)
content_path = self.kwargs.get(self.content_kwarg_name)
if self.has_breadcrumb:
self.prepare_breadcrumb(tables, navigation_item, content_path) | [
"def",
"set_tables",
"(",
"self",
",",
"tables",
")",
":",
"self",
".",
"navigation_table",
"=",
"tables",
"[",
"self",
".",
"navigation_table_class",
".",
"_meta",
".",
"name",
"]",
"self",
".",
"content_table",
"=",
"tables",
"[",
"self",
".",
"content_t... | Sets the table instances on the browser.
``tables`` argument specifies tables to be set.
It is a dictionary mapping table names to table instances
(as constructed by MultiTableView). | [
"Sets",
"the",
"table",
"instances",
"on",
"the",
"browser",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/browsers/base.py#L121-L133 |
235,059 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.get_account_history | def get_account_history(self, account_id, **kwargs):
""" List account activity. Account activity either increases or
decreases your account balance.
Entry type indicates the reason for the account change.
* transfer: Funds moved to/from Coinbase to cbpro
* match: Funds moved as a result of a trade
* fee: Fee as a result of a trade
* rebate: Fee rebate as per our fee schedule
If an entry is the result of a trade (match, fee), the details
field will contain additional information about the trade.
Args:
account_id (str): Account id to get history of.
kwargs (dict): Additional HTTP request parameters.
Returns:
list: History information for the account. Example::
[
{
"id": "100",
"created_at": "2014-11-07T08:19:27.028459Z",
"amount": "0.001",
"balance": "239.669",
"type": "fee",
"details": {
"order_id": "d50ec984-77a8-460a-b958-66f114b0de9b",
"trade_id": "74",
"product_id": "BTC-USD"
}
},
{
...
}
]
"""
endpoint = '/accounts/{}/ledger'.format(account_id)
return self._send_paginated_message(endpoint, params=kwargs) | python | def get_account_history(self, account_id, **kwargs):
endpoint = '/accounts/{}/ledger'.format(account_id)
return self._send_paginated_message(endpoint, params=kwargs) | [
"def",
"get_account_history",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"'/accounts/{}/ledger'",
".",
"format",
"(",
"account_id",
")",
"return",
"self",
".",
"_send_paginated_message",
"(",
"endpoint",
",",
"params",
... | List account activity. Account activity either increases or
decreases your account balance.
Entry type indicates the reason for the account change.
* transfer: Funds moved to/from Coinbase to cbpro
* match: Funds moved as a result of a trade
* fee: Fee as a result of a trade
* rebate: Fee rebate as per our fee schedule
If an entry is the result of a trade (match, fee), the details
field will contain additional information about the trade.
Args:
account_id (str): Account id to get history of.
kwargs (dict): Additional HTTP request parameters.
Returns:
list: History information for the account. Example::
[
{
"id": "100",
"created_at": "2014-11-07T08:19:27.028459Z",
"amount": "0.001",
"balance": "239.669",
"type": "fee",
"details": {
"order_id": "d50ec984-77a8-460a-b958-66f114b0de9b",
"trade_id": "74",
"product_id": "BTC-USD"
}
},
{
...
}
] | [
"List",
"account",
"activity",
".",
"Account",
"activity",
"either",
"increases",
"or",
"decreases",
"your",
"account",
"balance",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L91-L129 |
235,060 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.get_account_holds | def get_account_holds(self, account_id, **kwargs):
""" Get holds on an account.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Holds are placed on an account for active orders or
pending withdraw requests.
As an order is filled, the hold amount is updated. If an order
is canceled, any remaining hold is removed. For a withdraw, once
it is completed, the hold is removed.
The `type` field will indicate why the hold exists. The hold
type is 'order' for holds related to open orders and 'transfer'
for holds related to a withdraw.
The `ref` field contains the id of the order or transfer which
created the hold.
Args:
account_id (str): Account id to get holds of.
kwargs (dict): Additional HTTP request parameters.
Returns:
generator(list): Hold information for the account. Example::
[
{
"id": "82dcd140-c3c7-4507-8de4-2c529cd1a28f",
"account_id": "e0b3f39a-183d-453e-b754-0c13e5bab0b3",
"created_at": "2014-11-06T10:34:47.123456Z",
"updated_at": "2014-11-06T10:40:47.123456Z",
"amount": "4.23",
"type": "order",
"ref": "0a205de4-dd35-4370-a285-fe8fc375a273",
},
{
...
}
]
"""
endpoint = '/accounts/{}/holds'.format(account_id)
return self._send_paginated_message(endpoint, params=kwargs) | python | def get_account_holds(self, account_id, **kwargs):
endpoint = '/accounts/{}/holds'.format(account_id)
return self._send_paginated_message(endpoint, params=kwargs) | [
"def",
"get_account_holds",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"'/accounts/{}/holds'",
".",
"format",
"(",
"account_id",
")",
"return",
"self",
".",
"_send_paginated_message",
"(",
"endpoint",
",",
"params",
"="... | Get holds on an account.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Holds are placed on an account for active orders or
pending withdraw requests.
As an order is filled, the hold amount is updated. If an order
is canceled, any remaining hold is removed. For a withdraw, once
it is completed, the hold is removed.
The `type` field will indicate why the hold exists. The hold
type is 'order' for holds related to open orders and 'transfer'
for holds related to a withdraw.
The `ref` field contains the id of the order or transfer which
created the hold.
Args:
account_id (str): Account id to get holds of.
kwargs (dict): Additional HTTP request parameters.
Returns:
generator(list): Hold information for the account. Example::
[
{
"id": "82dcd140-c3c7-4507-8de4-2c529cd1a28f",
"account_id": "e0b3f39a-183d-453e-b754-0c13e5bab0b3",
"created_at": "2014-11-06T10:34:47.123456Z",
"updated_at": "2014-11-06T10:40:47.123456Z",
"amount": "4.23",
"type": "order",
"ref": "0a205de4-dd35-4370-a285-fe8fc375a273",
},
{
...
}
] | [
"Get",
"holds",
"on",
"an",
"account",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L131-L174 |
235,061 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.buy | def buy(self, product_id, order_type, **kwargs):
"""Place a buy order.
This is included to maintain backwards compatibility with older versions
of cbpro-Python. For maximum support from docstrings and function
signatures see the order type-specific functions place_limit_order,
place_market_order, and place_stop_order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
order_type (str): Order type ('limit', 'market', or 'stop')
**kwargs: Additional arguments can be specified for different order
types.
Returns:
dict: Order details. See `place_order` for example.
"""
return self.place_order(product_id, 'buy', order_type, **kwargs) | python | def buy(self, product_id, order_type, **kwargs):
return self.place_order(product_id, 'buy', order_type, **kwargs) | [
"def",
"buy",
"(",
"self",
",",
"product_id",
",",
"order_type",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"place_order",
"(",
"product_id",
",",
"'buy'",
",",
"order_type",
",",
"*",
"*",
"kwargs",
")"
] | Place a buy order.
This is included to maintain backwards compatibility with older versions
of cbpro-Python. For maximum support from docstrings and function
signatures see the order type-specific functions place_limit_order,
place_market_order, and place_stop_order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
order_type (str): Order type ('limit', 'market', or 'stop')
**kwargs: Additional arguments can be specified for different order
types.
Returns:
dict: Order details. See `place_order` for example. | [
"Place",
"a",
"buy",
"order",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L258-L276 |
235,062 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.sell | def sell(self, product_id, order_type, **kwargs):
"""Place a sell order.
This is included to maintain backwards compatibility with older versions
of cbpro-Python. For maximum support from docstrings and function
signatures see the order type-specific functions place_limit_order,
place_market_order, and place_stop_order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
order_type (str): Order type ('limit', 'market', or 'stop')
**kwargs: Additional arguments can be specified for different order
types.
Returns:
dict: Order details. See `place_order` for example.
"""
return self.place_order(product_id, 'sell', order_type, **kwargs) | python | def sell(self, product_id, order_type, **kwargs):
return self.place_order(product_id, 'sell', order_type, **kwargs) | [
"def",
"sell",
"(",
"self",
",",
"product_id",
",",
"order_type",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"place_order",
"(",
"product_id",
",",
"'sell'",
",",
"order_type",
",",
"*",
"*",
"kwargs",
")"
] | Place a sell order.
This is included to maintain backwards compatibility with older versions
of cbpro-Python. For maximum support from docstrings and function
signatures see the order type-specific functions place_limit_order,
place_market_order, and place_stop_order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
order_type (str): Order type ('limit', 'market', or 'stop')
**kwargs: Additional arguments can be specified for different order
types.
Returns:
dict: Order details. See `place_order` for example. | [
"Place",
"a",
"sell",
"order",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L278-L296 |
235,063 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.place_market_order | def place_market_order(self, product_id, side, size=None, funds=None,
client_oid=None,
stp=None,
overdraft_enabled=None,
funding_amount=None):
""" Place market order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
side (str): Order side ('buy' or 'sell)
size (Optional[Decimal]): Desired amount in crypto. Specify this or
`funds`.
funds (Optional[Decimal]): Desired amount of quote currency to use.
Specify this or `size`.
client_oid (Optional[str]): User-specified Order ID
stp (Optional[str]): Self-trade prevention flag. See `place_order`
for details.
overdraft_enabled (Optional[bool]): If true funding above and
beyond the account balance will be provided by margin, as
necessary.
funding_amount (Optional[Decimal]): Amount of margin funding to be
provided for the order. Mutually exclusive with
`overdraft_enabled`.
Returns:
dict: Order details. See `place_order` for example.
"""
params = {'product_id': product_id,
'side': side,
'order_type': 'market',
'size': size,
'funds': funds,
'client_oid': client_oid,
'stp': stp,
'overdraft_enabled': overdraft_enabled,
'funding_amount': funding_amount}
params = dict((k, v) for k, v in params.items() if v is not None)
return self.place_order(**params) | python | def place_market_order(self, product_id, side, size=None, funds=None,
client_oid=None,
stp=None,
overdraft_enabled=None,
funding_amount=None):
params = {'product_id': product_id,
'side': side,
'order_type': 'market',
'size': size,
'funds': funds,
'client_oid': client_oid,
'stp': stp,
'overdraft_enabled': overdraft_enabled,
'funding_amount': funding_amount}
params = dict((k, v) for k, v in params.items() if v is not None)
return self.place_order(**params) | [
"def",
"place_market_order",
"(",
"self",
",",
"product_id",
",",
"side",
",",
"size",
"=",
"None",
",",
"funds",
"=",
"None",
",",
"client_oid",
"=",
"None",
",",
"stp",
"=",
"None",
",",
"overdraft_enabled",
"=",
"None",
",",
"funding_amount",
"=",
"No... | Place market order.
Args:
product_id (str): Product to order (eg. 'BTC-USD')
side (str): Order side ('buy' or 'sell)
size (Optional[Decimal]): Desired amount in crypto. Specify this or
`funds`.
funds (Optional[Decimal]): Desired amount of quote currency to use.
Specify this or `size`.
client_oid (Optional[str]): User-specified Order ID
stp (Optional[str]): Self-trade prevention flag. See `place_order`
for details.
overdraft_enabled (Optional[bool]): If true funding above and
beyond the account balance will be provided by margin, as
necessary.
funding_amount (Optional[Decimal]): Amount of margin funding to be
provided for the order. Mutually exclusive with
`overdraft_enabled`.
Returns:
dict: Order details. See `place_order` for example. | [
"Place",
"market",
"order",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L354-L393 |
235,064 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.cancel_all | def cancel_all(self, product_id=None):
""" With best effort, cancel all open orders.
Args:
product_id (Optional[str]): Only cancel orders for this
product_id
Returns:
list: A list of ids of the canceled orders. Example::
[
"144c6f8e-713f-4682-8435-5280fbe8b2b4",
"debe4907-95dc-442f-af3b-cec12f42ebda",
"cf7aceee-7b08-4227-a76c-3858144323ab",
"dfc5ae27-cadb-4c0c-beef-8994936fde8a",
"34fecfbf-de33-4273-b2c6-baf8e8948be4"
]
"""
if product_id is not None:
params = {'product_id': product_id}
else:
params = None
return self._send_message('delete', '/orders', params=params) | python | def cancel_all(self, product_id=None):
if product_id is not None:
params = {'product_id': product_id}
else:
params = None
return self._send_message('delete', '/orders', params=params) | [
"def",
"cancel_all",
"(",
"self",
",",
"product_id",
"=",
"None",
")",
":",
"if",
"product_id",
"is",
"not",
"None",
":",
"params",
"=",
"{",
"'product_id'",
":",
"product_id",
"}",
"else",
":",
"params",
"=",
"None",
"return",
"self",
".",
"_send_messag... | With best effort, cancel all open orders.
Args:
product_id (Optional[str]): Only cancel orders for this
product_id
Returns:
list: A list of ids of the canceled orders. Example::
[
"144c6f8e-713f-4682-8435-5280fbe8b2b4",
"debe4907-95dc-442f-af3b-cec12f42ebda",
"cf7aceee-7b08-4227-a76c-3858144323ab",
"dfc5ae27-cadb-4c0c-beef-8994936fde8a",
"34fecfbf-de33-4273-b2c6-baf8e8948be4"
] | [
"With",
"best",
"effort",
"cancel",
"all",
"open",
"orders",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L460-L482 |
235,065 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.get_orders | def get_orders(self, product_id=None, status=None, **kwargs):
""" List your current open orders.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Only open or un-settled orders are returned. As soon as an
order is no longer open and settled, it will no longer appear
in the default request.
Orders which are no longer resting on the order book, will be
marked with the 'done' status. There is a small window between
an order being 'done' and 'settled'. An order is 'settled' when
all of the fills have settled and the remaining holds (if any)
have been removed.
For high-volume trading it is strongly recommended that you
maintain your own list of open orders and use one of the
streaming market data feeds to keep it updated. You should poll
the open orders endpoint once when you start trading to obtain
the current state of any open orders.
Args:
product_id (Optional[str]): Only list orders for this
product
status (Optional[list/str]): Limit list of orders to
this status or statuses. Passing 'all' returns orders
of all statuses.
** Options: 'open', 'pending', 'active', 'done',
'settled'
** default: ['open', 'pending', 'active']
Returns:
list: Containing information on orders. Example::
[
{
"id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
"price": "0.10000000",
"size": "0.01000000",
"product_id": "BTC-USD",
"side": "buy",
"stp": "dc",
"type": "limit",
"time_in_force": "GTC",
"post_only": false,
"created_at": "2016-12-08T20:02:28.53864Z",
"fill_fees": "0.0000000000000000",
"filled_size": "0.00000000",
"executed_value": "0.0000000000000000",
"status": "open",
"settled": false
},
{
...
}
]
"""
params = kwargs
if product_id is not None:
params['product_id'] = product_id
if status is not None:
params['status'] = status
return self._send_paginated_message('/orders', params=params) | python | def get_orders(self, product_id=None, status=None, **kwargs):
params = kwargs
if product_id is not None:
params['product_id'] = product_id
if status is not None:
params['status'] = status
return self._send_paginated_message('/orders', params=params) | [
"def",
"get_orders",
"(",
"self",
",",
"product_id",
"=",
"None",
",",
"status",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
"if",
"product_id",
"is",
"not",
"None",
":",
"params",
"[",
"'product_id'",
"]",
"=",
"product_id... | List your current open orders.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Only open or un-settled orders are returned. As soon as an
order is no longer open and settled, it will no longer appear
in the default request.
Orders which are no longer resting on the order book, will be
marked with the 'done' status. There is a small window between
an order being 'done' and 'settled'. An order is 'settled' when
all of the fills have settled and the remaining holds (if any)
have been removed.
For high-volume trading it is strongly recommended that you
maintain your own list of open orders and use one of the
streaming market data feeds to keep it updated. You should poll
the open orders endpoint once when you start trading to obtain
the current state of any open orders.
Args:
product_id (Optional[str]): Only list orders for this
product
status (Optional[list/str]): Limit list of orders to
this status or statuses. Passing 'all' returns orders
of all statuses.
** Options: 'open', 'pending', 'active', 'done',
'settled'
** default: ['open', 'pending', 'active']
Returns:
list: Containing information on orders. Example::
[
{
"id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
"price": "0.10000000",
"size": "0.01000000",
"product_id": "BTC-USD",
"side": "buy",
"stp": "dc",
"type": "limit",
"time_in_force": "GTC",
"post_only": false,
"created_at": "2016-12-08T20:02:28.53864Z",
"fill_fees": "0.0000000000000000",
"filled_size": "0.00000000",
"executed_value": "0.0000000000000000",
"status": "open",
"settled": false
},
{
...
}
] | [
"List",
"your",
"current",
"open",
"orders",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L519-L582 |
235,066 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.get_fundings | def get_fundings(self, status=None, **kwargs):
""" Every order placed with a margin profile that draws funding
will create a funding record.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Args:
status (list/str): Limit funding records to these statuses.
** Options: 'outstanding', 'settled', 'rejected'
kwargs (dict): Additional HTTP request parameters.
Returns:
list: Containing information on margin funding. Example::
[
{
"id": "b93d26cd-7193-4c8d-bfcc-446b2fe18f71",
"order_id": "b93d26cd-7193-4c8d-bfcc-446b2fe18f71",
"profile_id": "d881e5a6-58eb-47cd-b8e2-8d9f2e3ec6f6",
"amount": "1057.6519956381537500",
"status": "settled",
"created_at": "2017-03-17T23:46:16.663397Z",
"currency": "USD",
"repaid_amount": "1057.6519956381537500",
"default_amount": "0",
"repaid_default": false
},
{
...
}
]
"""
params = {}
if status is not None:
params['status'] = status
params.update(kwargs)
return self._send_paginated_message('/funding', params=params) | python | def get_fundings(self, status=None, **kwargs):
params = {}
if status is not None:
params['status'] = status
params.update(kwargs)
return self._send_paginated_message('/funding', params=params) | [
"def",
"get_fundings",
"(",
"self",
",",
"status",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"if",
"status",
"is",
"not",
"None",
":",
"params",
"[",
"'status'",
"]",
"=",
"status",
"params",
".",
"update",
"(",
"kwar... | Every order placed with a margin profile that draws funding
will create a funding record.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Args:
status (list/str): Limit funding records to these statuses.
** Options: 'outstanding', 'settled', 'rejected'
kwargs (dict): Additional HTTP request parameters.
Returns:
list: Containing information on margin funding. Example::
[
{
"id": "b93d26cd-7193-4c8d-bfcc-446b2fe18f71",
"order_id": "b93d26cd-7193-4c8d-bfcc-446b2fe18f71",
"profile_id": "d881e5a6-58eb-47cd-b8e2-8d9f2e3ec6f6",
"amount": "1057.6519956381537500",
"status": "settled",
"created_at": "2017-03-17T23:46:16.663397Z",
"currency": "USD",
"repaid_amount": "1057.6519956381537500",
"default_amount": "0",
"repaid_default": false
},
{
...
}
] | [
"Every",
"order",
"placed",
"with",
"a",
"margin",
"profile",
"that",
"draws",
"funding",
"will",
"create",
"a",
"funding",
"record",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L642-L679 |
235,067 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.repay_funding | def repay_funding(self, amount, currency):
""" Repay funding. Repays the older funding records first.
Args:
amount (int): Amount of currency to repay
currency (str): The currency, example USD
Returns:
Not specified by cbpro.
"""
params = {
'amount': amount,
'currency': currency # example: USD
}
return self._send_message('post', '/funding/repay',
data=json.dumps(params)) | python | def repay_funding(self, amount, currency):
params = {
'amount': amount,
'currency': currency # example: USD
}
return self._send_message('post', '/funding/repay',
data=json.dumps(params)) | [
"def",
"repay_funding",
"(",
"self",
",",
"amount",
",",
"currency",
")",
":",
"params",
"=",
"{",
"'amount'",
":",
"amount",
",",
"'currency'",
":",
"currency",
"# example: USD",
"}",
"return",
"self",
".",
"_send_message",
"(",
"'post'",
",",
"'/funding/re... | Repay funding. Repays the older funding records first.
Args:
amount (int): Amount of currency to repay
currency (str): The currency, example USD
Returns:
Not specified by cbpro. | [
"Repay",
"funding",
".",
"Repays",
"the",
"older",
"funding",
"records",
"first",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L681-L697 |
235,068 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.margin_transfer | def margin_transfer(self, margin_profile_id, transfer_type, currency,
amount):
""" Transfer funds between your standard profile and a margin profile.
Args:
margin_profile_id (str): Margin profile ID to withdraw or deposit
from.
transfer_type (str): 'deposit' or 'withdraw'
currency (str): Currency to transfer (eg. 'USD')
amount (Decimal): Amount to transfer
Returns:
dict: Transfer details. Example::
{
"created_at": "2017-01-25T19:06:23.415126Z",
"id": "80bc6b74-8b1f-4c60-a089-c61f9810d4ab",
"user_id": "521c20b3d4ab09621f000011",
"profile_id": "cda95996-ac59-45a3-a42e-30daeb061867",
"margin_profile_id": "45fa9e3b-00ba-4631-b907-8a98cbdf21be",
"type": "deposit",
"amount": "2",
"currency": "USD",
"account_id": "23035fc7-0707-4b59-b0d2-95d0c035f8f5",
"margin_account_id": "e1d9862c-a259-4e83-96cd-376352a9d24d",
"margin_product_id": "BTC-USD",
"status": "completed",
"nonce": 25
}
"""
params = {'margin_profile_id': margin_profile_id,
'type': transfer_type,
'currency': currency, # example: USD
'amount': amount}
return self._send_message('post', '/profiles/margin-transfer',
data=json.dumps(params)) | python | def margin_transfer(self, margin_profile_id, transfer_type, currency,
amount):
params = {'margin_profile_id': margin_profile_id,
'type': transfer_type,
'currency': currency, # example: USD
'amount': amount}
return self._send_message('post', '/profiles/margin-transfer',
data=json.dumps(params)) | [
"def",
"margin_transfer",
"(",
"self",
",",
"margin_profile_id",
",",
"transfer_type",
",",
"currency",
",",
"amount",
")",
":",
"params",
"=",
"{",
"'margin_profile_id'",
":",
"margin_profile_id",
",",
"'type'",
":",
"transfer_type",
",",
"'currency'",
":",
"cu... | Transfer funds between your standard profile and a margin profile.
Args:
margin_profile_id (str): Margin profile ID to withdraw or deposit
from.
transfer_type (str): 'deposit' or 'withdraw'
currency (str): Currency to transfer (eg. 'USD')
amount (Decimal): Amount to transfer
Returns:
dict: Transfer details. Example::
{
"created_at": "2017-01-25T19:06:23.415126Z",
"id": "80bc6b74-8b1f-4c60-a089-c61f9810d4ab",
"user_id": "521c20b3d4ab09621f000011",
"profile_id": "cda95996-ac59-45a3-a42e-30daeb061867",
"margin_profile_id": "45fa9e3b-00ba-4631-b907-8a98cbdf21be",
"type": "deposit",
"amount": "2",
"currency": "USD",
"account_id": "23035fc7-0707-4b59-b0d2-95d0c035f8f5",
"margin_account_id": "e1d9862c-a259-4e83-96cd-376352a9d24d",
"margin_product_id": "BTC-USD",
"status": "completed",
"nonce": 25
} | [
"Transfer",
"funds",
"between",
"your",
"standard",
"profile",
"and",
"a",
"margin",
"profile",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L699-L734 |
235,069 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.close_position | def close_position(self, repay_only):
""" Close position.
Args:
repay_only (bool): Undocumented by cbpro.
Returns:
Undocumented
"""
params = {'repay_only': repay_only}
return self._send_message('post', '/position/close',
data=json.dumps(params)) | python | def close_position(self, repay_only):
params = {'repay_only': repay_only}
return self._send_message('post', '/position/close',
data=json.dumps(params)) | [
"def",
"close_position",
"(",
"self",
",",
"repay_only",
")",
":",
"params",
"=",
"{",
"'repay_only'",
":",
"repay_only",
"}",
"return",
"self",
".",
"_send_message",
"(",
"'post'",
",",
"'/position/close'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"pa... | Close position.
Args:
repay_only (bool): Undocumented by cbpro.
Returns:
Undocumented | [
"Close",
"position",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L745-L757 |
235,070 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.withdraw | def withdraw(self, amount, currency, payment_method_id):
""" Withdraw funds to a payment method.
See AuthenticatedClient.get_payment_methods() to receive
information regarding payment methods.
Args:
amount (Decimal): The amount to withdraw.
currency (str): Currency type (eg. 'BTC')
payment_method_id (str): ID of the payment method.
Returns:
dict: Withdraw details. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount": "10.00",
"currency": "USD",
"payout_at": "2016-08-20T00:31:09Z"
}
"""
params = {'amount': amount,
'currency': currency,
'payment_method_id': payment_method_id}
return self._send_message('post', '/withdrawals/payment-method',
data=json.dumps(params)) | python | def withdraw(self, amount, currency, payment_method_id):
params = {'amount': amount,
'currency': currency,
'payment_method_id': payment_method_id}
return self._send_message('post', '/withdrawals/payment-method',
data=json.dumps(params)) | [
"def",
"withdraw",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"payment_method_id",
")",
":",
"params",
"=",
"{",
"'amount'",
":",
"amount",
",",
"'currency'",
":",
"currency",
",",
"'payment_method_id'",
":",
"payment_method_id",
"}",
"return",
"self",
... | Withdraw funds to a payment method.
See AuthenticatedClient.get_payment_methods() to receive
information regarding payment methods.
Args:
amount (Decimal): The amount to withdraw.
currency (str): Currency type (eg. 'BTC')
payment_method_id (str): ID of the payment method.
Returns:
dict: Withdraw details. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount": "10.00",
"currency": "USD",
"payout_at": "2016-08-20T00:31:09Z"
} | [
"Withdraw",
"funds",
"to",
"a",
"payment",
"method",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L816-L841 |
235,071 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.coinbase_withdraw | def coinbase_withdraw(self, amount, currency, coinbase_account_id):
""" Withdraw funds to a coinbase account.
You can move funds between your Coinbase accounts and your cbpro
trading accounts within your daily limits. Moving funds between
Coinbase and cbpro is instant and free.
See AuthenticatedClient.get_coinbase_accounts() to receive
information regarding your coinbase_accounts.
Args:
amount (Decimal): The amount to withdraw.
currency (str): The type of currency (eg. 'BTC')
coinbase_account_id (str): ID of the coinbase account.
Returns:
dict: Information about the deposit. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount":"10.00",
"currency": "BTC",
}
"""
params = {'amount': amount,
'currency': currency,
'coinbase_account_id': coinbase_account_id}
return self._send_message('post', '/withdrawals/coinbase-account',
data=json.dumps(params)) | python | def coinbase_withdraw(self, amount, currency, coinbase_account_id):
params = {'amount': amount,
'currency': currency,
'coinbase_account_id': coinbase_account_id}
return self._send_message('post', '/withdrawals/coinbase-account',
data=json.dumps(params)) | [
"def",
"coinbase_withdraw",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"coinbase_account_id",
")",
":",
"params",
"=",
"{",
"'amount'",
":",
"amount",
",",
"'currency'",
":",
"currency",
",",
"'coinbase_account_id'",
":",
"coinbase_account_id",
"}",
"retu... | Withdraw funds to a coinbase account.
You can move funds between your Coinbase accounts and your cbpro
trading accounts within your daily limits. Moving funds between
Coinbase and cbpro is instant and free.
See AuthenticatedClient.get_coinbase_accounts() to receive
information regarding your coinbase_accounts.
Args:
amount (Decimal): The amount to withdraw.
currency (str): The type of currency (eg. 'BTC')
coinbase_account_id (str): ID of the coinbase account.
Returns:
dict: Information about the deposit. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount":"10.00",
"currency": "BTC",
} | [
"Withdraw",
"funds",
"to",
"a",
"coinbase",
"account",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L843-L871 |
235,072 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.crypto_withdraw | def crypto_withdraw(self, amount, currency, crypto_address):
""" Withdraw funds to a crypto address.
Args:
amount (Decimal): The amount to withdraw
currency (str): The type of currency (eg. 'BTC')
crypto_address (str): Crypto address to withdraw to.
Returns:
dict: Withdraw details. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount":"10.00",
"currency": "BTC",
}
"""
params = {'amount': amount,
'currency': currency,
'crypto_address': crypto_address}
return self._send_message('post', '/withdrawals/crypto',
data=json.dumps(params)) | python | def crypto_withdraw(self, amount, currency, crypto_address):
params = {'amount': amount,
'currency': currency,
'crypto_address': crypto_address}
return self._send_message('post', '/withdrawals/crypto',
data=json.dumps(params)) | [
"def",
"crypto_withdraw",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"crypto_address",
")",
":",
"params",
"=",
"{",
"'amount'",
":",
"amount",
",",
"'currency'",
":",
"currency",
",",
"'crypto_address'",
":",
"crypto_address",
"}",
"return",
"self",
... | Withdraw funds to a crypto address.
Args:
amount (Decimal): The amount to withdraw
currency (str): The type of currency (eg. 'BTC')
crypto_address (str): Crypto address to withdraw to.
Returns:
dict: Withdraw details. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount":"10.00",
"currency": "BTC",
} | [
"Withdraw",
"funds",
"to",
"a",
"crypto",
"address",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L873-L894 |
235,073 | danpaquin/coinbasepro-python | cbpro/authenticated_client.py | AuthenticatedClient.create_report | def create_report(self, report_type, start_date, end_date, product_id=None,
account_id=None, report_format='pdf', email=None):
""" Create report of historic information about your account.
The report will be generated when resources are available. Report status
can be queried via `get_report(report_id)`.
Args:
report_type (str): 'fills' or 'account'
start_date (str): Starting date for the report in ISO 8601
end_date (str): Ending date for the report in ISO 8601
product_id (Optional[str]): ID of the product to generate a fills
report for. Required if account_type is 'fills'
account_id (Optional[str]): ID of the account to generate an account
report for. Required if report_type is 'account'.
report_format (Optional[str]): 'pdf' or 'csv'. Default is 'pdf'.
email (Optional[str]): Email address to send the report to.
Returns:
dict: Report details. Example::
{
"id": "0428b97b-bec1-429e-a94c-59232926778d",
"type": "fills",
"status": "pending",
"created_at": "2015-01-06T10:34:47.000Z",
"completed_at": undefined,
"expires_at": "2015-01-13T10:35:47.000Z",
"file_url": undefined,
"params": {
"start_date": "2014-11-01T00:00:00.000Z",
"end_date": "2014-11-30T23:59:59.000Z"
}
}
"""
params = {'type': report_type,
'start_date': start_date,
'end_date': end_date,
'format': report_format}
if product_id is not None:
params['product_id'] = product_id
if account_id is not None:
params['account_id'] = account_id
if email is not None:
params['email'] = email
return self._send_message('post', '/reports',
data=json.dumps(params)) | python | def create_report(self, report_type, start_date, end_date, product_id=None,
account_id=None, report_format='pdf', email=None):
params = {'type': report_type,
'start_date': start_date,
'end_date': end_date,
'format': report_format}
if product_id is not None:
params['product_id'] = product_id
if account_id is not None:
params['account_id'] = account_id
if email is not None:
params['email'] = email
return self._send_message('post', '/reports',
data=json.dumps(params)) | [
"def",
"create_report",
"(",
"self",
",",
"report_type",
",",
"start_date",
",",
"end_date",
",",
"product_id",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"report_format",
"=",
"'pdf'",
",",
"email",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'ty... | Create report of historic information about your account.
The report will be generated when resources are available. Report status
can be queried via `get_report(report_id)`.
Args:
report_type (str): 'fills' or 'account'
start_date (str): Starting date for the report in ISO 8601
end_date (str): Ending date for the report in ISO 8601
product_id (Optional[str]): ID of the product to generate a fills
report for. Required if account_type is 'fills'
account_id (Optional[str]): ID of the account to generate an account
report for. Required if report_type is 'account'.
report_format (Optional[str]): 'pdf' or 'csv'. Default is 'pdf'.
email (Optional[str]): Email address to send the report to.
Returns:
dict: Report details. Example::
{
"id": "0428b97b-bec1-429e-a94c-59232926778d",
"type": "fills",
"status": "pending",
"created_at": "2015-01-06T10:34:47.000Z",
"completed_at": undefined,
"expires_at": "2015-01-13T10:35:47.000Z",
"file_url": undefined,
"params": {
"start_date": "2014-11-01T00:00:00.000Z",
"end_date": "2014-11-30T23:59:59.000Z"
}
} | [
"Create",
"report",
"of",
"historic",
"information",
"about",
"your",
"account",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L914-L961 |
235,074 | danpaquin/coinbasepro-python | cbpro/public_client.py | PublicClient.get_product_order_book | def get_product_order_book(self, product_id, level=1):
"""Get a list of open orders for a product.
The amount of detail shown can be customized with the `level`
parameter:
* 1: Only the best bid and ask
* 2: Top 50 bids and asks (aggregated)
* 3: Full order book (non aggregated)
Level 1 and Level 2 are recommended for polling. For the most
up-to-date data, consider using the websocket stream.
**Caution**: Level 3 is only recommended for users wishing to
maintain a full real-time order book using the websocket
stream. Abuse of Level 3 via polling will cause your access to
be limited or blocked.
Args:
product_id (str): Product
level (Optional[int]): Order book level (1, 2, or 3).
Default is 1.
Returns:
dict: Order book. Example for level 1::
{
"sequence": "3",
"bids": [
[ price, size, num-orders ],
],
"asks": [
[ price, size, num-orders ],
]
}
"""
params = {'level': level}
return self._send_message('get',
'/products/{}/book'.format(product_id),
params=params) | python | def get_product_order_book(self, product_id, level=1):
params = {'level': level}
return self._send_message('get',
'/products/{}/book'.format(product_id),
params=params) | [
"def",
"get_product_order_book",
"(",
"self",
",",
"product_id",
",",
"level",
"=",
"1",
")",
":",
"params",
"=",
"{",
"'level'",
":",
"level",
"}",
"return",
"self",
".",
"_send_message",
"(",
"'get'",
",",
"'/products/{}/book'",
".",
"format",
"(",
"prod... | Get a list of open orders for a product.
The amount of detail shown can be customized with the `level`
parameter:
* 1: Only the best bid and ask
* 2: Top 50 bids and asks (aggregated)
* 3: Full order book (non aggregated)
Level 1 and Level 2 are recommended for polling. For the most
up-to-date data, consider using the websocket stream.
**Caution**: Level 3 is only recommended for users wishing to
maintain a full real-time order book using the websocket
stream. Abuse of Level 3 via polling will cause your access to
be limited or blocked.
Args:
product_id (str): Product
level (Optional[int]): Order book level (1, 2, or 3).
Default is 1.
Returns:
dict: Order book. Example for level 1::
{
"sequence": "3",
"bids": [
[ price, size, num-orders ],
],
"asks": [
[ price, size, num-orders ],
]
} | [
"Get",
"a",
"list",
"of",
"open",
"orders",
"for",
"a",
"product",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/public_client.py#L52-L90 |
235,075 | danpaquin/coinbasepro-python | cbpro/public_client.py | PublicClient.get_product_trades | def get_product_trades(self, product_id, before='', after='', limit=None, result=None):
"""List the latest trades for a product.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Args:
product_id (str): Product
before (Optional[str]): start time in ISO 8601
after (Optional[str]): end time in ISO 8601
limit (Optional[int]): the desired number of trades (can be more than 100,
automatically paginated)
results (Optional[list]): list of results that is used for the pagination
Returns:
list: Latest trades. Example::
[{
"time": "2014-11-07T22:19:28.578544Z",
"trade_id": 74,
"price": "10.00000000",
"size": "0.01000000",
"side": "buy"
}, {
"time": "2014-11-07T01:08:43.642366Z",
"trade_id": 73,
"price": "100.00000000",
"size": "0.01000000",
"side": "sell"
}]
"""
return self._send_paginated_message('/products/{}/trades'
.format(product_id)) | python | def get_product_trades(self, product_id, before='', after='', limit=None, result=None):
return self._send_paginated_message('/products/{}/trades'
.format(product_id)) | [
"def",
"get_product_trades",
"(",
"self",
",",
"product_id",
",",
"before",
"=",
"''",
",",
"after",
"=",
"''",
",",
"limit",
"=",
"None",
",",
"result",
"=",
"None",
")",
":",
"return",
"self",
".",
"_send_paginated_message",
"(",
"'/products/{}/trades'",
... | List the latest trades for a product.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Args:
product_id (str): Product
before (Optional[str]): start time in ISO 8601
after (Optional[str]): end time in ISO 8601
limit (Optional[int]): the desired number of trades (can be more than 100,
automatically paginated)
results (Optional[list]): list of results that is used for the pagination
Returns:
list: Latest trades. Example::
[{
"time": "2014-11-07T22:19:28.578544Z",
"trade_id": 74,
"price": "10.00000000",
"size": "0.01000000",
"side": "buy"
}, {
"time": "2014-11-07T01:08:43.642366Z",
"trade_id": 73,
"price": "100.00000000",
"size": "0.01000000",
"side": "sell"
}] | [
"List",
"the",
"latest",
"trades",
"for",
"a",
"product",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/public_client.py#L117-L147 |
235,076 | danpaquin/coinbasepro-python | cbpro/public_client.py | PublicClient.get_product_historic_rates | def get_product_historic_rates(self, product_id, start=None, end=None,
granularity=None):
"""Historic rates for a product.
Rates are returned in grouped buckets based on requested
`granularity`. If start, end, and granularity aren't provided,
the exchange will assume some (currently unknown) default values.
Historical rate data may be incomplete. No data is published for
intervals where there are no ticks.
**Caution**: Historical rates should not be polled frequently.
If you need real-time information, use the trade and book
endpoints along with the websocket feed.
The maximum number of data points for a single request is 200
candles. If your selection of start/end time and granularity
will result in more than 200 data points, your request will be
rejected. If you wish to retrieve fine granularity data over a
larger time range, you will need to make multiple requests with
new start/end ranges.
Args:
product_id (str): Product
start (Optional[str]): Start time in ISO 8601
end (Optional[str]): End time in ISO 8601
granularity (Optional[int]): Desired time slice in seconds
Returns:
list: Historic candle data. Example:
[
[ time, low, high, open, close, volume ],
[ 1415398768, 0.32, 4.2, 0.35, 4.2, 12.3 ],
...
]
"""
params = {}
if start is not None:
params['start'] = start
if end is not None:
params['end'] = end
if granularity is not None:
acceptedGrans = [60, 300, 900, 3600, 21600, 86400]
if granularity not in acceptedGrans:
raise ValueError( 'Specified granularity is {}, must be in approved values: {}'.format(
granularity, acceptedGrans) )
params['granularity'] = granularity
return self._send_message('get',
'/products/{}/candles'.format(product_id),
params=params) | python | def get_product_historic_rates(self, product_id, start=None, end=None,
granularity=None):
params = {}
if start is not None:
params['start'] = start
if end is not None:
params['end'] = end
if granularity is not None:
acceptedGrans = [60, 300, 900, 3600, 21600, 86400]
if granularity not in acceptedGrans:
raise ValueError( 'Specified granularity is {}, must be in approved values: {}'.format(
granularity, acceptedGrans) )
params['granularity'] = granularity
return self._send_message('get',
'/products/{}/candles'.format(product_id),
params=params) | [
"def",
"get_product_historic_rates",
"(",
"self",
",",
"product_id",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"granularity",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"start",
"is",
"not",
"None",
":",
"params",
"[",
"'start... | Historic rates for a product.
Rates are returned in grouped buckets based on requested
`granularity`. If start, end, and granularity aren't provided,
the exchange will assume some (currently unknown) default values.
Historical rate data may be incomplete. No data is published for
intervals where there are no ticks.
**Caution**: Historical rates should not be polled frequently.
If you need real-time information, use the trade and book
endpoints along with the websocket feed.
The maximum number of data points for a single request is 200
candles. If your selection of start/end time and granularity
will result in more than 200 data points, your request will be
rejected. If you wish to retrieve fine granularity data over a
larger time range, you will need to make multiple requests with
new start/end ranges.
Args:
product_id (str): Product
start (Optional[str]): Start time in ISO 8601
end (Optional[str]): End time in ISO 8601
granularity (Optional[int]): Desired time slice in seconds
Returns:
list: Historic candle data. Example:
[
[ time, low, high, open, close, volume ],
[ 1415398768, 0.32, 4.2, 0.35, 4.2, 12.3 ],
...
] | [
"Historic",
"rates",
"for",
"a",
"product",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/public_client.py#L149-L200 |
235,077 | danpaquin/coinbasepro-python | cbpro/public_client.py | PublicClient._send_message | def _send_message(self, method, endpoint, params=None, data=None):
"""Send API request.
Args:
method (str): HTTP method (get, post, delete, etc.)
endpoint (str): Endpoint (to be added to base URL)
params (Optional[dict]): HTTP request parameters
data (Optional[str]): JSON-encoded string payload for POST
Returns:
dict/list: JSON response
"""
url = self.url + endpoint
r = self.session.request(method, url, params=params, data=data,
auth=self.auth, timeout=30)
return r.json() | python | def _send_message(self, method, endpoint, params=None, data=None):
url = self.url + endpoint
r = self.session.request(method, url, params=params, data=data,
auth=self.auth, timeout=30)
return r.json() | [
"def",
"_send_message",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"url",
"+",
"endpoint",
"r",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
"... | Send API request.
Args:
method (str): HTTP method (get, post, delete, etc.)
endpoint (str): Endpoint (to be added to base URL)
params (Optional[dict]): HTTP request parameters
data (Optional[str]): JSON-encoded string payload for POST
Returns:
dict/list: JSON response | [
"Send",
"API",
"request",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/public_client.py#L254-L270 |
235,078 | danpaquin/coinbasepro-python | cbpro/public_client.py | PublicClient._send_paginated_message | def _send_paginated_message(self, endpoint, params=None):
""" Send API message that results in a paginated response.
The paginated responses are abstracted away by making API requests on
demand as the response is iterated over.
Paginated API messages support 3 additional parameters: `before`,
`after`, and `limit`. `before` and `after` are mutually exclusive. To
use them, supply an index value for that endpoint (the field used for
indexing varies by endpoint - get_fills() uses 'trade_id', for example).
`before`: Only get data that occurs more recently than index
`after`: Only get data that occurs further in the past than index
`limit`: Set amount of data per HTTP response. Default (and
maximum) of 100.
Args:
endpoint (str): Endpoint (to be added to base URL)
params (Optional[dict]): HTTP request parameters
Yields:
dict: API response objects
"""
if params is None:
params = dict()
url = self.url + endpoint
while True:
r = self.session.get(url, params=params, auth=self.auth, timeout=30)
results = r.json()
for result in results:
yield result
# If there are no more pages, we're done. Otherwise update `after`
# param to get next page.
# If this request included `before` don't get any more pages - the
# cbpro API doesn't support multiple pages in that case.
if not r.headers.get('cb-after') or \
params.get('before') is not None:
break
else:
params['after'] = r.headers['cb-after'] | python | def _send_paginated_message(self, endpoint, params=None):
if params is None:
params = dict()
url = self.url + endpoint
while True:
r = self.session.get(url, params=params, auth=self.auth, timeout=30)
results = r.json()
for result in results:
yield result
# If there are no more pages, we're done. Otherwise update `after`
# param to get next page.
# If this request included `before` don't get any more pages - the
# cbpro API doesn't support multiple pages in that case.
if not r.headers.get('cb-after') or \
params.get('before') is not None:
break
else:
params['after'] = r.headers['cb-after'] | [
"def",
"_send_paginated_message",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"dict",
"(",
")",
"url",
"=",
"self",
".",
"url",
"+",
"endpoint",
"while",
"True",
":",
"r",
"=",... | Send API message that results in a paginated response.
The paginated responses are abstracted away by making API requests on
demand as the response is iterated over.
Paginated API messages support 3 additional parameters: `before`,
`after`, and `limit`. `before` and `after` are mutually exclusive. To
use them, supply an index value for that endpoint (the field used for
indexing varies by endpoint - get_fills() uses 'trade_id', for example).
`before`: Only get data that occurs more recently than index
`after`: Only get data that occurs further in the past than index
`limit`: Set amount of data per HTTP response. Default (and
maximum) of 100.
Args:
endpoint (str): Endpoint (to be added to base URL)
params (Optional[dict]): HTTP request parameters
Yields:
dict: API response objects | [
"Send",
"API",
"message",
"that",
"results",
"in",
"a",
"paginated",
"response",
"."
] | 0a9dbd86a25ae266d0e0eefeb112368c284b7dcc | https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/public_client.py#L272-L311 |
235,079 | dask/dask-ml | dask_ml/model_selection/_search.py | check_cv | def check_cv(cv=3, y=None, classifier=False):
"""Dask aware version of ``sklearn.model_selection.check_cv``
Same as the scikit-learn version, but works if ``y`` is a dask object.
"""
if cv is None:
cv = 3
# If ``cv`` is not an integer, the scikit-learn implementation doesn't
# touch the ``y`` object, so passing on a dask object is fine
if not is_dask_collection(y) or not isinstance(cv, numbers.Integral):
return model_selection.check_cv(cv, y, classifier)
if classifier:
# ``y`` is a dask object. We need to compute the target type
target_type = delayed(type_of_target, pure=True)(y).compute()
if target_type in ("binary", "multiclass"):
return StratifiedKFold(cv)
return KFold(cv) | python | def check_cv(cv=3, y=None, classifier=False):
if cv is None:
cv = 3
# If ``cv`` is not an integer, the scikit-learn implementation doesn't
# touch the ``y`` object, so passing on a dask object is fine
if not is_dask_collection(y) or not isinstance(cv, numbers.Integral):
return model_selection.check_cv(cv, y, classifier)
if classifier:
# ``y`` is a dask object. We need to compute the target type
target_type = delayed(type_of_target, pure=True)(y).compute()
if target_type in ("binary", "multiclass"):
return StratifiedKFold(cv)
return KFold(cv) | [
"def",
"check_cv",
"(",
"cv",
"=",
"3",
",",
"y",
"=",
"None",
",",
"classifier",
"=",
"False",
")",
":",
"if",
"cv",
"is",
"None",
":",
"cv",
"=",
"3",
"# If ``cv`` is not an integer, the scikit-learn implementation doesn't",
"# touch the ``y`` object, so passing o... | Dask aware version of ``sklearn.model_selection.check_cv``
Same as the scikit-learn version, but works if ``y`` is a dask object. | [
"Dask",
"aware",
"version",
"of",
"sklearn",
".",
"model_selection",
".",
"check_cv"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L900-L918 |
235,080 | dask/dask-ml | dask_ml/model_selection/_search.py | compute_n_splits | def compute_n_splits(cv, X, y=None, groups=None):
"""Return the number of splits.
Parameters
----------
cv : BaseCrossValidator
X, y, groups : array_like, dask object, or None
Returns
-------
n_splits : int
"""
if not any(is_dask_collection(i) for i in (X, y, groups)):
return cv.get_n_splits(X, y, groups)
if isinstance(cv, (_BaseKFold, BaseShuffleSplit)):
return cv.n_splits
elif isinstance(cv, PredefinedSplit):
return len(cv.unique_folds)
elif isinstance(cv, _CVIterableWrapper):
return len(cv.cv)
elif isinstance(cv, (LeaveOneOut, LeavePOut)) and not is_dask_collection(X):
# Only `X` is referenced for these classes
return cv.get_n_splits(X, None, None)
elif isinstance(cv, (LeaveOneGroupOut, LeavePGroupsOut)) and not is_dask_collection(
groups
):
# Only `groups` is referenced for these classes
return cv.get_n_splits(None, None, groups)
else:
return delayed(cv).get_n_splits(X, y, groups).compute() | python | def compute_n_splits(cv, X, y=None, groups=None):
if not any(is_dask_collection(i) for i in (X, y, groups)):
return cv.get_n_splits(X, y, groups)
if isinstance(cv, (_BaseKFold, BaseShuffleSplit)):
return cv.n_splits
elif isinstance(cv, PredefinedSplit):
return len(cv.unique_folds)
elif isinstance(cv, _CVIterableWrapper):
return len(cv.cv)
elif isinstance(cv, (LeaveOneOut, LeavePOut)) and not is_dask_collection(X):
# Only `X` is referenced for these classes
return cv.get_n_splits(X, None, None)
elif isinstance(cv, (LeaveOneGroupOut, LeavePGroupsOut)) and not is_dask_collection(
groups
):
# Only `groups` is referenced for these classes
return cv.get_n_splits(None, None, groups)
else:
return delayed(cv).get_n_splits(X, y, groups).compute() | [
"def",
"compute_n_splits",
"(",
"cv",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"is_dask_collection",
"(",
"i",
")",
"for",
"i",
"in",
"(",
"X",
",",
"y",
",",
"groups",
")",
")",
":",
"retu... | Return the number of splits.
Parameters
----------
cv : BaseCrossValidator
X, y, groups : array_like, dask object, or None
Returns
-------
n_splits : int | [
"Return",
"the",
"number",
"of",
"splits",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L921-L956 |
235,081 | dask/dask-ml | dask_ml/model_selection/_search.py | StaticDaskSearchMixin.visualize | def visualize(self, filename="mydask", format=None, **kwargs):
"""Render the task graph for this parameter search using ``graphviz``.
Requires ``graphviz`` to be installed.
Parameters
----------
filename : str or None, optional
The name (without an extension) of the file to write to disk. If
`filename` is None, no file will be written, and we communicate
with dot using only pipes.
format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional
Format in which to write output file. Default is 'png'.
**kwargs
Additional keyword arguments to forward to
``dask.dot.to_graphviz``.
Returns
-------
result : IPython.diplay.Image, IPython.display.SVG, or None
See ``dask.dot.dot_graph`` for more information.
"""
check_is_fitted(self, "dask_graph_")
return dask.visualize(
self.dask_graph_, filename=filename, format=format, **kwargs
) | python | def visualize(self, filename="mydask", format=None, **kwargs):
check_is_fitted(self, "dask_graph_")
return dask.visualize(
self.dask_graph_, filename=filename, format=format, **kwargs
) | [
"def",
"visualize",
"(",
"self",
",",
"filename",
"=",
"\"mydask\"",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"dask_graph_\"",
")",
"return",
"dask",
".",
"visualize",
"(",
"self",
".",
"dask_g... | Render the task graph for this parameter search using ``graphviz``.
Requires ``graphviz`` to be installed.
Parameters
----------
filename : str or None, optional
The name (without an extension) of the file to write to disk. If
`filename` is None, no file will be written, and we communicate
with dot using only pipes.
format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional
Format in which to write output file. Default is 'png'.
**kwargs
Additional keyword arguments to forward to
``dask.dot.to_graphviz``.
Returns
-------
result : IPython.diplay.Image, IPython.display.SVG, or None
See ``dask.dot.dot_graph`` for more information. | [
"Render",
"the",
"task",
"graph",
"for",
"this",
"parameter",
"search",
"using",
"graphviz",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L975-L1000 |
235,082 | dask/dask-ml | dask_ml/model_selection/_search.py | DaskBaseSearchCV.fit | def fit(self, X, y=None, groups=None, **fit_params):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
groups : array-like, shape = [n_samples], optional
Group labels for the samples used while splitting the dataset into
train/test set.
**fit_params
Parameters passed to the ``fit`` method of the estimator
"""
estimator = self.estimator
from sklearn.metrics.scorer import _check_multimetric_scoring
scorer, multimetric = _check_multimetric_scoring(
estimator, scoring=self.scoring
)
if not multimetric:
scorer = scorer["score"]
self.multimetric_ = multimetric
if self.multimetric_:
if self.refit is not False and (
not isinstance(self.refit, str)
# This will work for both dict / list (tuple)
or self.refit not in scorer
):
raise ValueError(
"For multi-metric scoring, the parameter "
"refit must be set to a scorer key "
"to refit an estimator with the best "
"parameter setting on the whole data and "
"make the best_* attributes "
"available for that metric. If this is "
"not needed, refit should be set to "
"False explicitly. %r was ."
"passed." % self.refit
)
self.scorer_ = scorer
error_score = self.error_score
if not (isinstance(error_score, numbers.Number) or error_score == "raise"):
raise ValueError(
"error_score must be the string 'raise' or a" " numeric value."
)
dsk, keys, n_splits = build_graph(
estimator,
self.cv,
self.scorer_,
list(self._get_param_iterator()),
X,
y,
groups,
fit_params,
iid=self.iid,
refit=self.refit,
error_score=error_score,
return_train_score=self.return_train_score,
cache_cv=self.cache_cv,
multimetric=multimetric,
)
self.dask_graph_ = dsk
self.n_splits_ = n_splits
n_jobs = _normalize_n_jobs(self.n_jobs)
scheduler = dask.base.get_scheduler(scheduler=self.scheduler)
if not scheduler:
scheduler = dask.threaded.get
if scheduler is dask.threaded.get and n_jobs == 1:
scheduler = dask.local.get_sync
out = scheduler(dsk, keys, num_workers=n_jobs)
results = handle_deprecated_train_score(out[0], self.return_train_score)
self.cv_results_ = results
if self.refit:
if self.multimetric_:
key = self.refit
else:
key = "score"
self.best_index_ = np.flatnonzero(results["rank_test_{}".format(key)] == 1)[
0
]
self.best_estimator_ = out[1]
return self | python | def fit(self, X, y=None, groups=None, **fit_params):
estimator = self.estimator
from sklearn.metrics.scorer import _check_multimetric_scoring
scorer, multimetric = _check_multimetric_scoring(
estimator, scoring=self.scoring
)
if not multimetric:
scorer = scorer["score"]
self.multimetric_ = multimetric
if self.multimetric_:
if self.refit is not False and (
not isinstance(self.refit, str)
# This will work for both dict / list (tuple)
or self.refit not in scorer
):
raise ValueError(
"For multi-metric scoring, the parameter "
"refit must be set to a scorer key "
"to refit an estimator with the best "
"parameter setting on the whole data and "
"make the best_* attributes "
"available for that metric. If this is "
"not needed, refit should be set to "
"False explicitly. %r was ."
"passed." % self.refit
)
self.scorer_ = scorer
error_score = self.error_score
if not (isinstance(error_score, numbers.Number) or error_score == "raise"):
raise ValueError(
"error_score must be the string 'raise' or a" " numeric value."
)
dsk, keys, n_splits = build_graph(
estimator,
self.cv,
self.scorer_,
list(self._get_param_iterator()),
X,
y,
groups,
fit_params,
iid=self.iid,
refit=self.refit,
error_score=error_score,
return_train_score=self.return_train_score,
cache_cv=self.cache_cv,
multimetric=multimetric,
)
self.dask_graph_ = dsk
self.n_splits_ = n_splits
n_jobs = _normalize_n_jobs(self.n_jobs)
scheduler = dask.base.get_scheduler(scheduler=self.scheduler)
if not scheduler:
scheduler = dask.threaded.get
if scheduler is dask.threaded.get and n_jobs == 1:
scheduler = dask.local.get_sync
out = scheduler(dsk, keys, num_workers=n_jobs)
results = handle_deprecated_train_score(out[0], self.return_train_score)
self.cv_results_ = results
if self.refit:
if self.multimetric_:
key = self.refit
else:
key = "score"
self.best_index_ = np.flatnonzero(results["rank_test_{}".format(key)] == 1)[
0
]
self.best_estimator_ = out[1]
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"estimator",
"=",
"self",
".",
"estimator",
"from",
"sklearn",
".",
"metrics",
".",
"scorer",
"import",
"_check_multimetric_s... | Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
groups : array-like, shape = [n_samples], optional
Group labels for the samples used while splitting the dataset into
train/test set.
**fit_params
Parameters passed to the ``fit`` method of the estimator | [
"Run",
"fit",
"with",
"all",
"sets",
"of",
"parameters",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L1117-L1212 |
235,083 | dask/dask-ml | dask_ml/model_selection/_search.py | RandomizedSearchCV._get_param_iterator | def _get_param_iterator(self):
"""Return ParameterSampler instance for the given distributions"""
return model_selection.ParameterSampler(
self.param_distributions, self.n_iter, random_state=self.random_state
) | python | def _get_param_iterator(self):
return model_selection.ParameterSampler(
self.param_distributions, self.n_iter, random_state=self.random_state
) | [
"def",
"_get_param_iterator",
"(",
"self",
")",
":",
"return",
"model_selection",
".",
"ParameterSampler",
"(",
"self",
".",
"param_distributions",
",",
"self",
".",
"n_iter",
",",
"random_state",
"=",
"self",
".",
"random_state",
")"
] | Return ParameterSampler instance for the given distributions | [
"Return",
"ParameterSampler",
"instance",
"for",
"the",
"given",
"distributions"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L1605-L1609 |
235,084 | dask/dask-ml | dask_ml/model_selection/_incremental.py | _partial_fit | def _partial_fit(model_and_meta, X, y, fit_params):
"""
Call partial_fit on a classifiers with training data X and y
Arguments
---------
model_and_meta : Tuple[Estimator, dict]
X, y : np.ndarray, np.ndarray
Training data
fit_params : dict
Extra keyword arguments to pass to partial_fit
Returns
-------
Results
A namedtuple with four fields: info, models, history, best
* info : Dict[model_id, List[Dict]]
Keys are integers identifying each model. Values are a
List of Dict
* models : Dict[model_id, Future[Estimator]]
A dictionary with the same keys as `info`. The values
are futures to the fitted models.
* history : List[Dict]
The history of model fitting for each model. Each element
of the list is a dictionary with the following elements:
* model_id : int
A superset of the keys for `info` and `models`.
* params : Dict[str, Any]
Parameters this model was trained with.
* partial_fit_calls : int
The number of *consecutive* partial fit calls at this stage in
this models training history.
* partial_fit_time : float
Time (in seconds) spent on this partial fit
* score : float
Score on the test set for the model at this point in history
* score_time : float
Time (in seconds) spent on this scoring.
* best : Tuple[model_id, Future[Estimator]]]
The estimator with the highest validation score in the final
round.
"""
with log_errors():
start = time()
model, meta = model_and_meta
if len(X):
model = deepcopy(model)
model.partial_fit(X, y, **(fit_params or {}))
meta = dict(meta)
meta["partial_fit_calls"] += 1
meta["partial_fit_time"] = time() - start
return model, meta | python | def _partial_fit(model_and_meta, X, y, fit_params):
with log_errors():
start = time()
model, meta = model_and_meta
if len(X):
model = deepcopy(model)
model.partial_fit(X, y, **(fit_params or {}))
meta = dict(meta)
meta["partial_fit_calls"] += 1
meta["partial_fit_time"] = time() - start
return model, meta | [
"def",
"_partial_fit",
"(",
"model_and_meta",
",",
"X",
",",
"y",
",",
"fit_params",
")",
":",
"with",
"log_errors",
"(",
")",
":",
"start",
"=",
"time",
"(",
")",
"model",
",",
"meta",
"=",
"model_and_meta",
"if",
"len",
"(",
"X",
")",
":",
"model",... | Call partial_fit on a classifiers with training data X and y
Arguments
---------
model_and_meta : Tuple[Estimator, dict]
X, y : np.ndarray, np.ndarray
Training data
fit_params : dict
Extra keyword arguments to pass to partial_fit
Returns
-------
Results
A namedtuple with four fields: info, models, history, best
* info : Dict[model_id, List[Dict]]
Keys are integers identifying each model. Values are a
List of Dict
* models : Dict[model_id, Future[Estimator]]
A dictionary with the same keys as `info`. The values
are futures to the fitted models.
* history : List[Dict]
The history of model fitting for each model. Each element
of the list is a dictionary with the following elements:
* model_id : int
A superset of the keys for `info` and `models`.
* params : Dict[str, Any]
Parameters this model was trained with.
* partial_fit_calls : int
The number of *consecutive* partial fit calls at this stage in
this models training history.
* partial_fit_time : float
Time (in seconds) spent on this partial fit
* score : float
Score on the test set for the model at this point in history
* score_time : float
Time (in seconds) spent on this scoring.
* best : Tuple[model_id, Future[Estimator]]]
The estimator with the highest validation score in the final
round. | [
"Call",
"partial_fit",
"on",
"a",
"classifiers",
"with",
"training",
"data",
"X",
"and",
"y"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L30-L86 |
235,085 | dask/dask-ml | dask_ml/model_selection/_incremental.py | _create_model | def _create_model(model, ident, **params):
""" Create a model by cloning and then setting params """
with log_errors(pdb=True):
model = clone(model).set_params(**params)
return model, {"model_id": ident, "params": params, "partial_fit_calls": 0} | python | def _create_model(model, ident, **params):
with log_errors(pdb=True):
model = clone(model).set_params(**params)
return model, {"model_id": ident, "params": params, "partial_fit_calls": 0} | [
"def",
"_create_model",
"(",
"model",
",",
"ident",
",",
"*",
"*",
"params",
")",
":",
"with",
"log_errors",
"(",
"pdb",
"=",
"True",
")",
":",
"model",
"=",
"clone",
"(",
"model",
")",
".",
"set_params",
"(",
"*",
"*",
"params",
")",
"return",
"mo... | Create a model by cloning and then setting params | [
"Create",
"a",
"model",
"by",
"cloning",
"and",
"then",
"setting",
"params"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L102-L106 |
235,086 | dask/dask-ml | dask_ml/model_selection/_incremental.py | fit | def fit(
model,
params,
X_train,
y_train,
X_test,
y_test,
additional_calls,
fit_params=None,
scorer=None,
random_state=None,
):
""" Find a good model and search among a space of hyper-parameters
This does a hyper-parameter search by creating many models and then fitting
them incrementally on batches of data and reducing the number of models based
on the scores computed during training. Over time fewer and fewer models
remain. We train these models for increasingly long times.
The model, number of starting parameters, and decay can all be provided as
configuration parameters.
Training data should be given as Dask arrays. It can be large. Testing
data should be given either as a small dask array or as a numpy array. It
should fit on a single worker.
Parameters
----------
model : Estimator
params : List[Dict]
Parameters to start training on model
X_train : dask Array
y_train : dask Array
X_test : Array
Numpy array or small dask array. Should fit in single node's memory.
y_test : Array
Numpy array or small dask array. Should fit in single node's memory.
additional_calls : callable
A function that takes information about scoring history per model and
returns the number of additional partial fit calls to run on each model
fit_params : dict
Extra parameters to give to partial_fit
scorer : callable
A scorer callable object / function with signature
``scorer(estimator, X, y)``.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Examples
--------
>>> import numpy as np
>>> from dask_ml.datasets import make_classification
>>> X, y = make_classification(n_samples=5000000, n_features=20,
... chunks=100000, random_state=0)
>>> from sklearn.linear_model import SGDClassifier
>>> model = SGDClassifier(tol=1e-3, penalty='elasticnet', random_state=0)
>>> from sklearn.model_selection import ParameterSampler
>>> params = {'alpha': np.logspace(-2, 1, num=1000),
... 'l1_ratio': np.linspace(0, 1, num=1000),
... 'average': [True, False]}
>>> params = list(ParameterSampler(params, 10, random_state=0))
>>> X_test, y_test = X[:100000], y[:100000]
>>> X_train = X[100000:]
>>> y_train = y[100000:]
>>> def remove_worst(scores):
... last_score = {model_id: info[-1]['score']
... for model_id, info in scores.items()}
... worst_score = min(last_score.values())
... out = {}
... for model_id, score in last_score.items():
... if score != worst_score:
... out[model_id] = 1 # do one more training step
... if len(out) == 1:
... out = {k: 0 for k in out} # no more work to do, stops execution
... return out
>>> from dask.distributed import Client
>>> client = Client(processes=False)
>>> from dask_ml.model_selection._incremental import fit
>>> info, models, history, best = fit(model, params,
... X_train, y_train,
... X_test, y_test,
... additional_calls=remove_worst,
... fit_params={'classes': [0, 1]},
... random_state=0)
>>> models
{2: <Future: status: finished, type: SGDClassifier, key: ...}
>>> models[2].result()
SGDClassifier(...)
>>> info[2][-1] # doctest: +SKIP
{'model_id': 2,
'params': {'l1_ratio': 0.9529529529529529, 'average': False,
'alpha': 0.014933932161242525},
'partial_fit_calls': 8,
'partial_fit_time': 0.17334818840026855,
'score': 0.58765,
'score_time': 0.031442880630493164}
Returns
-------
info : Dict[int, List[Dict]]
Scoring history of each successful model, keyed by model ID.
This has the parameters, scores, and timing information over time
models : Dict[int, Future]
Dask futures pointing to trained models
history : List[Dict]
A history of all models scores over time
"""
return default_client().sync(
_fit,
model,
params,
X_train,
y_train,
X_test,
y_test,
additional_calls,
fit_params=fit_params,
scorer=scorer,
random_state=random_state,
) | python | def fit(
model,
params,
X_train,
y_train,
X_test,
y_test,
additional_calls,
fit_params=None,
scorer=None,
random_state=None,
):
return default_client().sync(
_fit,
model,
params,
X_train,
y_train,
X_test,
y_test,
additional_calls,
fit_params=fit_params,
scorer=scorer,
random_state=random_state,
) | [
"def",
"fit",
"(",
"model",
",",
"params",
",",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test",
",",
"additional_calls",
",",
"fit_params",
"=",
"None",
",",
"scorer",
"=",
"None",
",",
"random_state",
"=",
"None",
",",
")",
":",
"return",
"de... | Find a good model and search among a space of hyper-parameters
This does a hyper-parameter search by creating many models and then fitting
them incrementally on batches of data and reducing the number of models based
on the scores computed during training. Over time fewer and fewer models
remain. We train these models for increasingly long times.
The model, number of starting parameters, and decay can all be provided as
configuration parameters.
Training data should be given as Dask arrays. It can be large. Testing
data should be given either as a small dask array or as a numpy array. It
should fit on a single worker.
Parameters
----------
model : Estimator
params : List[Dict]
Parameters to start training on model
X_train : dask Array
y_train : dask Array
X_test : Array
Numpy array or small dask array. Should fit in single node's memory.
y_test : Array
Numpy array or small dask array. Should fit in single node's memory.
additional_calls : callable
A function that takes information about scoring history per model and
returns the number of additional partial fit calls to run on each model
fit_params : dict
Extra parameters to give to partial_fit
scorer : callable
A scorer callable object / function with signature
``scorer(estimator, X, y)``.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Examples
--------
>>> import numpy as np
>>> from dask_ml.datasets import make_classification
>>> X, y = make_classification(n_samples=5000000, n_features=20,
... chunks=100000, random_state=0)
>>> from sklearn.linear_model import SGDClassifier
>>> model = SGDClassifier(tol=1e-3, penalty='elasticnet', random_state=0)
>>> from sklearn.model_selection import ParameterSampler
>>> params = {'alpha': np.logspace(-2, 1, num=1000),
... 'l1_ratio': np.linspace(0, 1, num=1000),
... 'average': [True, False]}
>>> params = list(ParameterSampler(params, 10, random_state=0))
>>> X_test, y_test = X[:100000], y[:100000]
>>> X_train = X[100000:]
>>> y_train = y[100000:]
>>> def remove_worst(scores):
... last_score = {model_id: info[-1]['score']
... for model_id, info in scores.items()}
... worst_score = min(last_score.values())
... out = {}
... for model_id, score in last_score.items():
... if score != worst_score:
... out[model_id] = 1 # do one more training step
... if len(out) == 1:
... out = {k: 0 for k in out} # no more work to do, stops execution
... return out
>>> from dask.distributed import Client
>>> client = Client(processes=False)
>>> from dask_ml.model_selection._incremental import fit
>>> info, models, history, best = fit(model, params,
... X_train, y_train,
... X_test, y_test,
... additional_calls=remove_worst,
... fit_params={'classes': [0, 1]},
... random_state=0)
>>> models
{2: <Future: status: finished, type: SGDClassifier, key: ...}
>>> models[2].result()
SGDClassifier(...)
>>> info[2][-1] # doctest: +SKIP
{'model_id': 2,
'params': {'l1_ratio': 0.9529529529529529, 'average': False,
'alpha': 0.014933932161242525},
'partial_fit_calls': 8,
'partial_fit_time': 0.17334818840026855,
'score': 0.58765,
'score_time': 0.031442880630493164}
Returns
-------
info : Dict[int, List[Dict]]
Scoring history of each successful model, keyed by model ID.
This has the parameters, scores, and timing information over time
models : Dict[int, Future]
Dask futures pointing to trained models
history : List[Dict]
A history of all models scores over time | [
"Find",
"a",
"good",
"model",
"and",
"search",
"among",
"a",
"space",
"of",
"hyper",
"-",
"parameters"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L273-L402 |
235,087 | dask/dask-ml | dask_ml/model_selection/_incremental.py | BaseIncrementalSearchCV._check_array | def _check_array(self, X, **kwargs):
"""Validate the data arguments X and y.
By default, NumPy arrays are converted to 1-block dask arrays.
Parameters
----------
X, y : array-like
"""
if isinstance(X, np.ndarray):
X = da.from_array(X, X.shape)
X = check_array(X, **kwargs)
return X | python | def _check_array(self, X, **kwargs):
if isinstance(X, np.ndarray):
X = da.from_array(X, X.shape)
X = check_array(X, **kwargs)
return X | [
"def",
"_check_array",
"(",
"self",
",",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
"X",
"=",
"da",
".",
"from_array",
"(",
"X",
",",
"X",
".",
"shape",
")",
"X",
"=",
"check_array... | Validate the data arguments X and y.
By default, NumPy arrays are converted to 1-block dask arrays.
Parameters
----------
X, y : array-like | [
"Validate",
"the",
"data",
"arguments",
"X",
"and",
"y",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L432-L444 |
235,088 | dask/dask-ml | dask_ml/model_selection/_incremental.py | BaseIncrementalSearchCV.fit | def fit(self, X, y, **fit_params):
"""Find the best parameters for a particular model.
Parameters
----------
X, y : array-like
**fit_params
Additional partial fit keyword arguments for the estimator.
"""
return default_client().sync(self._fit, X, y, **fit_params) | python | def fit(self, X, y, **fit_params):
return default_client().sync(self._fit, X, y, **fit_params) | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")",
":",
"return",
"default_client",
"(",
")",
".",
"sync",
"(",
"self",
".",
"_fit",
",",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")"
] | Find the best parameters for a particular model.
Parameters
----------
X, y : array-like
**fit_params
Additional partial fit keyword arguments for the estimator. | [
"Find",
"the",
"best",
"parameters",
"for",
"a",
"particular",
"model",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_incremental.py#L569-L578 |
235,089 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit._check_array | def _check_array(self, X):
"""Validate an array for post-fit tasks.
Parameters
----------
X : Union[Array, DataFrame]
Returns
-------
same type as 'X'
Notes
-----
The following checks are applied.
- Ensure that the array is blocked only along the samples.
"""
if isinstance(X, da.Array):
if X.ndim == 2 and X.numblocks[1] > 1:
logger.debug("auto-rechunking 'X'")
if not np.isnan(X.chunks[0]).any():
X = X.rechunk({0: "auto", 1: -1})
else:
X = X.rechunk({1: -1})
return X | python | def _check_array(self, X):
if isinstance(X, da.Array):
if X.ndim == 2 and X.numblocks[1] > 1:
logger.debug("auto-rechunking 'X'")
if not np.isnan(X.chunks[0]).any():
X = X.rechunk({0: "auto", 1: -1})
else:
X = X.rechunk({1: -1})
return X | [
"def",
"_check_array",
"(",
"self",
",",
"X",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"da",
".",
"Array",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"2",
"and",
"X",
".",
"numblocks",
"[",
"1",
"]",
">",
"1",
":",
"logger",
".",
"debug",
"(... | Validate an array for post-fit tasks.
Parameters
----------
X : Union[Array, DataFrame]
Returns
-------
same type as 'X'
Notes
-----
The following checks are applied.
- Ensure that the array is blocked only along the samples. | [
"Validate",
"an",
"array",
"for",
"post",
"-",
"fit",
"tasks",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L122-L146 |
235,090 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit.transform | def transform(self, X):
"""Transform block or partition-wise for dask inputs.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``transform`` method, then
an ``AttributeError`` is raised.
Parameters
----------
X : array-like
Returns
-------
transformed : array-like
"""
self._check_method("transform")
X = self._check_array(X)
if isinstance(X, da.Array):
return X.map_blocks(_transform, estimator=self._postfit_estimator)
elif isinstance(X, dd._Frame):
return X.map_partitions(_transform, estimator=self._postfit_estimator)
else:
return _transform(X, estimator=self._postfit_estimator) | python | def transform(self, X):
self._check_method("transform")
X = self._check_array(X)
if isinstance(X, da.Array):
return X.map_blocks(_transform, estimator=self._postfit_estimator)
elif isinstance(X, dd._Frame):
return X.map_partitions(_transform, estimator=self._postfit_estimator)
else:
return _transform(X, estimator=self._postfit_estimator) | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_check_method",
"(",
"\"transform\"",
")",
"X",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"if",
"isinstance",
"(",
"X",
",",
"da",
".",
"Array",
")",
":",
"return",
"X",
".",... | Transform block or partition-wise for dask inputs.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``transform`` method, then
an ``AttributeError`` is raised.
Parameters
----------
X : array-like
Returns
-------
transformed : array-like | [
"Transform",
"block",
"or",
"partition",
"-",
"wise",
"for",
"dask",
"inputs",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L185-L211 |
235,091 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit.score | def score(self, X, y, compute=True):
"""Returns the score on the given data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input data, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
Returns
-------
score : float
return self.estimator.score(X, y)
"""
scoring = self.scoring
X = self._check_array(X)
y = self._check_array(y)
if not scoring:
if type(self._postfit_estimator).score == sklearn.base.RegressorMixin.score:
scoring = "r2"
elif (
type(self._postfit_estimator).score
== sklearn.base.ClassifierMixin.score
):
scoring = "accuracy"
else:
scoring = self.scoring
if scoring:
if not dask.is_dask_collection(X) and not dask.is_dask_collection(y):
scorer = sklearn.metrics.get_scorer(scoring)
else:
scorer = get_scorer(scoring, compute=compute)
return scorer(self, X, y)
else:
return self._postfit_estimator.score(X, y) | python | def score(self, X, y, compute=True):
scoring = self.scoring
X = self._check_array(X)
y = self._check_array(y)
if not scoring:
if type(self._postfit_estimator).score == sklearn.base.RegressorMixin.score:
scoring = "r2"
elif (
type(self._postfit_estimator).score
== sklearn.base.ClassifierMixin.score
):
scoring = "accuracy"
else:
scoring = self.scoring
if scoring:
if not dask.is_dask_collection(X) and not dask.is_dask_collection(y):
scorer = sklearn.metrics.get_scorer(scoring)
else:
scorer = get_scorer(scoring, compute=compute)
return scorer(self, X, y)
else:
return self._postfit_estimator.score(X, y) | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
",",
"compute",
"=",
"True",
")",
":",
"scoring",
"=",
"self",
".",
"scoring",
"X",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"y",
"=",
"self",
".",
"_check_array",
"(",
"y",
")",
"if",
"n... | Returns the score on the given data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input data, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, n_output], optional
Target relative to X for classification or regression;
None for unsupervised learning.
Returns
-------
score : float
return self.estimator.score(X, y) | [
"Returns",
"the",
"score",
"on",
"the",
"given",
"data",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L213-L253 |
235,092 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit.predict | def predict(self, X):
"""Predict for X.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
Parameters
----------
X : array-like
Returns
-------
y : array-like
"""
self._check_method("predict")
X = self._check_array(X)
if isinstance(X, da.Array):
result = X.map_blocks(
_predict, dtype="int", estimator=self._postfit_estimator, drop_axis=1
)
return result
elif isinstance(X, dd._Frame):
return X.map_partitions(
_predict, estimator=self._postfit_estimator, meta=np.array([1])
)
else:
return _predict(X, estimator=self._postfit_estimator) | python | def predict(self, X):
self._check_method("predict")
X = self._check_array(X)
if isinstance(X, da.Array):
result = X.map_blocks(
_predict, dtype="int", estimator=self._postfit_estimator, drop_axis=1
)
return result
elif isinstance(X, dd._Frame):
return X.map_partitions(
_predict, estimator=self._postfit_estimator, meta=np.array([1])
)
else:
return _predict(X, estimator=self._postfit_estimator) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_check_method",
"(",
"\"predict\"",
")",
"X",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"if",
"isinstance",
"(",
"X",
",",
"da",
".",
"Array",
")",
":",
"result",
"=",
"X",
"... | Predict for X.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
Parameters
----------
X : array-like
Returns
-------
y : array-like | [
"Predict",
"for",
"X",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L255-L285 |
235,093 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit.predict_log_proba | def predict_log_proba(self, X):
"""Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like
"""
self._check_method("predict_log_proba")
return da.log(self.predict_proba(X)) | python | def predict_log_proba(self, X):
self._check_method("predict_log_proba")
return da.log(self.predict_proba(X)) | [
"def",
"predict_log_proba",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_check_method",
"(",
"\"predict_log_proba\"",
")",
"return",
"da",
".",
"log",
"(",
"self",
".",
"predict_proba",
"(",
"X",
")",
")"
] | Log of proability estimates.
For dask inputs, a dask array or dataframe is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeError`` is raised.
Parameters
----------
X : array or dataframe
Returns
-------
y : array-like | [
"Log",
"of",
"proability",
"estimates",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L322-L341 |
235,094 | dask/dask-ml | dask_ml/wrappers.py | ParallelPostFit._check_method | def _check_method(self, method):
"""Check if self.estimator has 'method'.
Raises
------
AttributeError
"""
estimator = self._postfit_estimator
if not hasattr(estimator, method):
msg = "The wrapped estimator '{}' does not have a '{}' method.".format(
estimator, method
)
raise AttributeError(msg)
return getattr(estimator, method) | python | def _check_method(self, method):
estimator = self._postfit_estimator
if not hasattr(estimator, method):
msg = "The wrapped estimator '{}' does not have a '{}' method.".format(
estimator, method
)
raise AttributeError(msg)
return getattr(estimator, method) | [
"def",
"_check_method",
"(",
"self",
",",
"method",
")",
":",
"estimator",
"=",
"self",
".",
"_postfit_estimator",
"if",
"not",
"hasattr",
"(",
"estimator",
",",
"method",
")",
":",
"msg",
"=",
"\"The wrapped estimator '{}' does not have a '{}' method.\"",
".",
"f... | Check if self.estimator has 'method'.
Raises
------
AttributeError | [
"Check",
"if",
"self",
".",
"estimator",
"has",
"method",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/wrappers.py#L343-L356 |
235,095 | dask/dask-ml | dask_ml/linear_model/glm.py | _GLM.fit | def fit(self, X, y=None):
"""Fit the model on the training data
Parameters
----------
X: array-like, shape (n_samples, n_features)
y : array-like, shape (n_samples,)
Returns
-------
self : objectj
"""
X = self._check_array(X)
solver_kwargs = self._get_solver_kwargs()
self._coef = algorithms._solvers[self.solver](X, y, **solver_kwargs)
if self.fit_intercept:
self.coef_ = self._coef[:-1]
self.intercept_ = self._coef[-1]
else:
self.coef_ = self._coef
return self | python | def fit(self, X, y=None):
X = self._check_array(X)
solver_kwargs = self._get_solver_kwargs()
self._coef = algorithms._solvers[self.solver](X, y, **solver_kwargs)
if self.fit_intercept:
self.coef_ = self._coef[:-1]
self.intercept_ = self._coef[-1]
else:
self.coef_ = self._coef
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"solver_kwargs",
"=",
"self",
".",
"_get_solver_kwargs",
"(",
")",
"self",
".",
"_coef",
"=",
"algorithms",
".",
"_solvers",
... | Fit the model on the training data
Parameters
----------
X: array-like, shape (n_samples, n_features)
y : array-like, shape (n_samples,)
Returns
-------
self : objectj | [
"Fit",
"the",
"model",
"on",
"the",
"training",
"data"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/linear_model/glm.py#L171-L193 |
235,096 | dask/dask-ml | dask_ml/linear_model/glm.py | LogisticRegression.predict_proba | def predict_proba(self, X):
"""Probability estimates for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples, n_classes]
The probability of the sample for each class in the model.
"""
X_ = self._check_array(X)
return sigmoid(dot(X_, self._coef)) | python | def predict_proba(self, X):
X_ = self._check_array(X)
return sigmoid(dot(X_, self._coef)) | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"X_",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"return",
"sigmoid",
"(",
"dot",
"(",
"X_",
",",
"self",
".",
"_coef",
")",
")"
] | Probability estimates for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
T : array-like, shape = [n_samples, n_classes]
The probability of the sample for each class in the model. | [
"Probability",
"estimates",
"for",
"samples",
"in",
"X",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/linear_model/glm.py#L235-L248 |
235,097 | dask/dask-ml | dask_ml/linear_model/glm.py | PoissonRegression.predict | def predict(self, X):
"""Predict count for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples,]
Predicted count for each sample
"""
X_ = self._check_array(X)
return exp(dot(X_, self._coef)) | python | def predict(self, X):
X_ = self._check_array(X)
return exp(dot(X_, self._coef)) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"X_",
"=",
"self",
".",
"_check_array",
"(",
"X",
")",
"return",
"exp",
"(",
"dot",
"(",
"X_",
",",
"self",
".",
"_coef",
")",
")"
] | Predict count for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples,]
Predicted count for each sample | [
"Predict",
"count",
"for",
"samples",
"in",
"X",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/linear_model/glm.py#L348-L361 |
235,098 | dask/dask-ml | dask_ml/cluster/k_means.py | k_means | def k_means(
X,
n_clusters,
init="k-means||",
precompute_distances="auto",
n_init=1,
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
n_jobs=-1,
algorithm="full",
return_n_iter=False,
oversampling_factor=2,
init_max_iter=None,
):
"""K-means algorithm for clustering
Differences from scikit-learn:
* init='k-means||'
* oversampling_factor keyword
* n_jobs=-1
"""
labels, inertia, centers, n_iter = _kmeans_single_lloyd(
X,
n_clusters,
max_iter=max_iter,
init=init,
verbose=verbose,
tol=tol,
random_state=random_state,
oversampling_factor=oversampling_factor,
init_max_iter=init_max_iter,
)
if return_n_iter:
return labels, centers, inertia, n_iter
else:
return labels, centers, inertia | python | def k_means(
X,
n_clusters,
init="k-means||",
precompute_distances="auto",
n_init=1,
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
n_jobs=-1,
algorithm="full",
return_n_iter=False,
oversampling_factor=2,
init_max_iter=None,
):
labels, inertia, centers, n_iter = _kmeans_single_lloyd(
X,
n_clusters,
max_iter=max_iter,
init=init,
verbose=verbose,
tol=tol,
random_state=random_state,
oversampling_factor=oversampling_factor,
init_max_iter=init_max_iter,
)
if return_n_iter:
return labels, centers, inertia, n_iter
else:
return labels, centers, inertia | [
"def",
"k_means",
"(",
"X",
",",
"n_clusters",
",",
"init",
"=",
"\"k-means||\"",
",",
"precompute_distances",
"=",
"\"auto\"",
",",
"n_init",
"=",
"1",
",",
"max_iter",
"=",
"300",
",",
"verbose",
"=",
"False",
",",
"tol",
"=",
"1e-4",
",",
"random_stat... | K-means algorithm for clustering
Differences from scikit-learn:
* init='k-means||'
* oversampling_factor keyword
* n_jobs=-1 | [
"K",
"-",
"means",
"algorithm",
"for",
"clustering"
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/cluster/k_means.py#L236-L275 |
235,099 | dask/dask-ml | dask_ml/cluster/k_means.py | k_init | def k_init(
X,
n_clusters,
init="k-means||",
random_state=None,
max_iter=None,
oversampling_factor=2,
):
"""Choose the initial centers for K-Means.
Parameters
----------
X : da.Array (n_samples, n_features)
n_clusters : int
Number of clusters to end up with
init : {'k-means||', 'k-means++', 'random'} or numpy.ndarray
Initialization method, or pass a NumPy array to use
random_state : int, optional
max_iter : int, optional
Only used for ``init='k-means||'``.
oversampling_factor : int, optional
Only used for ``init='k-means||`''. Controls the additional number of
candidate centers in each iteration.
Return
------
centers : np.ndarray (n_clusters, n_features)
Notes
-----
The default strategy is ``k-means||``, which tends to be slower than
``k-means++`` for small (in-memory) datasets, but works better in a
distributed setting.
.. warning::
Using ``init='k-means++'`` assumes that the entire dataset fits
in RAM.
"""
if isinstance(init, np.ndarray):
K, P = init.shape
if K != n_clusters:
msg = (
"Number of centers in provided 'init' ({}) does "
"not match 'n_clusters' ({})"
)
raise ValueError(msg.format(K, n_clusters))
if P != X.shape[1]:
msg = (
"Number of features in the provided 'init' ({}) do not "
"match the number of features in 'X'"
)
raise ValueError(msg.format(P, X.shape[1]))
return init
elif not isinstance(init, str):
raise TypeError("'init' must be an array or str, got {}".format(type(init)))
valid = {"k-means||", "k-means++", "random"}
if isinstance(random_state, Integral) or random_state is None:
if init == "k-means||":
random_state = da.random.RandomState(random_state)
else:
random_state = np.random.RandomState(random_state)
if init == "k-means||":
return init_scalable(X, n_clusters, random_state, max_iter, oversampling_factor)
elif init == "k-means++":
return init_pp(X, n_clusters, random_state)
elif init == "random":
return init_random(X, n_clusters, random_state)
else:
raise ValueError("'init' must be one of {}, got {}".format(valid, init)) | python | def k_init(
X,
n_clusters,
init="k-means||",
random_state=None,
max_iter=None,
oversampling_factor=2,
):
if isinstance(init, np.ndarray):
K, P = init.shape
if K != n_clusters:
msg = (
"Number of centers in provided 'init' ({}) does "
"not match 'n_clusters' ({})"
)
raise ValueError(msg.format(K, n_clusters))
if P != X.shape[1]:
msg = (
"Number of features in the provided 'init' ({}) do not "
"match the number of features in 'X'"
)
raise ValueError(msg.format(P, X.shape[1]))
return init
elif not isinstance(init, str):
raise TypeError("'init' must be an array or str, got {}".format(type(init)))
valid = {"k-means||", "k-means++", "random"}
if isinstance(random_state, Integral) or random_state is None:
if init == "k-means||":
random_state = da.random.RandomState(random_state)
else:
random_state = np.random.RandomState(random_state)
if init == "k-means||":
return init_scalable(X, n_clusters, random_state, max_iter, oversampling_factor)
elif init == "k-means++":
return init_pp(X, n_clusters, random_state)
elif init == "random":
return init_random(X, n_clusters, random_state)
else:
raise ValueError("'init' must be one of {}, got {}".format(valid, init)) | [
"def",
"k_init",
"(",
"X",
",",
"n_clusters",
",",
"init",
"=",
"\"k-means||\"",
",",
"random_state",
"=",
"None",
",",
"max_iter",
"=",
"None",
",",
"oversampling_factor",
"=",
"2",
",",
")",
":",
"if",
"isinstance",
"(",
"init",
",",
"np",
".",
"ndar... | Choose the initial centers for K-Means.
Parameters
----------
X : da.Array (n_samples, n_features)
n_clusters : int
Number of clusters to end up with
init : {'k-means||', 'k-means++', 'random'} or numpy.ndarray
Initialization method, or pass a NumPy array to use
random_state : int, optional
max_iter : int, optional
Only used for ``init='k-means||'``.
oversampling_factor : int, optional
Only used for ``init='k-means||`''. Controls the additional number of
candidate centers in each iteration.
Return
------
centers : np.ndarray (n_clusters, n_features)
Notes
-----
The default strategy is ``k-means||``, which tends to be slower than
``k-means++`` for small (in-memory) datasets, but works better in a
distributed setting.
.. warning::
Using ``init='k-means++'`` assumes that the entire dataset fits
in RAM. | [
"Choose",
"the",
"initial",
"centers",
"for",
"K",
"-",
"Means",
"."
] | cc4837c2c2101f9302cac38354b55754263cd1f3 | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/cluster/k_means.py#L291-L369 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.