repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
GNS3/gns3-server | gns3server/controller/topology.py | _convert_snapshots | def _convert_snapshots(topo_dir):
"""
Convert 1.x snapshot to the new format
"""
old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots")
if os.path.exists(old_snapshots_dir):
new_snapshots_dir = os.path.join(topo_dir, "snapshots")
os.makedirs(new_snapshots_dir)
for snapshot in os.listdir(old_snapshots_dir):
snapshot_dir = os.path.join(old_snapshots_dir, snapshot)
if os.path.isdir(snapshot_dir):
is_gns3_topo = False
# In .gns3project fileformat the .gns3 should be name project.gns3
for file in os.listdir(snapshot_dir):
if file.endswith(".gns3"):
shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3"))
is_gns3_topo = True
if is_gns3_topo:
snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project")
with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip:
for root, dirs, files in os.walk(snapshot_dir):
for file in files:
myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED)
shutil.rmtree(old_snapshots_dir) | python | def _convert_snapshots(topo_dir):
"""
Convert 1.x snapshot to the new format
"""
old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots")
if os.path.exists(old_snapshots_dir):
new_snapshots_dir = os.path.join(topo_dir, "snapshots")
os.makedirs(new_snapshots_dir)
for snapshot in os.listdir(old_snapshots_dir):
snapshot_dir = os.path.join(old_snapshots_dir, snapshot)
if os.path.isdir(snapshot_dir):
is_gns3_topo = False
# In .gns3project fileformat the .gns3 should be name project.gns3
for file in os.listdir(snapshot_dir):
if file.endswith(".gns3"):
shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3"))
is_gns3_topo = True
if is_gns3_topo:
snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project")
with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip:
for root, dirs, files in os.walk(snapshot_dir):
for file in files:
myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED)
shutil.rmtree(old_snapshots_dir) | [
"def",
"_convert_snapshots",
"(",
"topo_dir",
")",
":",
"old_snapshots_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"topo_dir",
",",
"\"project-files\"",
",",
"\"snapshots\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"old_snapshots_dir",
")",
":"... | Convert 1.x snapshot to the new format | [
"Convert",
"1",
".",
"x",
"snapshot",
"to",
"the",
"new",
"format"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L638-L665 | train | 221,600 |
GNS3/gns3-server | gns3server/controller/topology.py | _convert_qemu_node | def _convert_qemu_node(node, old_node):
"""
Convert qemu node from 1.X to 2.0
"""
# In 2.0 the internet VM is replaced by the NAT node
if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31":
node["console"] = None
node["console_type"] = None
node["node_type"] = "nat"
del old_node["properties"]
node["properties"] = {
"ports": [
{
"interface": "eth1",
"name": "nat0",
"port_number": 0,
"type": "ethernet"
}
]
}
if node["symbol"] is None:
node["symbol"] = ":/symbols/cloud.svg"
return node
node["node_type"] = "qemu"
if node["symbol"] is None:
node["symbol"] = ":/symbols/qemu_guest.svg"
return node | python | def _convert_qemu_node(node, old_node):
"""
Convert qemu node from 1.X to 2.0
"""
# In 2.0 the internet VM is replaced by the NAT node
if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31":
node["console"] = None
node["console_type"] = None
node["node_type"] = "nat"
del old_node["properties"]
node["properties"] = {
"ports": [
{
"interface": "eth1",
"name": "nat0",
"port_number": 0,
"type": "ethernet"
}
]
}
if node["symbol"] is None:
node["symbol"] = ":/symbols/cloud.svg"
return node
node["node_type"] = "qemu"
if node["symbol"] is None:
node["symbol"] = ":/symbols/qemu_guest.svg"
return node | [
"def",
"_convert_qemu_node",
"(",
"node",
",",
"old_node",
")",
":",
"# In 2.0 the internet VM is replaced by the NAT node",
"if",
"old_node",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"hda_disk_image_md5sum\"",
")",
"==",
"\"8ebc5a6e... | Convert qemu node from 1.X to 2.0 | [
"Convert",
"qemu",
"node",
"from",
"1",
".",
"X",
"to",
"2",
".",
"0"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L668-L696 | train | 221,601 |
GNS3/gns3-server | gns3server/controller/project.py | open_required | def open_required(func):
"""
Use this decorator to raise an error if the project is not opened
"""
def wrapper(self, *args, **kwargs):
if self._status == "closed":
raise aiohttp.web.HTTPForbidden(text="The project is not opened")
return func(self, *args, **kwargs)
return wrapper | python | def open_required(func):
"""
Use this decorator to raise an error if the project is not opened
"""
def wrapper(self, *args, **kwargs):
if self._status == "closed":
raise aiohttp.web.HTTPForbidden(text="The project is not opened")
return func(self, *args, **kwargs)
return wrapper | [
"def",
"open_required",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_status",
"==",
"\"closed\"",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPForbidden",
"(",
"text... | Use this decorator to raise an error if the project is not opened | [
"Use",
"this",
"decorator",
"to",
"raise",
"an",
"error",
"if",
"the",
"project",
"is",
"not",
"opened"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L47-L56 | train | 221,602 |
GNS3/gns3-server | gns3server/controller/project.py | Project.captures_directory | def captures_directory(self):
"""
Location of the captures files
"""
path = os.path.join(self._path, "project-files", "captures")
os.makedirs(path, exist_ok=True)
return path | python | def captures_directory(self):
"""
Location of the captures files
"""
path = os.path.join(self._path, "project-files", "captures")
os.makedirs(path, exist_ok=True)
return path | [
"def",
"captures_directory",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"\"project-files\"",
",",
"\"captures\"",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"exist_ok",
"=",
"True",
")",
"retu... | Location of the captures files | [
"Location",
"of",
"the",
"captures",
"files"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L325-L331 | train | 221,603 |
GNS3/gns3-server | gns3server/controller/project.py | Project.remove_allocated_node_name | def remove_allocated_node_name(self, name):
"""
Removes an allocated node name
:param name: allocated node name
"""
if name in self._allocated_node_names:
self._allocated_node_names.remove(name) | python | def remove_allocated_node_name(self, name):
"""
Removes an allocated node name
:param name: allocated node name
"""
if name in self._allocated_node_names:
self._allocated_node_names.remove(name) | [
"def",
"remove_allocated_node_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_allocated_node_names",
":",
"self",
".",
"_allocated_node_names",
".",
"remove",
"(",
"name",
")"
] | Removes an allocated node name
:param name: allocated node name | [
"Removes",
"an",
"allocated",
"node",
"name"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L349-L357 | train | 221,604 |
GNS3/gns3-server | gns3server/controller/project.py | Project.update_allocated_node_name | def update_allocated_node_name(self, base_name):
"""
Updates a node name or generate a new if no node
name is available.
:param base_name: new node base name
"""
if base_name is None:
return None
base_name = re.sub(r"[ ]", "", base_name)
if base_name in self._allocated_node_names:
base_name = re.sub(r"[0-9]+$", "{0}", base_name)
if '{0}' in base_name or '{id}' in base_name:
# base name is a template, replace {0} or {id} by an unique identifier
for number in range(1, 1000000):
try:
name = base_name.format(number, id=number, name="Node")
except KeyError as e:
raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name")
except (ValueError, IndexError) as e:
raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name))
if name not in self._allocated_node_names:
self._allocated_node_names.add(name)
return name
else:
if base_name not in self._allocated_node_names:
self._allocated_node_names.add(base_name)
return base_name
# base name is not unique, let's find a unique name by appending a number
for number in range(1, 1000000):
name = base_name + str(number)
if name not in self._allocated_node_names:
self._allocated_node_names.add(name)
return name
raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)") | python | def update_allocated_node_name(self, base_name):
"""
Updates a node name or generate a new if no node
name is available.
:param base_name: new node base name
"""
if base_name is None:
return None
base_name = re.sub(r"[ ]", "", base_name)
if base_name in self._allocated_node_names:
base_name = re.sub(r"[0-9]+$", "{0}", base_name)
if '{0}' in base_name or '{id}' in base_name:
# base name is a template, replace {0} or {id} by an unique identifier
for number in range(1, 1000000):
try:
name = base_name.format(number, id=number, name="Node")
except KeyError as e:
raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name")
except (ValueError, IndexError) as e:
raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name))
if name not in self._allocated_node_names:
self._allocated_node_names.add(name)
return name
else:
if base_name not in self._allocated_node_names:
self._allocated_node_names.add(base_name)
return base_name
# base name is not unique, let's find a unique name by appending a number
for number in range(1, 1000000):
name = base_name + str(number)
if name not in self._allocated_node_names:
self._allocated_node_names.add(name)
return name
raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)") | [
"def",
"update_allocated_node_name",
"(",
"self",
",",
"base_name",
")",
":",
"if",
"base_name",
"is",
"None",
":",
"return",
"None",
"base_name",
"=",
"re",
".",
"sub",
"(",
"r\"[ ]\"",
",",
"\"\"",
",",
"base_name",
")",
"if",
"base_name",
"in",
"self",
... | Updates a node name or generate a new if no node
name is available.
:param base_name: new node base name | [
"Updates",
"a",
"node",
"name",
"or",
"generate",
"a",
"new",
"if",
"no",
"node",
"name",
"is",
"available",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L359-L395 | train | 221,605 |
GNS3/gns3-server | gns3server/controller/project.py | Project.add_node_from_appliance | def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None):
"""
Create a node from an appliance
"""
try:
template = self.controller.appliances[appliance_id].data
except KeyError:
msg = "Appliance {} doesn't exist".format(appliance_id)
log.error(msg)
raise aiohttp.web.HTTPNotFound(text=msg)
template["x"] = x
template["y"] = y
node_type = template.pop("node_type")
compute = self.controller.get_compute(template.pop("server", compute_id))
name = template.pop("name")
default_name_format = template.pop("default_name_format", "{name}-{0}")
name = default_name_format.replace("{name}", name)
node_id = str(uuid.uuid4())
node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template)
return node | python | def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None):
"""
Create a node from an appliance
"""
try:
template = self.controller.appliances[appliance_id].data
except KeyError:
msg = "Appliance {} doesn't exist".format(appliance_id)
log.error(msg)
raise aiohttp.web.HTTPNotFound(text=msg)
template["x"] = x
template["y"] = y
node_type = template.pop("node_type")
compute = self.controller.get_compute(template.pop("server", compute_id))
name = template.pop("name")
default_name_format = template.pop("default_name_format", "{name}-{0}")
name = default_name_format.replace("{name}", name)
node_id = str(uuid.uuid4())
node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template)
return node | [
"def",
"add_node_from_appliance",
"(",
"self",
",",
"appliance_id",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"compute_id",
"=",
"None",
")",
":",
"try",
":",
"template",
"=",
"self",
".",
"controller",
".",
"appliances",
"[",
"appliance_id",
"]",
"... | Create a node from an appliance | [
"Create",
"a",
"node",
"from",
"an",
"appliance"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L406-L425 | train | 221,606 |
GNS3/gns3-server | gns3server/controller/project.py | Project.add_node | def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs):
"""
Create a node or return an existing node
:param dump: Dump topology to disk
:param kwargs: See the documentation of node
"""
if node_id in self._nodes:
return self._nodes[node_id]
node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs)
if compute not in self._project_created_on_compute:
# For a local server we send the project path
if compute.id == "local":
yield from compute.post("/projects", data={
"name": self._name,
"project_id": self._id,
"path": self._path
})
else:
yield from compute.post("/projects", data={
"name": self._name,
"project_id": self._id,
})
self._project_created_on_compute.add(compute)
yield from node.create()
self._nodes[node.id] = node
self.controller.notification.emit("node.created", node.__json__())
if dump:
self.dump()
return node | python | def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs):
"""
Create a node or return an existing node
:param dump: Dump topology to disk
:param kwargs: See the documentation of node
"""
if node_id in self._nodes:
return self._nodes[node_id]
node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs)
if compute not in self._project_created_on_compute:
# For a local server we send the project path
if compute.id == "local":
yield from compute.post("/projects", data={
"name": self._name,
"project_id": self._id,
"path": self._path
})
else:
yield from compute.post("/projects", data={
"name": self._name,
"project_id": self._id,
})
self._project_created_on_compute.add(compute)
yield from node.create()
self._nodes[node.id] = node
self.controller.notification.emit("node.created", node.__json__())
if dump:
self.dump()
return node | [
"def",
"add_node",
"(",
"self",
",",
"compute",
",",
"name",
",",
"node_id",
",",
"dump",
"=",
"True",
",",
"node_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"node_id",
"in",
"self",
".",
"_nodes",
":",
"return",
"self",
".",
"_nod... | Create a node or return an existing node
:param dump: Dump topology to disk
:param kwargs: See the documentation of node | [
"Create",
"a",
"node",
"or",
"return",
"an",
"existing",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L429-L461 | train | 221,607 |
GNS3/gns3-server | gns3server/controller/project.py | Project.__delete_node_links | def __delete_node_links(self, node):
"""
Delete all link connected to this node.
The operation use a lock to avoid cleaning links from
multiple nodes at the same time.
"""
for link in list(self._links.values()):
if node in link.nodes:
yield from self.delete_link(link.id, force_delete=True) | python | def __delete_node_links(self, node):
"""
Delete all link connected to this node.
The operation use a lock to avoid cleaning links from
multiple nodes at the same time.
"""
for link in list(self._links.values()):
if node in link.nodes:
yield from self.delete_link(link.id, force_delete=True) | [
"def",
"__delete_node_links",
"(",
"self",
",",
"node",
")",
":",
"for",
"link",
"in",
"list",
"(",
"self",
".",
"_links",
".",
"values",
"(",
")",
")",
":",
"if",
"node",
"in",
"link",
".",
"nodes",
":",
"yield",
"from",
"self",
".",
"delete_link",
... | Delete all link connected to this node.
The operation use a lock to avoid cleaning links from
multiple nodes at the same time. | [
"Delete",
"all",
"link",
"connected",
"to",
"this",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L464-L473 | train | 221,608 |
GNS3/gns3-server | gns3server/controller/project.py | Project.get_node | def get_node(self, node_id):
"""
Return the node or raise a 404 if the node is unknown
"""
try:
return self._nodes[node_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id)) | python | def get_node(self, node_id):
"""
Return the node or raise a 404 if the node is unknown
"""
try:
return self._nodes[node_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id)) | [
"def",
"get_node",
"(",
"self",
",",
"node_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_nodes",
"[",
"node_id",
"]",
"except",
"KeyError",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",
"(",
"text",
"=",
"\"Node ID {} doesn't exist\"",
".... | Return the node or raise a 404 if the node is unknown | [
"Return",
"the",
"node",
"or",
"raise",
"a",
"404",
"if",
"the",
"node",
"is",
"unknown"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L487-L494 | train | 221,609 |
GNS3/gns3-server | gns3server/controller/project.py | Project.add_drawing | def add_drawing(self, drawing_id=None, dump=True, **kwargs):
"""
Create an drawing or return an existing drawing
:param dump: Dump the topology to disk
:param kwargs: See the documentation of drawing
"""
if drawing_id not in self._drawings:
drawing = Drawing(self, drawing_id=drawing_id, **kwargs)
self._drawings[drawing.id] = drawing
self.controller.notification.emit("drawing.created", drawing.__json__())
if dump:
self.dump()
return drawing
return self._drawings[drawing_id] | python | def add_drawing(self, drawing_id=None, dump=True, **kwargs):
"""
Create an drawing or return an existing drawing
:param dump: Dump the topology to disk
:param kwargs: See the documentation of drawing
"""
if drawing_id not in self._drawings:
drawing = Drawing(self, drawing_id=drawing_id, **kwargs)
self._drawings[drawing.id] = drawing
self.controller.notification.emit("drawing.created", drawing.__json__())
if dump:
self.dump()
return drawing
return self._drawings[drawing_id] | [
"def",
"add_drawing",
"(",
"self",
",",
"drawing_id",
"=",
"None",
",",
"dump",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"drawing_id",
"not",
"in",
"self",
".",
"_drawings",
":",
"drawing",
"=",
"Drawing",
"(",
"self",
",",
"drawing_id",
... | Create an drawing or return an existing drawing
:param dump: Dump the topology to disk
:param kwargs: See the documentation of drawing | [
"Create",
"an",
"drawing",
"or",
"return",
"an",
"existing",
"drawing"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L512-L526 | train | 221,610 |
GNS3/gns3-server | gns3server/controller/project.py | Project.get_drawing | def get_drawing(self, drawing_id):
"""
Return the Drawing or raise a 404 if the drawing is unknown
"""
try:
return self._drawings[drawing_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id)) | python | def get_drawing(self, drawing_id):
"""
Return the Drawing or raise a 404 if the drawing is unknown
"""
try:
return self._drawings[drawing_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id)) | [
"def",
"get_drawing",
"(",
"self",
",",
"drawing_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_drawings",
"[",
"drawing_id",
"]",
"except",
"KeyError",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",
"(",
"text",
"=",
"\"Drawing ID {} doesn't... | Return the Drawing or raise a 404 if the drawing is unknown | [
"Return",
"the",
"Drawing",
"or",
"raise",
"a",
"404",
"if",
"the",
"drawing",
"is",
"unknown"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L529-L536 | train | 221,611 |
GNS3/gns3-server | gns3server/controller/project.py | Project.add_link | def add_link(self, link_id=None, dump=True):
"""
Create a link. By default the link is empty
:param dump: Dump topology to disk
"""
if link_id and link_id in self._links:
return self._links[link_id]
link = UDPLink(self, link_id=link_id)
self._links[link.id] = link
if dump:
self.dump()
return link | python | def add_link(self, link_id=None, dump=True):
"""
Create a link. By default the link is empty
:param dump: Dump topology to disk
"""
if link_id and link_id in self._links:
return self._links[link_id]
link = UDPLink(self, link_id=link_id)
self._links[link.id] = link
if dump:
self.dump()
return link | [
"def",
"add_link",
"(",
"self",
",",
"link_id",
"=",
"None",
",",
"dump",
"=",
"True",
")",
":",
"if",
"link_id",
"and",
"link_id",
"in",
"self",
".",
"_links",
":",
"return",
"self",
".",
"_links",
"[",
"link_id",
"]",
"link",
"=",
"UDPLink",
"(",
... | Create a link. By default the link is empty
:param dump: Dump topology to disk | [
"Create",
"a",
"link",
".",
"By",
"default",
"the",
"link",
"is",
"empty"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L548-L560 | train | 221,612 |
GNS3/gns3-server | gns3server/controller/project.py | Project.get_link | def get_link(self, link_id):
"""
Return the Link or raise a 404 if the link is unknown
"""
try:
return self._links[link_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id)) | python | def get_link(self, link_id):
"""
Return the Link or raise a 404 if the link is unknown
"""
try:
return self._links[link_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id)) | [
"def",
"get_link",
"(",
"self",
",",
"link_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_links",
"[",
"link_id",
"]",
"except",
"KeyError",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",
"(",
"text",
"=",
"\"Link ID {} doesn't exist\"",
".... | Return the Link or raise a 404 if the link is unknown | [
"Return",
"the",
"Link",
"or",
"raise",
"a",
"404",
"if",
"the",
"link",
"is",
"unknown"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L576-L583 | train | 221,613 |
GNS3/gns3-server | gns3server/controller/project.py | Project.get_snapshot | def get_snapshot(self, snapshot_id):
"""
Return the snapshot or raise a 404 if the snapshot is unknown
"""
try:
return self._snapshots[snapshot_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id)) | python | def get_snapshot(self, snapshot_id):
"""
Return the snapshot or raise a 404 if the snapshot is unknown
"""
try:
return self._snapshots[snapshot_id]
except KeyError:
raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id)) | [
"def",
"get_snapshot",
"(",
"self",
",",
"snapshot_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_snapshots",
"[",
"snapshot_id",
"]",
"except",
"KeyError",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",
"(",
"text",
"=",
"\"Snapshot ID {} do... | Return the snapshot or raise a 404 if the snapshot is unknown | [
"Return",
"the",
"snapshot",
"or",
"raise",
"a",
"404",
"if",
"the",
"snapshot",
"is",
"unknown"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L600-L607 | train | 221,614 |
GNS3/gns3-server | gns3server/controller/project.py | Project.snapshot | def snapshot(self, name):
"""
Snapshot the project
:param name: Name of the snapshot
"""
if name in [snap.name for snap in self.snapshots.values()]:
raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name))
snapshot = Snapshot(self, name=name)
try:
if os.path.exists(snapshot.path):
raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name))
os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True)
with tempfile.TemporaryDirectory() as tmpdir:
zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True)
try:
with open(snapshot.path, "wb") as f:
for data in zipstream:
f.write(data)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
self._snapshots[snapshot.id] = snapshot
return snapshot | python | def snapshot(self, name):
"""
Snapshot the project
:param name: Name of the snapshot
"""
if name in [snap.name for snap in self.snapshots.values()]:
raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name))
snapshot = Snapshot(self, name=name)
try:
if os.path.exists(snapshot.path):
raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name))
os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True)
with tempfile.TemporaryDirectory() as tmpdir:
zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True)
try:
with open(snapshot.path, "wb") as f:
for data in zipstream:
f.write(data)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
self._snapshots[snapshot.id] = snapshot
return snapshot | [
"def",
"snapshot",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"[",
"snap",
".",
"name",
"for",
"snap",
"in",
"self",
".",
"snapshots",
".",
"values",
"(",
")",
"]",
":",
"raise",
"aiohttp",
".",
"web_exceptions",
".",
"HTTPConflict",
"("... | Snapshot the project
:param name: Name of the snapshot | [
"Snapshot",
"the",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L611-L640 | train | 221,615 |
GNS3/gns3-server | gns3server/controller/project.py | Project._cleanPictures | def _cleanPictures(self):
"""
Delete unused images
"""
# Project have been deleted
if not os.path.exists(self.path):
return
try:
pictures = set(os.listdir(self.pictures_directory))
for drawing in self._drawings.values():
try:
pictures.remove(drawing.ressource_filename)
except KeyError:
pass
for pict in pictures:
os.remove(os.path.join(self.pictures_directory, pict))
except OSError as e:
log.warning(str(e)) | python | def _cleanPictures(self):
"""
Delete unused images
"""
# Project have been deleted
if not os.path.exists(self.path):
return
try:
pictures = set(os.listdir(self.pictures_directory))
for drawing in self._drawings.values():
try:
pictures.remove(drawing.ressource_filename)
except KeyError:
pass
for pict in pictures:
os.remove(os.path.join(self.pictures_directory, pict))
except OSError as e:
log.warning(str(e)) | [
"def",
"_cleanPictures",
"(",
"self",
")",
":",
"# Project have been deleted",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"return",
"try",
":",
"pictures",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"self",
".",... | Delete unused images | [
"Delete",
"unused",
"images"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L663-L682 | train | 221,616 |
GNS3/gns3-server | gns3server/controller/project.py | Project.delete_on_computes | def delete_on_computes(self):
"""
Delete the project on computes but not on controller
"""
for compute in list(self._project_created_on_compute):
if compute.id != "local":
yield from compute.delete("/projects/{}".format(self._id))
self._project_created_on_compute.remove(compute) | python | def delete_on_computes(self):
"""
Delete the project on computes but not on controller
"""
for compute in list(self._project_created_on_compute):
if compute.id != "local":
yield from compute.delete("/projects/{}".format(self._id))
self._project_created_on_compute.remove(compute) | [
"def",
"delete_on_computes",
"(",
"self",
")",
":",
"for",
"compute",
"in",
"list",
"(",
"self",
".",
"_project_created_on_compute",
")",
":",
"if",
"compute",
".",
"id",
"!=",
"\"local\"",
":",
"yield",
"from",
"compute",
".",
"delete",
"(",
"\"/projects/{}... | Delete the project on computes but not on controller | [
"Delete",
"the",
"project",
"on",
"computes",
"but",
"not",
"on",
"controller"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L701-L708 | train | 221,617 |
GNS3/gns3-server | gns3server/controller/project.py | Project.duplicate | def duplicate(self, name=None, location=None):
"""
Duplicate a project
It's the save as feature of the 1.X. It's implemented on top of the
export / import features. It will generate a gns3p and reimport it.
It's a little slower but we have only one implementation to maintain.
:param name: Name of the new project. A new one will be generated in case of conflicts
:param location: Parent directory of the new project
"""
# If the project was not open we open it temporary
previous_status = self._status
if self._status == "closed":
yield from self.open()
self.dump()
try:
with tempfile.TemporaryDirectory() as tmpdir:
zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True)
with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f:
for data in zipstream:
f.write(data)
with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f:
project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True)
except (OSError, UnicodeEncodeError) as e:
raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e)))
if previous_status == "closed":
yield from self.close()
return project | python | def duplicate(self, name=None, location=None):
"""
Duplicate a project
It's the save as feature of the 1.X. It's implemented on top of the
export / import features. It will generate a gns3p and reimport it.
It's a little slower but we have only one implementation to maintain.
:param name: Name of the new project. A new one will be generated in case of conflicts
:param location: Parent directory of the new project
"""
# If the project was not open we open it temporary
previous_status = self._status
if self._status == "closed":
yield from self.open()
self.dump()
try:
with tempfile.TemporaryDirectory() as tmpdir:
zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True)
with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f:
for data in zipstream:
f.write(data)
with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f:
project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True)
except (OSError, UnicodeEncodeError) as e:
raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e)))
if previous_status == "closed":
yield from self.close()
return project | [
"def",
"duplicate",
"(",
"self",
",",
"name",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"# If the project was not open we open it temporary",
"previous_status",
"=",
"self",
".",
"_status",
"if",
"self",
".",
"_status",
"==",
"\"closed\"",
":",
"yield... | Duplicate a project
It's the save as feature of the 1.X. It's implemented on top of the
export / import features. It will generate a gns3p and reimport it.
It's a little slower but we have only one implementation to maintain.
:param name: Name of the new project. A new one will be generated in case of conflicts
:param location: Parent directory of the new project | [
"Duplicate",
"a",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L844-L875 | train | 221,618 |
GNS3/gns3-server | gns3server/controller/project.py | Project.is_running | def is_running(self):
"""
If a node is started or paused return True
"""
for node in self._nodes.values():
# Some node type are always running we ignore them
if node.status != "stopped" and not node.is_always_running():
return True
return False | python | def is_running(self):
"""
If a node is started or paused return True
"""
for node in self._nodes.values():
# Some node type are always running we ignore them
if node.status != "stopped" and not node.is_always_running():
return True
return False | [
"def",
"is_running",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"_nodes",
".",
"values",
"(",
")",
":",
"# Some node type are always running we ignore them",
"if",
"node",
".",
"status",
"!=",
"\"stopped\"",
"and",
"not",
"node",
".",
"is_always_... | If a node is started or paused return True | [
"If",
"a",
"node",
"is",
"started",
"or",
"paused",
"return",
"True"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L877-L885 | train | 221,619 |
GNS3/gns3-server | gns3server/controller/project.py | Project.dump | def dump(self):
"""
Dump topology to disk
"""
try:
topo = project_to_topology(self)
path = self._topology_file()
log.debug("Write %s", path)
with open(path + ".tmp", "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4, sort_keys=True)
shutil.move(path + ".tmp", path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e)) | python | def dump(self):
"""
Dump topology to disk
"""
try:
topo = project_to_topology(self)
path = self._topology_file()
log.debug("Write %s", path)
with open(path + ".tmp", "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4, sort_keys=True)
shutil.move(path + ".tmp", path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e)) | [
"def",
"dump",
"(",
"self",
")",
":",
"try",
":",
"topo",
"=",
"project_to_topology",
"(",
"self",
")",
"path",
"=",
"self",
".",
"_topology_file",
"(",
")",
"log",
".",
"debug",
"(",
"\"Write %s\"",
",",
"path",
")",
"with",
"open",
"(",
"path",
"+"... | Dump topology to disk | [
"Dump",
"topology",
"to",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L887-L899 | train | 221,620 |
GNS3/gns3-server | gns3server/controller/project.py | Project.start_all | def start_all(self):
"""
Start all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.start)
yield from pool.join() | python | def start_all(self):
"""
Start all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.start)
yield from pool.join() | [
"def",
"start_all",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"concurrency",
"=",
"3",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"pool",
".",
"append",
"(",
"node",
".",
"start",
")",
"yield",
"from",
"p... | Start all nodes | [
"Start",
"all",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L902-L909 | train | 221,621 |
GNS3/gns3-server | gns3server/controller/project.py | Project.stop_all | def stop_all(self):
"""
Stop all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() | python | def stop_all(self):
"""
Stop all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() | [
"def",
"stop_all",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"concurrency",
"=",
"3",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"pool",
".",
"append",
"(",
"node",
".",
"stop",
")",
"yield",
"from",
"poo... | Stop all nodes | [
"Stop",
"all",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L912-L919 | train | 221,622 |
GNS3/gns3-server | gns3server/controller/project.py | Project.suspend_all | def suspend_all(self):
"""
Suspend all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.suspend)
yield from pool.join() | python | def suspend_all(self):
"""
Suspend all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.suspend)
yield from pool.join() | [
"def",
"suspend_all",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"concurrency",
"=",
"3",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"pool",
".",
"append",
"(",
"node",
".",
"suspend",
")",
"yield",
"from",
... | Suspend all nodes | [
"Suspend",
"all",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L922-L929 | train | 221,623 |
GNS3/gns3-server | gns3server/utils/asyncio/input_stream.py | InputStream._get_match | def _get_match(self, prefix):
"""
Return the key that maps to this prefix.
"""
# (hard coded) If we match a CPR response, return Keys.CPRResponse.
# (This one doesn't fit in the ANSI_SEQUENCES, because it contains
# integer variables.)
if _cpr_response_re.match(prefix):
return Keys.CPRResponse
elif _mouse_event_re.match(prefix):
return Keys.Vt100MouseEvent
# Otherwise, use the mappings.
try:
return ANSI_SEQUENCES[prefix]
except KeyError:
return None | python | def _get_match(self, prefix):
"""
Return the key that maps to this prefix.
"""
# (hard coded) If we match a CPR response, return Keys.CPRResponse.
# (This one doesn't fit in the ANSI_SEQUENCES, because it contains
# integer variables.)
if _cpr_response_re.match(prefix):
return Keys.CPRResponse
elif _mouse_event_re.match(prefix):
return Keys.Vt100MouseEvent
# Otherwise, use the mappings.
try:
return ANSI_SEQUENCES[prefix]
except KeyError:
return None | [
"def",
"_get_match",
"(",
"self",
",",
"prefix",
")",
":",
"# (hard coded) If we match a CPR response, return Keys.CPRResponse.",
"# (This one doesn't fit in the ANSI_SEQUENCES, because it contains",
"# integer variables.)",
"if",
"_cpr_response_re",
".",
"match",
"(",
"prefix",
")... | Return the key that maps to this prefix. | [
"Return",
"the",
"key",
"that",
"maps",
"to",
"this",
"prefix",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L259-L276 | train | 221,624 |
GNS3/gns3-server | gns3server/utils/asyncio/input_stream.py | InputStream._call_handler | def _call_handler(self, key, insert_text):
"""
Callback to handler.
"""
if isinstance(key, tuple):
for k in key:
self._call_handler(k, insert_text)
else:
if key == Keys.BracketedPaste:
self._in_bracketed_paste = True
self._paste_buffer = ''
else:
self.feed_key_callback(KeyPress(key, insert_text)) | python | def _call_handler(self, key, insert_text):
"""
Callback to handler.
"""
if isinstance(key, tuple):
for k in key:
self._call_handler(k, insert_text)
else:
if key == Keys.BracketedPaste:
self._in_bracketed_paste = True
self._paste_buffer = ''
else:
self.feed_key_callback(KeyPress(key, insert_text)) | [
"def",
"_call_handler",
"(",
"self",
",",
"key",
",",
"insert_text",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"for",
"k",
"in",
"key",
":",
"self",
".",
"_call_handler",
"(",
"k",
",",
"insert_text",
")",
"else",
":",
"if",
... | Callback to handler. | [
"Callback",
"to",
"handler",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L328-L340 | train | 221,625 |
GNS3/gns3-server | gns3server/utils/asyncio/input_stream.py | InputStream.feed | def feed(self, data):
"""
Feed the input stream.
:param data: Input string (unicode).
"""
assert isinstance(data, six.text_type)
if _DEBUG_RENDERER_INPUT:
self.LOG.write(repr(data).encode('utf-8') + b'\n')
self.LOG.flush()
# Handle bracketed paste. (We bypass the parser that matches all other
# key presses and keep reading input until we see the end mark.)
# This is much faster then parsing character by character.
if self._in_bracketed_paste:
self._paste_buffer += data
end_mark = '\x1b[201~'
if end_mark in self._paste_buffer:
end_index = self._paste_buffer.index(end_mark)
# Feed content to key bindings.
paste_content = self._paste_buffer[:end_index]
self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content))
# Quit bracketed paste mode and handle remaining input.
self._in_bracketed_paste = False
remaining = self._paste_buffer[end_index + len(end_mark):]
self._paste_buffer = ''
self.feed(remaining)
# Handle normal input character by character.
else:
for i, c in enumerate(data):
if self._in_bracketed_paste:
# Quit loop and process from this position when the parser
# entered bracketed paste.
self.feed(data[i:])
break
else:
# Replace \r by \n. (Some clients send \r instead of \n
# when enter is pressed. E.g. telnet and some other
# terminals.)
# XXX: We should remove this in a future version. It *is*
# now possible to recognise the difference.
# (We remove ICRNL/INLCR/IGNCR below.)
# However, this breaks IPython and maybe other applications,
# because they bind ControlJ (\n) for handling the Enter key.
# When this is removed, replace Enter=ControlJ by
# Enter=ControlM in keys.py.
if c == '\r':
c = '\n'
self._input_parser.send(c) | python | def feed(self, data):
"""
Feed the input stream.
:param data: Input string (unicode).
"""
assert isinstance(data, six.text_type)
if _DEBUG_RENDERER_INPUT:
self.LOG.write(repr(data).encode('utf-8') + b'\n')
self.LOG.flush()
# Handle bracketed paste. (We bypass the parser that matches all other
# key presses and keep reading input until we see the end mark.)
# This is much faster then parsing character by character.
if self._in_bracketed_paste:
self._paste_buffer += data
end_mark = '\x1b[201~'
if end_mark in self._paste_buffer:
end_index = self._paste_buffer.index(end_mark)
# Feed content to key bindings.
paste_content = self._paste_buffer[:end_index]
self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content))
# Quit bracketed paste mode and handle remaining input.
self._in_bracketed_paste = False
remaining = self._paste_buffer[end_index + len(end_mark):]
self._paste_buffer = ''
self.feed(remaining)
# Handle normal input character by character.
else:
for i, c in enumerate(data):
if self._in_bracketed_paste:
# Quit loop and process from this position when the parser
# entered bracketed paste.
self.feed(data[i:])
break
else:
# Replace \r by \n. (Some clients send \r instead of \n
# when enter is pressed. E.g. telnet and some other
# terminals.)
# XXX: We should remove this in a future version. It *is*
# now possible to recognise the difference.
# (We remove ICRNL/INLCR/IGNCR below.)
# However, this breaks IPython and maybe other applications,
# because they bind ControlJ (\n) for handling the Enter key.
# When this is removed, replace Enter=ControlJ by
# Enter=ControlM in keys.py.
if c == '\r':
c = '\n'
self._input_parser.send(c) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
"if",
"_DEBUG_RENDERER_INPUT",
":",
"self",
".",
"LOG",
".",
"write",
"(",
"repr",
"(",
"data",
")",
".",
"encode",
"(",
"'utf-... | Feed the input stream.
:param data: Input string (unicode). | [
"Feed",
"the",
"input",
"stream",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L342-L398 | train | 221,626 |
GNS3/gns3-server | gns3server/compute/docker/__init__.py | Docker.query | def query(self, method, path, data={}, params={}):
"""
Make a query to the docker daemon and decode the request
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
"""
response = yield from self.http_query(method, path, data=data, params=params)
body = yield from response.read()
if body and len(body):
if response.headers['CONTENT-TYPE'] == 'application/json':
body = json.loads(body.decode("utf-8"))
else:
body = body.decode("utf-8")
log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body)
return body | python | def query(self, method, path, data={}, params={}):
"""
Make a query to the docker daemon and decode the request
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
"""
response = yield from self.http_query(method, path, data=data, params=params)
body = yield from response.read()
if body and len(body):
if response.headers['CONTENT-TYPE'] == 'application/json':
body = json.loads(body.decode("utf-8"))
else:
body = body.decode("utf-8")
log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body)
return body | [
"def",
"query",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"{",
"}",
",",
"params",
"=",
"{",
"}",
")",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"method",
",",
"path",
",",
"data",
"=",
"data",
",",
... | Make a query to the docker daemon and decode the request
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg | [
"Make",
"a",
"query",
"to",
"the",
"docker",
"daemon",
"and",
"decode",
"the",
"request"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L96-L114 | train | 221,627 |
GNS3/gns3-server | gns3server/compute/docker/__init__.py | Docker.http_query | def http_query(self, method, path, data={}, params={}, timeout=300):
"""
Make a query to the docker daemon
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionnary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
:param timeout: Timeout
:returns: HTTP response
"""
data = json.dumps(data)
if timeout is None:
timeout = 60 * 60 * 24 * 31 # One month timeout
if path == 'version':
url = "http://docker/v1.12/" + path # API of docker v1.0
else:
url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path
try:
if path != "version": # version is use by check connection
yield from self._check_connection()
if self._session is None or self._session.closed:
connector = self.connector()
self._session = aiohttp.ClientSession(connector=connector)
response = yield from self._session.request(
method,
url,
params=params,
data=data,
headers={"content-type": "application/json", },
timeout=timeout
)
except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e:
raise DockerError("Docker has returned an error: {}".format(str(e)))
except (asyncio.TimeoutError):
raise DockerError("Docker timeout " + method + " " + path)
if response.status >= 300:
body = yield from response.read()
try:
body = json.loads(body.decode("utf-8"))["message"]
except ValueError:
pass
log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body)
if response.status == 304:
raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body))
elif response.status == 404:
raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body))
else:
raise DockerError("Docker has returned an error: {} {}".format(response.status, body))
return response | python | def http_query(self, method, path, data={}, params={}, timeout=300):
"""
Make a query to the docker daemon
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionnary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
:param timeout: Timeout
:returns: HTTP response
"""
data = json.dumps(data)
if timeout is None:
timeout = 60 * 60 * 24 * 31 # One month timeout
if path == 'version':
url = "http://docker/v1.12/" + path # API of docker v1.0
else:
url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path
try:
if path != "version": # version is use by check connection
yield from self._check_connection()
if self._session is None or self._session.closed:
connector = self.connector()
self._session = aiohttp.ClientSession(connector=connector)
response = yield from self._session.request(
method,
url,
params=params,
data=data,
headers={"content-type": "application/json", },
timeout=timeout
)
except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e:
raise DockerError("Docker has returned an error: {}".format(str(e)))
except (asyncio.TimeoutError):
raise DockerError("Docker timeout " + method + " " + path)
if response.status >= 300:
body = yield from response.read()
try:
body = json.loads(body.decode("utf-8"))["message"]
except ValueError:
pass
log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body)
if response.status == 304:
raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body))
elif response.status == 404:
raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body))
else:
raise DockerError("Docker has returned an error: {} {}".format(response.status, body))
return response | [
"def",
"http_query",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"{",
"}",
",",
"params",
"=",
"{",
"}",
",",
"timeout",
"=",
"300",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"if",
"timeout",
"is",
"None",
":... | Make a query to the docker daemon
:param method: HTTP method
:param path: Endpoint in API
:param data: Dictionnary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
:param timeout: Timeout
:returns: HTTP response | [
"Make",
"a",
"query",
"to",
"the",
"docker",
"daemon"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L117-L167 | train | 221,628 |
GNS3/gns3-server | gns3server/compute/docker/__init__.py | Docker.websocket_query | def websocket_query(self, path, params={}):
"""
Open a websocket connection
:param path: Endpoint in API
:param params: Parameters added as a query arg
:returns: Websocket
"""
url = "http://docker/v" + self._api_version + "/" + path
connection = yield from self._session.ws_connect(url,
origin="http://docker",
autoping=True)
return connection | python | def websocket_query(self, path, params={}):
"""
Open a websocket connection
:param path: Endpoint in API
:param params: Parameters added as a query arg
:returns: Websocket
"""
url = "http://docker/v" + self._api_version + "/" + path
connection = yield from self._session.ws_connect(url,
origin="http://docker",
autoping=True)
return connection | [
"def",
"websocket_query",
"(",
"self",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"\"http://docker/v\"",
"+",
"self",
".",
"_api_version",
"+",
"\"/\"",
"+",
"path",
"connection",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
... | Open a websocket connection
:param path: Endpoint in API
:param params: Parameters added as a query arg
:returns: Websocket | [
"Open",
"a",
"websocket",
"connection"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L170-L183 | train | 221,629 |
GNS3/gns3-server | gns3server/compute/docker/__init__.py | Docker.list_images | def list_images(self):
"""Gets Docker image list.
:returns: list of dicts
:rtype: list
"""
images = []
for image in (yield from self.query("GET", "images/json", params={"all": 0})):
if image['RepoTags']:
for tag in image['RepoTags']:
if tag != "<none>:<none>":
images.append({'image': tag})
return sorted(images, key=lambda i: i['image']) | python | def list_images(self):
"""Gets Docker image list.
:returns: list of dicts
:rtype: list
"""
images = []
for image in (yield from self.query("GET", "images/json", params={"all": 0})):
if image['RepoTags']:
for tag in image['RepoTags']:
if tag != "<none>:<none>":
images.append({'image': tag})
return sorted(images, key=lambda i: i['image']) | [
"def",
"list_images",
"(",
"self",
")",
":",
"images",
"=",
"[",
"]",
"for",
"image",
"in",
"(",
"yield",
"from",
"self",
".",
"query",
"(",
"\"GET\"",
",",
"\"images/json\"",
",",
"params",
"=",
"{",
"\"all\"",
":",
"0",
"}",
")",
")",
":",
"if",
... | Gets Docker image list.
:returns: list of dicts
:rtype: list | [
"Gets",
"Docker",
"image",
"list",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L228-L240 | train | 221,630 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.get_kvm_archs | def get_kvm_archs():
"""
Gets a list of architectures for which KVM is available on this server.
:returns: List of architectures for which KVM is available on this server.
"""
kvm = []
if not os.path.exists("/dev/kvm"):
return kvm
arch = platform.machine()
if arch == "x86_64":
kvm.append("x86_64")
kvm.append("i386")
elif arch == "i386":
kvm.append("i386")
else:
kvm.append(platform.machine())
return kvm | python | def get_kvm_archs():
"""
Gets a list of architectures for which KVM is available on this server.
:returns: List of architectures for which KVM is available on this server.
"""
kvm = []
if not os.path.exists("/dev/kvm"):
return kvm
arch = platform.machine()
if arch == "x86_64":
kvm.append("x86_64")
kvm.append("i386")
elif arch == "i386":
kvm.append("i386")
else:
kvm.append(platform.machine())
return kvm | [
"def",
"get_kvm_archs",
"(",
")",
":",
"kvm",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"/dev/kvm\"",
")",
":",
"return",
"kvm",
"arch",
"=",
"platform",
".",
"machine",
"(",
")",
"if",
"arch",
"==",
"\"x86_64\"",
":",
"k... | Gets a list of architectures for which KVM is available on this server.
:returns: List of architectures for which KVM is available on this server. | [
"Gets",
"a",
"list",
"of",
"architectures",
"for",
"which",
"KVM",
"is",
"available",
"on",
"this",
"server",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L45-L64 | train | 221,631 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.paths_list | def paths_list():
"""
Gets a folder list of possibly available QEMU binaries on the host.
:returns: List of folders where Qemu binaries MAY reside.
"""
paths = set()
try:
paths.add(os.getcwd())
except FileNotFoundError:
log.warning("The current working directory doesn't exist")
if "PATH" in os.environ:
paths.update(os.environ["PATH"].split(os.pathsep))
else:
log.warning("The PATH environment variable doesn't exist")
# look for Qemu binaries in the current working directory and $PATH
if sys.platform.startswith("win"):
# add specific Windows paths
if hasattr(sys, "frozen"):
# add any qemu dir in the same location as gns3server.exe to the list of paths
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
for f in os.listdir(exec_dir):
if f.lower().startswith("qemu"):
paths.add(os.path.join(exec_dir, f))
if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]):
paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu"))
if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]):
paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu"))
elif sys.platform.startswith("darwin"):
if hasattr(sys, "frozen"):
# add specific locations on Mac OS X regardless of what's in $PATH
paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"])
try:
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/")))
# If the user run the server by hand from outside
except FileNotFoundError:
paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin")
return paths | python | def paths_list():
"""
Gets a folder list of possibly available QEMU binaries on the host.
:returns: List of folders where Qemu binaries MAY reside.
"""
paths = set()
try:
paths.add(os.getcwd())
except FileNotFoundError:
log.warning("The current working directory doesn't exist")
if "PATH" in os.environ:
paths.update(os.environ["PATH"].split(os.pathsep))
else:
log.warning("The PATH environment variable doesn't exist")
# look for Qemu binaries in the current working directory and $PATH
if sys.platform.startswith("win"):
# add specific Windows paths
if hasattr(sys, "frozen"):
# add any qemu dir in the same location as gns3server.exe to the list of paths
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
for f in os.listdir(exec_dir):
if f.lower().startswith("qemu"):
paths.add(os.path.join(exec_dir, f))
if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]):
paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu"))
if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]):
paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu"))
elif sys.platform.startswith("darwin"):
if hasattr(sys, "frozen"):
# add specific locations on Mac OS X regardless of what's in $PATH
paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"])
try:
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/")))
# If the user run the server by hand from outside
except FileNotFoundError:
paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin")
return paths | [
"def",
"paths_list",
"(",
")",
":",
"paths",
"=",
"set",
"(",
")",
"try",
":",
"paths",
".",
"add",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"except",
"FileNotFoundError",
":",
"log",
".",
"warning",
"(",
"\"The current working directory doesn't exist\"",
... | Gets a folder list of possibly available QEMU binaries on the host.
:returns: List of folders where Qemu binaries MAY reside. | [
"Gets",
"a",
"folder",
"list",
"of",
"possibly",
"available",
"QEMU",
"binaries",
"on",
"the",
"host",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L67-L107 | train | 221,632 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.binary_list | def binary_list(archs=None):
"""
Gets QEMU binaries list available on the host.
:returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu}
"""
qemus = []
for path in Qemu.paths_list():
try:
for f in os.listdir(path):
if f.endswith("-spice"):
continue
if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \
os.access(os.path.join(path, f), os.X_OK) and \
os.path.isfile(os.path.join(path, f)):
if archs is not None:
for arch in archs:
if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)):
qemu_path = os.path.join(path, f)
version = yield from Qemu.get_qemu_version(qemu_path)
qemus.append({"path": qemu_path, "version": version})
else:
qemu_path = os.path.join(path, f)
version = yield from Qemu.get_qemu_version(qemu_path)
qemus.append({"path": qemu_path, "version": version})
except OSError:
continue
return qemus | python | def binary_list(archs=None):
"""
Gets QEMU binaries list available on the host.
:returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu}
"""
qemus = []
for path in Qemu.paths_list():
try:
for f in os.listdir(path):
if f.endswith("-spice"):
continue
if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \
os.access(os.path.join(path, f), os.X_OK) and \
os.path.isfile(os.path.join(path, f)):
if archs is not None:
for arch in archs:
if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)):
qemu_path = os.path.join(path, f)
version = yield from Qemu.get_qemu_version(qemu_path)
qemus.append({"path": qemu_path, "version": version})
else:
qemu_path = os.path.join(path, f)
version = yield from Qemu.get_qemu_version(qemu_path)
qemus.append({"path": qemu_path, "version": version})
except OSError:
continue
return qemus | [
"def",
"binary_list",
"(",
"archs",
"=",
"None",
")",
":",
"qemus",
"=",
"[",
"]",
"for",
"path",
"in",
"Qemu",
".",
"paths_list",
"(",
")",
":",
"try",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"f",
".",
"endswi... | Gets QEMU binaries list available on the host.
:returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu} | [
"Gets",
"QEMU",
"binaries",
"list",
"available",
"on",
"the",
"host",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L110-L140 | train | 221,633 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.img_binary_list | def img_binary_list():
"""
Gets QEMU-img binaries list available on the host.
:returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img}
"""
qemu_imgs = []
for path in Qemu.paths_list():
try:
for f in os.listdir(path):
if (f == "qemu-img" or f == "qemu-img.exe") and \
os.access(os.path.join(path, f), os.X_OK) and \
os.path.isfile(os.path.join(path, f)):
qemu_path = os.path.join(path, f)
version = yield from Qemu._get_qemu_img_version(qemu_path)
qemu_imgs.append({"path": qemu_path, "version": version})
except OSError:
continue
return qemu_imgs | python | def img_binary_list():
"""
Gets QEMU-img binaries list available on the host.
:returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img}
"""
qemu_imgs = []
for path in Qemu.paths_list():
try:
for f in os.listdir(path):
if (f == "qemu-img" or f == "qemu-img.exe") and \
os.access(os.path.join(path, f), os.X_OK) and \
os.path.isfile(os.path.join(path, f)):
qemu_path = os.path.join(path, f)
version = yield from Qemu._get_qemu_img_version(qemu_path)
qemu_imgs.append({"path": qemu_path, "version": version})
except OSError:
continue
return qemu_imgs | [
"def",
"img_binary_list",
"(",
")",
":",
"qemu_imgs",
"=",
"[",
"]",
"for",
"path",
"in",
"Qemu",
".",
"paths_list",
"(",
")",
":",
"try",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"(",
"f",
"==",
"\"qemu-img\"",
"... | Gets QEMU-img binaries list available on the host.
:returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img} | [
"Gets",
"QEMU",
"-",
"img",
"binaries",
"list",
"available",
"on",
"the",
"host",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L143-L162 | train | 221,634 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.get_qemu_version | def get_qemu_version(qemu_path):
"""
Gets the Qemu version.
:param qemu_path: path to Qemu executable.
"""
if sys.platform.startswith("win"):
# Qemu on Windows doesn't return anything with parameter -version
# look for a version number in version.txt file in the same directory instead
version_file = os.path.join(os.path.dirname(qemu_path), "version.txt")
if os.path.isfile(version_file):
try:
with open(version_file, "rb") as file:
version = file.read().decode("utf-8").strip()
match = re.search("[0-9\.]+", version)
if match:
return version
except (UnicodeDecodeError, OSError) as e:
log.warn("could not read {}: {}".format(version_file, e))
return ""
else:
try:
output = yield from subprocess_check_output(qemu_path, "-version")
match = re.search("version\s+([0-9a-z\-\.]+)", output)
if match:
version = match.group(1)
return version
else:
raise QemuError("Could not determine the Qemu version for {}".format(qemu_path))
except subprocess.SubprocessError as e:
raise QemuError("Error while looking for the Qemu version: {}".format(e)) | python | def get_qemu_version(qemu_path):
"""
Gets the Qemu version.
:param qemu_path: path to Qemu executable.
"""
if sys.platform.startswith("win"):
# Qemu on Windows doesn't return anything with parameter -version
# look for a version number in version.txt file in the same directory instead
version_file = os.path.join(os.path.dirname(qemu_path), "version.txt")
if os.path.isfile(version_file):
try:
with open(version_file, "rb") as file:
version = file.read().decode("utf-8").strip()
match = re.search("[0-9\.]+", version)
if match:
return version
except (UnicodeDecodeError, OSError) as e:
log.warn("could not read {}: {}".format(version_file, e))
return ""
else:
try:
output = yield from subprocess_check_output(qemu_path, "-version")
match = re.search("version\s+([0-9a-z\-\.]+)", output)
if match:
version = match.group(1)
return version
else:
raise QemuError("Could not determine the Qemu version for {}".format(qemu_path))
except subprocess.SubprocessError as e:
raise QemuError("Error while looking for the Qemu version: {}".format(e)) | [
"def",
"get_qemu_version",
"(",
"qemu_path",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# Qemu on Windows doesn't return anything with parameter -version",
"# look for a version number in version.txt file in the same directory instead",
... | Gets the Qemu version.
:param qemu_path: path to Qemu executable. | [
"Gets",
"the",
"Qemu",
"version",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L166-L197 | train | 221,635 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu._get_qemu_img_version | def _get_qemu_img_version(qemu_img_path):
"""
Gets the Qemu-img version.
:param qemu_img_path: path to Qemu-img executable.
"""
try:
output = yield from subprocess_check_output(qemu_img_path, "--version")
match = re.search("version\s+([0-9a-z\-\.]+)", output)
if match:
version = match.group(1)
return version
else:
raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path))
except subprocess.SubprocessError as e:
raise QemuError("Error while looking for the Qemu-img version: {}".format(e)) | python | def _get_qemu_img_version(qemu_img_path):
"""
Gets the Qemu-img version.
:param qemu_img_path: path to Qemu-img executable.
"""
try:
output = yield from subprocess_check_output(qemu_img_path, "--version")
match = re.search("version\s+([0-9a-z\-\.]+)", output)
if match:
version = match.group(1)
return version
else:
raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path))
except subprocess.SubprocessError as e:
raise QemuError("Error while looking for the Qemu-img version: {}".format(e)) | [
"def",
"_get_qemu_img_version",
"(",
"qemu_img_path",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"subprocess_check_output",
"(",
"qemu_img_path",
",",
"\"--version\"",
")",
"match",
"=",
"re",
".",
"search",
"(",
"\"version\\s+([0-9a-z\\-\\.]+)\"",
",",
... | Gets the Qemu-img version.
:param qemu_img_path: path to Qemu-img executable. | [
"Gets",
"the",
"Qemu",
"-",
"img",
"version",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L201-L217 | train | 221,636 |
GNS3/gns3-server | gns3server/compute/qemu/__init__.py | Qemu.create_disk | def create_disk(self, qemu_img, path, options):
"""
Create a qemu disk with qemu-img
:param qemu_img: qemu-img binary path
:param path: Image path
:param options: Disk image creation options
"""
try:
img_format = options.pop("format")
img_size = options.pop("size")
if not os.path.isabs(path):
directory = self.get_images_directory()
os.makedirs(directory, exist_ok=True)
path = os.path.join(directory, os.path.basename(path))
try:
if os.path.exists(path):
raise QemuError("Could not create disk image {} already exist".format(path))
except UnicodeEncodeError:
raise QemuError("Could not create disk image {}, "
"path contains characters not supported by filesystem".format(path))
command = [qemu_img, "create", "-f", img_format]
for option in sorted(options.keys()):
command.extend(["-o", "{}={}".format(option, options[option])])
command.append(path)
command.append("{}M".format(img_size))
process = yield from asyncio.create_subprocess_exec(*command)
yield from process.wait()
except (OSError, subprocess.SubprocessError) as e:
raise QemuError("Could not create disk image {}:{}".format(path, e)) | python | def create_disk(self, qemu_img, path, options):
"""
Create a qemu disk with qemu-img
:param qemu_img: qemu-img binary path
:param path: Image path
:param options: Disk image creation options
"""
try:
img_format = options.pop("format")
img_size = options.pop("size")
if not os.path.isabs(path):
directory = self.get_images_directory()
os.makedirs(directory, exist_ok=True)
path = os.path.join(directory, os.path.basename(path))
try:
if os.path.exists(path):
raise QemuError("Could not create disk image {} already exist".format(path))
except UnicodeEncodeError:
raise QemuError("Could not create disk image {}, "
"path contains characters not supported by filesystem".format(path))
command = [qemu_img, "create", "-f", img_format]
for option in sorted(options.keys()):
command.extend(["-o", "{}={}".format(option, options[option])])
command.append(path)
command.append("{}M".format(img_size))
process = yield from asyncio.create_subprocess_exec(*command)
yield from process.wait()
except (OSError, subprocess.SubprocessError) as e:
raise QemuError("Could not create disk image {}:{}".format(path, e)) | [
"def",
"create_disk",
"(",
"self",
",",
"qemu_img",
",",
"path",
",",
"options",
")",
":",
"try",
":",
"img_format",
"=",
"options",
".",
"pop",
"(",
"\"format\"",
")",
"img_size",
"=",
"options",
".",
"pop",
"(",
"\"size\"",
")",
"if",
"not",
"os",
... | Create a qemu disk with qemu-img
:param qemu_img: qemu-img binary path
:param path: Image path
:param options: Disk image creation options | [
"Create",
"a",
"qemu",
"disk",
"with",
"qemu",
"-",
"img"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L233-L267 | train | 221,637 |
jmcarpenter2/swifter | swifter/swifter.py | _SwifterObject.set_npartitions | def set_npartitions(self, npartitions=None):
"""
Set the number of partitions to use for dask
"""
if npartitions is None:
self._npartitions = cpu_count() * 2
else:
self._npartitions = npartitions
return self | python | def set_npartitions(self, npartitions=None):
"""
Set the number of partitions to use for dask
"""
if npartitions is None:
self._npartitions = cpu_count() * 2
else:
self._npartitions = npartitions
return self | [
"def",
"set_npartitions",
"(",
"self",
",",
"npartitions",
"=",
"None",
")",
":",
"if",
"npartitions",
"is",
"None",
":",
"self",
".",
"_npartitions",
"=",
"cpu_count",
"(",
")",
"*",
"2",
"else",
":",
"self",
".",
"_npartitions",
"=",
"npartitions",
"re... | Set the number of partitions to use for dask | [
"Set",
"the",
"number",
"of",
"partitions",
"to",
"use",
"for",
"dask"
] | ed5fc3235b43f981fa58ac9bc982c8209d4e3df3 | https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L39-L47 | train | 221,638 |
jmcarpenter2/swifter | swifter/swifter.py | _SwifterObject.rolling | def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None):
"""
Create a swifter rolling object
"""
kwds = {
"window": window,
"min_periods": min_periods,
"center": center,
"win_type": win_type,
"on": on,
"axis": axis,
"closed": closed,
}
return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds) | python | def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None):
"""
Create a swifter rolling object
"""
kwds = {
"window": window,
"min_periods": min_periods,
"center": center,
"win_type": win_type,
"on": on,
"axis": axis,
"closed": closed,
}
return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds) | [
"def",
"rolling",
"(",
"self",
",",
"window",
",",
"min_periods",
"=",
"None",
",",
"center",
"=",
"False",
",",
"win_type",
"=",
"None",
",",
"on",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"closed",
"=",
"None",
")",
":",
"kwds",
"=",
"{",
"\"wi... | Create a swifter rolling object | [
"Create",
"a",
"swifter",
"rolling",
"object"
] | ed5fc3235b43f981fa58ac9bc982c8209d4e3df3 | https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L78-L91 | train | 221,639 |
jmcarpenter2/swifter | swifter/swifter.py | Transformation.apply | def apply(self, func, *args, **kwds):
"""
Apply the function to the transformed swifter object
"""
# estimate time to pandas apply
wrapped = self._wrapped_apply(func, *args, **kwds)
n_repeats = 3
timed = timeit.timeit(wrapped, number=n_repeats)
samp_proc_est = timed / n_repeats
est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows
# if pandas apply takes too long, use dask
if est_apply_duration > self._dask_threshold:
return self._dask_apply(func, *args, **kwds)
else: # use pandas
if self._progress_bar:
tqdm.pandas(desc="Pandas Apply")
return self._obj_pd.progress_apply(func, *args, **kwds)
else:
return self._obj_pd.apply(func, *args, **kwds) | python | def apply(self, func, *args, **kwds):
"""
Apply the function to the transformed swifter object
"""
# estimate time to pandas apply
wrapped = self._wrapped_apply(func, *args, **kwds)
n_repeats = 3
timed = timeit.timeit(wrapped, number=n_repeats)
samp_proc_est = timed / n_repeats
est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows
# if pandas apply takes too long, use dask
if est_apply_duration > self._dask_threshold:
return self._dask_apply(func, *args, **kwds)
else: # use pandas
if self._progress_bar:
tqdm.pandas(desc="Pandas Apply")
return self._obj_pd.progress_apply(func, *args, **kwds)
else:
return self._obj_pd.apply(func, *args, **kwds) | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# estimate time to pandas apply",
"wrapped",
"=",
"self",
".",
"_wrapped_apply",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"n_repeats",
"=",
... | Apply the function to the transformed swifter object | [
"Apply",
"the",
"function",
"to",
"the",
"transformed",
"swifter",
"object"
] | ed5fc3235b43f981fa58ac9bc982c8209d4e3df3 | https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L338-L357 | train | 221,640 |
summernote/django-summernote | django_summernote/utils.py | using_config | def using_config(_func=None):
"""
This allows a function to use Summernote configuration
as a global variable, temporarily.
"""
def decorator(func):
@wraps(func)
def inner_dec(*args, **kwargs):
g = func.__globals__
var_name = 'config'
sentinel = object()
oldvalue = g.get(var_name, sentinel)
g[var_name] = apps.get_app_config('django_summernote').config
try:
res = func(*args, **kwargs)
finally:
if oldvalue is sentinel:
del g[var_name]
else:
g[var_name] = oldvalue
return res
return inner_dec
if _func is None:
return decorator
else:
return decorator(_func) | python | def using_config(_func=None):
"""
This allows a function to use Summernote configuration
as a global variable, temporarily.
"""
def decorator(func):
@wraps(func)
def inner_dec(*args, **kwargs):
g = func.__globals__
var_name = 'config'
sentinel = object()
oldvalue = g.get(var_name, sentinel)
g[var_name] = apps.get_app_config('django_summernote').config
try:
res = func(*args, **kwargs)
finally:
if oldvalue is sentinel:
del g[var_name]
else:
g[var_name] = oldvalue
return res
return inner_dec
if _func is None:
return decorator
else:
return decorator(_func) | [
"def",
"using_config",
"(",
"_func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner_dec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"g",
"=",
"func",
".",
"__globals__",
... | This allows a function to use Summernote configuration
as a global variable, temporarily. | [
"This",
"allows",
"a",
"function",
"to",
"use",
"Summernote",
"configuration",
"as",
"a",
"global",
"variable",
"temporarily",
"."
] | bc7fbbf065d88a909fe3e1533c84110e0dd132bc | https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L117-L146 | train | 221,641 |
summernote/django-summernote | django_summernote/utils.py | uploaded_filepath | def uploaded_filepath(instance, filename):
"""
Returns default filepath for uploaded files.
"""
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
today = datetime.now().strftime('%Y-%m-%d')
return os.path.join('django-summernote', today, filename) | python | def uploaded_filepath(instance, filename):
"""
Returns default filepath for uploaded files.
"""
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
today = datetime.now().strftime('%Y-%m-%d')
return os.path.join('django-summernote', today, filename) | [
"def",
"uploaded_filepath",
"(",
"instance",
",",
"filename",
")",
":",
"ext",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"filename",
"=",
"\"%s.%s\"",
"%",
"(",
"uuid",
".",
"uuid4",
"(",
")",
",",
"ext",
")",
"today",
"="... | Returns default filepath for uploaded files. | [
"Returns",
"default",
"filepath",
"for",
"uploaded",
"files",
"."
] | bc7fbbf065d88a909fe3e1533c84110e0dd132bc | https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L149-L156 | train | 221,642 |
summernote/django-summernote | django_summernote/utils.py | get_attachment_model | def get_attachment_model():
"""
Returns the Attachment model that is active in this project.
"""
try:
from .models import AbstractAttachment
klass = apps.get_model(config["attachment_model"])
if not issubclass(klass, AbstractAttachment):
raise ImproperlyConfigured(
"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that is not "
"inherited from 'django_summernote.models.AbstractAttachment'" % config["attachment_model"]
)
return klass
except ValueError:
raise ImproperlyConfigured("SUMMERNOTE_CONFIG['attachment_model'] must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that has not been installed" % config["attachment_model"]
) | python | def get_attachment_model():
"""
Returns the Attachment model that is active in this project.
"""
try:
from .models import AbstractAttachment
klass = apps.get_model(config["attachment_model"])
if not issubclass(klass, AbstractAttachment):
raise ImproperlyConfigured(
"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that is not "
"inherited from 'django_summernote.models.AbstractAttachment'" % config["attachment_model"]
)
return klass
except ValueError:
raise ImproperlyConfigured("SUMMERNOTE_CONFIG['attachment_model'] must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that has not been installed" % config["attachment_model"]
) | [
"def",
"get_attachment_model",
"(",
")",
":",
"try",
":",
"from",
".",
"models",
"import",
"AbstractAttachment",
"klass",
"=",
"apps",
".",
"get_model",
"(",
"config",
"[",
"\"attachment_model\"",
"]",
")",
"if",
"not",
"issubclass",
"(",
"klass",
",",
"Abst... | Returns the Attachment model that is active in this project. | [
"Returns",
"the",
"Attachment",
"model",
"that",
"is",
"active",
"in",
"this",
"project",
"."
] | bc7fbbf065d88a909fe3e1533c84110e0dd132bc | https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L180-L199 | train | 221,643 |
PyMySQL/mysqlclient-python | MySQLdb/connections.py | numeric_part | def numeric_part(s):
"""Returns the leading numeric part of a string.
>>> numeric_part("20-alpha")
20
>>> numeric_part("foo")
>>> numeric_part("16b")
16
"""
m = re_numeric_part.match(s)
if m:
return int(m.group(1))
return None | python | def numeric_part(s):
"""Returns the leading numeric part of a string.
>>> numeric_part("20-alpha")
20
>>> numeric_part("foo")
>>> numeric_part("16b")
16
"""
m = re_numeric_part.match(s)
if m:
return int(m.group(1))
return None | [
"def",
"numeric_part",
"(",
"s",
")",
":",
"m",
"=",
"re_numeric_part",
".",
"match",
"(",
"s",
")",
"if",
"m",
":",
"return",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"return",
"None"
] | Returns the leading numeric part of a string.
>>> numeric_part("20-alpha")
20
>>> numeric_part("foo")
>>> numeric_part("16b")
16 | [
"Returns",
"the",
"leading",
"numeric",
"part",
"of",
"a",
"string",
"."
] | b66971ee36be96b772ae7fdec79ccc1611376f3c | https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L21-L34 | train | 221,644 |
PyMySQL/mysqlclient-python | MySQLdb/connections.py | Connection.literal | def literal(self, o):
"""If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
Non-standard. For internal use; do not use this in your
applications.
"""
if isinstance(o, unicode):
s = self.string_literal(o.encode(self.encoding))
elif isinstance(o, bytearray):
s = self._bytes_literal(o)
elif isinstance(o, bytes):
if PY2:
s = self.string_literal(o)
else:
s = self._bytes_literal(o)
elif isinstance(o, (tuple, list)):
s = self._tuple_literal(o)
else:
s = self.escape(o, self.encoders)
if isinstance(s, unicode):
s = s.encode(self.encoding)
assert isinstance(s, bytes)
return s | python | def literal(self, o):
"""If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
Non-standard. For internal use; do not use this in your
applications.
"""
if isinstance(o, unicode):
s = self.string_literal(o.encode(self.encoding))
elif isinstance(o, bytearray):
s = self._bytes_literal(o)
elif isinstance(o, bytes):
if PY2:
s = self.string_literal(o)
else:
s = self._bytes_literal(o)
elif isinstance(o, (tuple, list)):
s = self._tuple_literal(o)
else:
s = self.escape(o, self.encoders)
if isinstance(s, unicode):
s = s.encode(self.encoding)
assert isinstance(s, bytes)
return s | [
"def",
"literal",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"unicode",
")",
":",
"s",
"=",
"self",
".",
"string_literal",
"(",
"o",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
")",
"elif",
"isinstance",
"(",
"o",
"... | If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
Non-standard. For internal use; do not use this in your
applications. | [
"If",
"o",
"is",
"a",
"single",
"object",
"returns",
"an",
"SQL",
"literal",
"as",
"a",
"string",
".",
"If",
"o",
"is",
"a",
"non",
"-",
"string",
"sequence",
"the",
"items",
"of",
"the",
"sequence",
"are",
"converted",
"and",
"returned",
"as",
"a",
... | b66971ee36be96b772ae7fdec79ccc1611376f3c | https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L238-L262 | train | 221,645 |
PyMySQL/mysqlclient-python | MySQLdb/connections.py | Connection.set_character_set | def set_character_set(self, charset):
"""Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised."""
if charset in ("utf8mb4", "utf8mb3"):
py_charset = "utf8"
else:
py_charset = charset
if self.character_set_name() != charset:
try:
super(Connection, self).set_character_set(charset)
except AttributeError:
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set charset")
self.query('SET NAMES %s' % charset)
self.store_result()
self.encoding = py_charset | python | def set_character_set(self, charset):
"""Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised."""
if charset in ("utf8mb4", "utf8mb3"):
py_charset = "utf8"
else:
py_charset = charset
if self.character_set_name() != charset:
try:
super(Connection, self).set_character_set(charset)
except AttributeError:
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set charset")
self.query('SET NAMES %s' % charset)
self.store_result()
self.encoding = py_charset | [
"def",
"set_character_set",
"(",
"self",
",",
"charset",
")",
":",
"if",
"charset",
"in",
"(",
"\"utf8mb4\"",
",",
"\"utf8mb3\"",
")",
":",
"py_charset",
"=",
"\"utf8\"",
"else",
":",
"py_charset",
"=",
"charset",
"if",
"self",
".",
"character_set_name",
"("... | Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised. | [
"Set",
"the",
"connection",
"character",
"set",
"to",
"charset",
".",
"The",
"character",
"set",
"can",
"only",
"be",
"changed",
"in",
"MySQL",
"-",
"4",
".",
"1",
"and",
"newer",
".",
"If",
"you",
"try",
"to",
"change",
"the",
"character",
"set",
"fro... | b66971ee36be96b772ae7fdec79ccc1611376f3c | https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L282-L299 | train | 221,646 |
PyMySQL/mysqlclient-python | MySQLdb/connections.py | Connection.set_sql_mode | def set_sql_mode(self, sql_mode):
"""Set the connection sql_mode. See MySQL documentation for
legal values."""
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set sql_mode")
self.query("SET SESSION sql_mode='%s'" % sql_mode)
self.store_result() | python | def set_sql_mode(self, sql_mode):
"""Set the connection sql_mode. See MySQL documentation for
legal values."""
if self._server_version < (4, 1):
raise NotSupportedError("server is too old to set sql_mode")
self.query("SET SESSION sql_mode='%s'" % sql_mode)
self.store_result() | [
"def",
"set_sql_mode",
"(",
"self",
",",
"sql_mode",
")",
":",
"if",
"self",
".",
"_server_version",
"<",
"(",
"4",
",",
"1",
")",
":",
"raise",
"NotSupportedError",
"(",
"\"server is too old to set sql_mode\"",
")",
"self",
".",
"query",
"(",
"\"SET SESSION s... | Set the connection sql_mode. See MySQL documentation for
legal values. | [
"Set",
"the",
"connection",
"sql_mode",
".",
"See",
"MySQL",
"documentation",
"for",
"legal",
"values",
"."
] | b66971ee36be96b772ae7fdec79ccc1611376f3c | https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L301-L307 | train | 221,647 |
PyMySQL/mysqlclient-python | MySQLdb/cursors.py | BaseCursor.close | def close(self):
"""Close the cursor. No further queries will be possible."""
try:
if self.connection is None:
return
while self.nextset():
pass
finally:
self.connection = None
self._result = None | python | def close(self):
"""Close the cursor. No further queries will be possible."""
try:
if self.connection is None:
return
while self.nextset():
pass
finally:
self.connection = None
self._result = None | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"return",
"while",
"self",
".",
"nextset",
"(",
")",
":",
"pass",
"finally",
":",
"self",
".",
"connection",
"=",
"None",
"self",
".",
"_result",
... | Close the cursor. No further queries will be possible. | [
"Close",
"the",
"cursor",
".",
"No",
"further",
"queries",
"will",
"be",
"possible",
"."
] | b66971ee36be96b772ae7fdec79ccc1611376f3c | https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/cursors.py#L81-L90 | train | 221,648 |
MagicStack/asyncpg | asyncpg/cursor.py | Cursor.fetchrow | async def fetchrow(self, *, timeout=None):
r"""Return the next row.
:param float timeout: Optional timeout value in seconds.
:return: A :class:`Record` instance.
"""
self._check_ready()
if self._exhausted:
return None
recs = await self._exec(1, timeout)
if len(recs) < 1:
self._exhausted = True
return None
return recs[0] | python | async def fetchrow(self, *, timeout=None):
r"""Return the next row.
:param float timeout: Optional timeout value in seconds.
:return: A :class:`Record` instance.
"""
self._check_ready()
if self._exhausted:
return None
recs = await self._exec(1, timeout)
if len(recs) < 1:
self._exhausted = True
return None
return recs[0] | [
"async",
"def",
"fetchrow",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_check_ready",
"(",
")",
"if",
"self",
".",
"_exhausted",
":",
"return",
"None",
"recs",
"=",
"await",
"self",
".",
"_exec",
"(",
"1",
",",
"tim... | r"""Return the next row.
:param float timeout: Optional timeout value in seconds.
:return: A :class:`Record` instance. | [
"r",
"Return",
"the",
"next",
"row",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cursor.py#L224-L238 | train | 221,649 |
MagicStack/asyncpg | asyncpg/connresource.py | guarded | def guarded(meth):
"""A decorator to add a sanity check to ConnectionResource methods."""
@functools.wraps(meth)
def _check(self, *args, **kwargs):
self._check_conn_validity(meth.__name__)
return meth(self, *args, **kwargs)
return _check | python | def guarded(meth):
"""A decorator to add a sanity check to ConnectionResource methods."""
@functools.wraps(meth)
def _check(self, *args, **kwargs):
self._check_conn_validity(meth.__name__)
return meth(self, *args, **kwargs)
return _check | [
"def",
"guarded",
"(",
"meth",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"meth",
")",
"def",
"_check",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_conn_validity",
"(",
"meth",
".",
"__name__",
")",
"r... | A decorator to add a sanity check to ConnectionResource methods. | [
"A",
"decorator",
"to",
"add",
"a",
"sanity",
"check",
"to",
"ConnectionResource",
"methods",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connresource.py#L14-L22 | train | 221,650 |
MagicStack/asyncpg | asyncpg/cluster.py | Cluster.start | def start(self, wait=60, *, server_settings={}, **opts):
"""Start the cluster."""
status = self.get_status()
if status == 'running':
return
elif status == 'not-initialized':
raise ClusterError(
'cluster in {!r} has not been initialized'.format(
self._data_dir))
port = opts.pop('port', None)
if port == 'dynamic':
port = find_available_port()
extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()]
extra_args.append('--port={}'.format(port))
sockdir = server_settings.get('unix_socket_directories')
if sockdir is None:
sockdir = server_settings.get('unix_socket_directory')
if sockdir is None:
sockdir = '/tmp'
ssl_key = server_settings.get('ssl_key_file')
if ssl_key:
# Make sure server certificate key file has correct permissions.
keyfile = os.path.join(self._data_dir, 'srvkey.pem')
shutil.copy(ssl_key, keyfile)
os.chmod(keyfile, 0o600)
server_settings = server_settings.copy()
server_settings['ssl_key_file'] = keyfile
if self._pg_version < (9, 3):
sockdir_opt = 'unix_socket_directory'
else:
sockdir_opt = 'unix_socket_directories'
server_settings[sockdir_opt] = sockdir
for k, v in server_settings.items():
extra_args.extend(['-c', '{}={}'.format(k, v)])
if _system == 'Windows':
# On Windows we have to use pg_ctl as direct execution
# of postgres daemon under an Administrative account
# is not permitted and there is no easy way to drop
# privileges.
if os.getenv('ASYNCPG_DEBUG_SERVER'):
stdout = sys.stdout
else:
stdout = subprocess.DEVNULL
process = subprocess.run(
[self._pg_ctl, 'start', '-D', self._data_dir,
'-o', ' '.join(extra_args)],
stdout=stdout, stderr=subprocess.STDOUT)
if process.returncode != 0:
if process.stderr:
stderr = ':\n{}'.format(process.stderr.decode())
else:
stderr = ''
raise ClusterError(
'pg_ctl start exited with status {:d}{}'.format(
process.returncode, stderr))
else:
if os.getenv('ASYNCPG_DEBUG_SERVER'):
stdout = sys.stdout
else:
stdout = subprocess.DEVNULL
self._daemon_process = \
subprocess.Popen(
[self._postgres, '-D', self._data_dir, *extra_args],
stdout=stdout, stderr=subprocess.STDOUT)
self._daemon_pid = self._daemon_process.pid
self._test_connection(timeout=wait) | python | def start(self, wait=60, *, server_settings={}, **opts):
"""Start the cluster."""
status = self.get_status()
if status == 'running':
return
elif status == 'not-initialized':
raise ClusterError(
'cluster in {!r} has not been initialized'.format(
self._data_dir))
port = opts.pop('port', None)
if port == 'dynamic':
port = find_available_port()
extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()]
extra_args.append('--port={}'.format(port))
sockdir = server_settings.get('unix_socket_directories')
if sockdir is None:
sockdir = server_settings.get('unix_socket_directory')
if sockdir is None:
sockdir = '/tmp'
ssl_key = server_settings.get('ssl_key_file')
if ssl_key:
# Make sure server certificate key file has correct permissions.
keyfile = os.path.join(self._data_dir, 'srvkey.pem')
shutil.copy(ssl_key, keyfile)
os.chmod(keyfile, 0o600)
server_settings = server_settings.copy()
server_settings['ssl_key_file'] = keyfile
if self._pg_version < (9, 3):
sockdir_opt = 'unix_socket_directory'
else:
sockdir_opt = 'unix_socket_directories'
server_settings[sockdir_opt] = sockdir
for k, v in server_settings.items():
extra_args.extend(['-c', '{}={}'.format(k, v)])
if _system == 'Windows':
# On Windows we have to use pg_ctl as direct execution
# of postgres daemon under an Administrative account
# is not permitted and there is no easy way to drop
# privileges.
if os.getenv('ASYNCPG_DEBUG_SERVER'):
stdout = sys.stdout
else:
stdout = subprocess.DEVNULL
process = subprocess.run(
[self._pg_ctl, 'start', '-D', self._data_dir,
'-o', ' '.join(extra_args)],
stdout=stdout, stderr=subprocess.STDOUT)
if process.returncode != 0:
if process.stderr:
stderr = ':\n{}'.format(process.stderr.decode())
else:
stderr = ''
raise ClusterError(
'pg_ctl start exited with status {:d}{}'.format(
process.returncode, stderr))
else:
if os.getenv('ASYNCPG_DEBUG_SERVER'):
stdout = sys.stdout
else:
stdout = subprocess.DEVNULL
self._daemon_process = \
subprocess.Popen(
[self._postgres, '-D', self._data_dir, *extra_args],
stdout=stdout, stderr=subprocess.STDOUT)
self._daemon_pid = self._daemon_process.pid
self._test_connection(timeout=wait) | [
"def",
"start",
"(",
"self",
",",
"wait",
"=",
"60",
",",
"*",
",",
"server_settings",
"=",
"{",
"}",
",",
"*",
"*",
"opts",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"'running'",
":",
"return",
"elif",
"... | Start the cluster. | [
"Start",
"the",
"cluster",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L144-L222 | train | 221,651 |
MagicStack/asyncpg | asyncpg/cluster.py | Cluster.reload | def reload(self):
"""Reload server configuration."""
status = self.get_status()
if status != 'running':
raise ClusterError('cannot reload: cluster is not running')
process = subprocess.run(
[self._pg_ctl, 'reload', '-D', self._data_dir],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = process.stderr
if process.returncode != 0:
raise ClusterError(
'pg_ctl stop exited with status {:d}: {}'.format(
process.returncode, stderr.decode())) | python | def reload(self):
"""Reload server configuration."""
status = self.get_status()
if status != 'running':
raise ClusterError('cannot reload: cluster is not running')
process = subprocess.run(
[self._pg_ctl, 'reload', '-D', self._data_dir],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = process.stderr
if process.returncode != 0:
raise ClusterError(
'pg_ctl stop exited with status {:d}: {}'.format(
process.returncode, stderr.decode())) | [
"def",
"reload",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"!=",
"'running'",
":",
"raise",
"ClusterError",
"(",
"'cannot reload: cluster is not running'",
")",
"process",
"=",
"subprocess",
".",
"run",
"(",
"... | Reload server configuration. | [
"Reload",
"server",
"configuration",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L224-L239 | train | 221,652 |
MagicStack/asyncpg | asyncpg/cluster.py | Cluster.reset_hba | def reset_hba(self):
"""Remove all records from pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: cluster is not initialized')
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
try:
with open(pg_hba, 'w'):
pass
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e | python | def reset_hba(self):
"""Remove all records from pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: cluster is not initialized')
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
try:
with open(pg_hba, 'w'):
pass
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e | [
"def",
"reset_hba",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"'not-initialized'",
":",
"raise",
"ClusterError",
"(",
"'cannot modify HBA records: cluster is not initialized'",
")",
"pg_hba",
"=",
"os",
".",
... | Remove all records from pg_hba.conf. | [
"Remove",
"all",
"records",
"from",
"pg_hba",
".",
"conf",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L323-L337 | train | 221,653 |
MagicStack/asyncpg | asyncpg/cluster.py | Cluster.add_hba_entry | def add_hba_entry(self, *, type='host', database, user, address=None,
auth_method, auth_options=None):
"""Add a record to pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: cluster is not initialized')
if type not in {'local', 'host', 'hostssl', 'hostnossl'}:
raise ValueError('invalid HBA record type: {!r}'.format(type))
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
record = '{} {} {}'.format(type, database, user)
if type != 'local':
if address is None:
raise ValueError(
'{!r} entry requires a valid address'.format(type))
else:
record += ' {}'.format(address)
record += ' {}'.format(auth_method)
if auth_options is not None:
record += ' ' + ' '.join(
'{}={}'.format(k, v) for k, v in auth_options)
try:
with open(pg_hba, 'a') as f:
print(record, file=f)
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e | python | def add_hba_entry(self, *, type='host', database, user, address=None,
auth_method, auth_options=None):
"""Add a record to pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: cluster is not initialized')
if type not in {'local', 'host', 'hostssl', 'hostnossl'}:
raise ValueError('invalid HBA record type: {!r}'.format(type))
pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')
record = '{} {} {}'.format(type, database, user)
if type != 'local':
if address is None:
raise ValueError(
'{!r} entry requires a valid address'.format(type))
else:
record += ' {}'.format(address)
record += ' {}'.format(auth_method)
if auth_options is not None:
record += ' ' + ' '.join(
'{}={}'.format(k, v) for k, v in auth_options)
try:
with open(pg_hba, 'a') as f:
print(record, file=f)
except IOError as e:
raise ClusterError(
'cannot modify HBA records: {}'.format(e)) from e | [
"def",
"add_hba_entry",
"(",
"self",
",",
"*",
",",
"type",
"=",
"'host'",
",",
"database",
",",
"user",
",",
"address",
"=",
"None",
",",
"auth_method",
",",
"auth_options",
"=",
"None",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
... | Add a record to pg_hba.conf. | [
"Add",
"a",
"record",
"to",
"pg_hba",
".",
"conf",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L339-L372 | train | 221,654 |
MagicStack/asyncpg | asyncpg/connection.py | connect | async def connect(dsn=None, *,
host=None, port=None,
user=None, password=None, passfile=None,
database=None,
loop=None,
timeout=60,
statement_cache_size=100,
max_cached_statement_lifetime=300,
max_cacheable_statement_size=1024 * 15,
command_timeout=None,
ssl=None,
connection_class=Connection,
server_settings=None):
r"""A coroutine to establish a connection to a PostgreSQL server.
The connection parameters may be specified either as a connection
URI in *dsn*, or as specific keyword arguments, or both.
If both *dsn* and keyword arguments are specified, the latter
override the corresponding values parsed from the connection URI.
The default values for the majority of arguments can be specified
using `environment variables <postgres envvars>`_.
Returns a new :class:`~asyncpg.connection.Connection` object.
:param dsn:
Connection arguments specified using as a single string in the
`libpq connection URI format`_:
``postgres://user:password@host:port/database?option=value``.
The following options are recognized by asyncpg: host, port,
user, database (or dbname), password, passfile, sslmode.
Unlike libpq, asyncpg will treat unrecognized options
as `server settings`_ to be used for the connection.
:param host:
Database host address as one of the following:
- an IP address or a domain name;
- an absolute path to the directory containing the database
server Unix-domain socket (not supported on Windows);
- a sequence of any of the above, in which case the addresses
will be tried in order, and the first successful connection
will be returned.
If not specified, asyncpg will try the following, in order:
- host address(es) parsed from the *dsn* argument,
- the value of the ``PGHOST`` environment variable,
- on Unix, common directories used for PostgreSQL Unix-domain
sockets: ``"/run/postgresql"``, ``"/var/run/postgresl"``,
``"/var/pgsql_socket"``, ``"/private/tmp"``, and ``"/tmp"``,
- ``"localhost"``.
:param port:
Port number to connect to at the server host
(or Unix-domain socket file extension). If multiple host
addresses were specified, this parameter may specify a
sequence of port numbers of the same length as the host sequence,
or it may specify a single port number to be used for all host
addresses.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGPORT`` environment variable, or ``5432`` if
neither is specified.
:param user:
The name of the database role used for authentication.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGUSER`` environment variable, or the
operating system name of the user running the application.
:param database:
The name of the database to connect to.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGDATABASE`` environment variable, or the
operating system name of the user running the application.
:param password:
Password to be used for authentication, if the server requires
one. If not specified, the value parsed from the *dsn* argument
is used, or the value of the ``PGPASSWORD`` environment variable.
Note that the use of the environment variable is discouraged as
other users and applications may be able to read it without needing
specific privileges. It is recommended to use *passfile* instead.
:param passfile:
The name of the file used to store passwords
(defaults to ``~/.pgpass``, or ``%APPDATA%\postgresql\pgpass.conf``
on Windows).
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:param float timeout:
Connection timeout in seconds.
:param int statement_cache_size:
The size of prepared statement LRU cache. Pass ``0`` to
disable the cache.
:param int max_cached_statement_lifetime:
The maximum time in seconds a prepared statement will stay
in the cache. Pass ``0`` to allow statements be cached
indefinitely.
:param int max_cacheable_statement_size:
The maximum size of a statement that can be cached (15KiB by
default). Pass ``0`` to allow all statements to be cached
regardless of their size.
:param float command_timeout:
The default timeout for operations on this connection
(the default is ``None``: no timeout).
:param ssl:
Pass ``True`` or an `ssl.SSLContext <SSLContext_>`_ instance to
require an SSL connection. If ``True``, a default SSL context
returned by `ssl.create_default_context() <create_default_context_>`_
will be used.
:param dict server_settings:
An optional dict of server runtime parameters. Refer to
PostgreSQL documentation for
a `list of supported options <server settings>`_.
:param Connection connection_class:
Class of the returned connection object. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:return: A :class:`~asyncpg.connection.Connection` instance.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... types = await con.fetch('SELECT * FROM pg_type')
... print(types)
...
>>> asyncio.get_event_loop().run_until_complete(run())
[<Record typname='bool' typnamespace=11 ...
.. versionadded:: 0.10.0
Added ``max_cached_statement_use_count`` parameter.
.. versionchanged:: 0.11.0
Removed ability to pass arbitrary keyword arguments to set
server settings. Added a dedicated parameter ``server_settings``
for that.
.. versionadded:: 0.11.0
Added ``connection_class`` parameter.
.. versionadded:: 0.16.0
Added ``passfile`` parameter
(and support for password files in general).
.. versionadded:: 0.18.0
Added ability to specify multiple hosts in the *dsn*
and *host* arguments.
.. _SSLContext: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
.. _create_default_context:
https://docs.python.org/3/library/ssl.html#ssl.create_default_context
.. _server settings:
https://www.postgresql.org/docs/current/static/runtime-config.html
.. _postgres envvars:
https://www.postgresql.org/docs/current/static/libpq-envars.html
.. _libpq connection URI format:
https://www.postgresql.org/docs/current/static/\
libpq-connect.html#LIBPQ-CONNSTRING
"""
if not issubclass(connection_class, Connection):
raise TypeError(
'connection_class is expected to be a subclass of '
'asyncpg.Connection, got {!r}'.format(connection_class))
if loop is None:
loop = asyncio.get_event_loop()
return await connect_utils._connect(
loop=loop, timeout=timeout, connection_class=connection_class,
dsn=dsn, host=host, port=port, user=user,
password=password, passfile=passfile,
ssl=ssl, database=database,
server_settings=server_settings,
command_timeout=command_timeout,
statement_cache_size=statement_cache_size,
max_cached_statement_lifetime=max_cached_statement_lifetime,
max_cacheable_statement_size=max_cacheable_statement_size) | python | async def connect(dsn=None, *,
host=None, port=None,
user=None, password=None, passfile=None,
database=None,
loop=None,
timeout=60,
statement_cache_size=100,
max_cached_statement_lifetime=300,
max_cacheable_statement_size=1024 * 15,
command_timeout=None,
ssl=None,
connection_class=Connection,
server_settings=None):
r"""A coroutine to establish a connection to a PostgreSQL server.
The connection parameters may be specified either as a connection
URI in *dsn*, or as specific keyword arguments, or both.
If both *dsn* and keyword arguments are specified, the latter
override the corresponding values parsed from the connection URI.
The default values for the majority of arguments can be specified
using `environment variables <postgres envvars>`_.
Returns a new :class:`~asyncpg.connection.Connection` object.
:param dsn:
Connection arguments specified using as a single string in the
`libpq connection URI format`_:
``postgres://user:password@host:port/database?option=value``.
The following options are recognized by asyncpg: host, port,
user, database (or dbname), password, passfile, sslmode.
Unlike libpq, asyncpg will treat unrecognized options
as `server settings`_ to be used for the connection.
:param host:
Database host address as one of the following:
- an IP address or a domain name;
- an absolute path to the directory containing the database
server Unix-domain socket (not supported on Windows);
- a sequence of any of the above, in which case the addresses
will be tried in order, and the first successful connection
will be returned.
If not specified, asyncpg will try the following, in order:
- host address(es) parsed from the *dsn* argument,
- the value of the ``PGHOST`` environment variable,
- on Unix, common directories used for PostgreSQL Unix-domain
sockets: ``"/run/postgresql"``, ``"/var/run/postgresl"``,
``"/var/pgsql_socket"``, ``"/private/tmp"``, and ``"/tmp"``,
- ``"localhost"``.
:param port:
Port number to connect to at the server host
(or Unix-domain socket file extension). If multiple host
addresses were specified, this parameter may specify a
sequence of port numbers of the same length as the host sequence,
or it may specify a single port number to be used for all host
addresses.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGPORT`` environment variable, or ``5432`` if
neither is specified.
:param user:
The name of the database role used for authentication.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGUSER`` environment variable, or the
operating system name of the user running the application.
:param database:
The name of the database to connect to.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGDATABASE`` environment variable, or the
operating system name of the user running the application.
:param password:
Password to be used for authentication, if the server requires
one. If not specified, the value parsed from the *dsn* argument
is used, or the value of the ``PGPASSWORD`` environment variable.
Note that the use of the environment variable is discouraged as
other users and applications may be able to read it without needing
specific privileges. It is recommended to use *passfile* instead.
:param passfile:
The name of the file used to store passwords
(defaults to ``~/.pgpass``, or ``%APPDATA%\postgresql\pgpass.conf``
on Windows).
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:param float timeout:
Connection timeout in seconds.
:param int statement_cache_size:
The size of prepared statement LRU cache. Pass ``0`` to
disable the cache.
:param int max_cached_statement_lifetime:
The maximum time in seconds a prepared statement will stay
in the cache. Pass ``0`` to allow statements be cached
indefinitely.
:param int max_cacheable_statement_size:
The maximum size of a statement that can be cached (15KiB by
default). Pass ``0`` to allow all statements to be cached
regardless of their size.
:param float command_timeout:
The default timeout for operations on this connection
(the default is ``None``: no timeout).
:param ssl:
Pass ``True`` or an `ssl.SSLContext <SSLContext_>`_ instance to
require an SSL connection. If ``True``, a default SSL context
returned by `ssl.create_default_context() <create_default_context_>`_
will be used.
:param dict server_settings:
An optional dict of server runtime parameters. Refer to
PostgreSQL documentation for
a `list of supported options <server settings>`_.
:param Connection connection_class:
Class of the returned connection object. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:return: A :class:`~asyncpg.connection.Connection` instance.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... types = await con.fetch('SELECT * FROM pg_type')
... print(types)
...
>>> asyncio.get_event_loop().run_until_complete(run())
[<Record typname='bool' typnamespace=11 ...
.. versionadded:: 0.10.0
Added ``max_cached_statement_use_count`` parameter.
.. versionchanged:: 0.11.0
Removed ability to pass arbitrary keyword arguments to set
server settings. Added a dedicated parameter ``server_settings``
for that.
.. versionadded:: 0.11.0
Added ``connection_class`` parameter.
.. versionadded:: 0.16.0
Added ``passfile`` parameter
(and support for password files in general).
.. versionadded:: 0.18.0
Added ability to specify multiple hosts in the *dsn*
and *host* arguments.
.. _SSLContext: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
.. _create_default_context:
https://docs.python.org/3/library/ssl.html#ssl.create_default_context
.. _server settings:
https://www.postgresql.org/docs/current/static/runtime-config.html
.. _postgres envvars:
https://www.postgresql.org/docs/current/static/libpq-envars.html
.. _libpq connection URI format:
https://www.postgresql.org/docs/current/static/\
libpq-connect.html#LIBPQ-CONNSTRING
"""
if not issubclass(connection_class, Connection):
raise TypeError(
'connection_class is expected to be a subclass of '
'asyncpg.Connection, got {!r}'.format(connection_class))
if loop is None:
loop = asyncio.get_event_loop()
return await connect_utils._connect(
loop=loop, timeout=timeout, connection_class=connection_class,
dsn=dsn, host=host, port=port, user=user,
password=password, passfile=passfile,
ssl=ssl, database=database,
server_settings=server_settings,
command_timeout=command_timeout,
statement_cache_size=statement_cache_size,
max_cached_statement_lifetime=max_cached_statement_lifetime,
max_cacheable_statement_size=max_cacheable_statement_size) | [
"async",
"def",
"connect",
"(",
"dsn",
"=",
"None",
",",
"*",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"passfile",
"=",
"None",
",",
"database",
"=",
"None",
",",
"loop",
"="... | r"""A coroutine to establish a connection to a PostgreSQL server.
The connection parameters may be specified either as a connection
URI in *dsn*, or as specific keyword arguments, or both.
If both *dsn* and keyword arguments are specified, the latter
override the corresponding values parsed from the connection URI.
The default values for the majority of arguments can be specified
using `environment variables <postgres envvars>`_.
Returns a new :class:`~asyncpg.connection.Connection` object.
:param dsn:
Connection arguments specified using as a single string in the
`libpq connection URI format`_:
``postgres://user:password@host:port/database?option=value``.
The following options are recognized by asyncpg: host, port,
user, database (or dbname), password, passfile, sslmode.
Unlike libpq, asyncpg will treat unrecognized options
as `server settings`_ to be used for the connection.
:param host:
Database host address as one of the following:
- an IP address or a domain name;
- an absolute path to the directory containing the database
server Unix-domain socket (not supported on Windows);
- a sequence of any of the above, in which case the addresses
will be tried in order, and the first successful connection
will be returned.
If not specified, asyncpg will try the following, in order:
- host address(es) parsed from the *dsn* argument,
- the value of the ``PGHOST`` environment variable,
- on Unix, common directories used for PostgreSQL Unix-domain
sockets: ``"/run/postgresql"``, ``"/var/run/postgresl"``,
``"/var/pgsql_socket"``, ``"/private/tmp"``, and ``"/tmp"``,
- ``"localhost"``.
:param port:
Port number to connect to at the server host
(or Unix-domain socket file extension). If multiple host
addresses were specified, this parameter may specify a
sequence of port numbers of the same length as the host sequence,
or it may specify a single port number to be used for all host
addresses.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGPORT`` environment variable, or ``5432`` if
neither is specified.
:param user:
The name of the database role used for authentication.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGUSER`` environment variable, or the
operating system name of the user running the application.
:param database:
The name of the database to connect to.
If not specified, the value parsed from the *dsn* argument is used,
or the value of the ``PGDATABASE`` environment variable, or the
operating system name of the user running the application.
:param password:
Password to be used for authentication, if the server requires
one. If not specified, the value parsed from the *dsn* argument
is used, or the value of the ``PGPASSWORD`` environment variable.
Note that the use of the environment variable is discouraged as
other users and applications may be able to read it without needing
specific privileges. It is recommended to use *passfile* instead.
:param passfile:
The name of the file used to store passwords
(defaults to ``~/.pgpass``, or ``%APPDATA%\postgresql\pgpass.conf``
on Windows).
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:param float timeout:
Connection timeout in seconds.
:param int statement_cache_size:
The size of prepared statement LRU cache. Pass ``0`` to
disable the cache.
:param int max_cached_statement_lifetime:
The maximum time in seconds a prepared statement will stay
in the cache. Pass ``0`` to allow statements be cached
indefinitely.
:param int max_cacheable_statement_size:
The maximum size of a statement that can be cached (15KiB by
default). Pass ``0`` to allow all statements to be cached
regardless of their size.
:param float command_timeout:
The default timeout for operations on this connection
(the default is ``None``: no timeout).
:param ssl:
Pass ``True`` or an `ssl.SSLContext <SSLContext_>`_ instance to
require an SSL connection. If ``True``, a default SSL context
returned by `ssl.create_default_context() <create_default_context_>`_
will be used.
:param dict server_settings:
An optional dict of server runtime parameters. Refer to
PostgreSQL documentation for
a `list of supported options <server settings>`_.
:param Connection connection_class:
Class of the returned connection object. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:return: A :class:`~asyncpg.connection.Connection` instance.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... types = await con.fetch('SELECT * FROM pg_type')
... print(types)
...
>>> asyncio.get_event_loop().run_until_complete(run())
[<Record typname='bool' typnamespace=11 ...
.. versionadded:: 0.10.0
Added ``max_cached_statement_use_count`` parameter.
.. versionchanged:: 0.11.0
Removed ability to pass arbitrary keyword arguments to set
server settings. Added a dedicated parameter ``server_settings``
for that.
.. versionadded:: 0.11.0
Added ``connection_class`` parameter.
.. versionadded:: 0.16.0
Added ``passfile`` parameter
(and support for password files in general).
.. versionadded:: 0.18.0
Added ability to specify multiple hosts in the *dsn*
and *host* arguments.
.. _SSLContext: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
.. _create_default_context:
https://docs.python.org/3/library/ssl.html#ssl.create_default_context
.. _server settings:
https://www.postgresql.org/docs/current/static/runtime-config.html
.. _postgres envvars:
https://www.postgresql.org/docs/current/static/libpq-envars.html
.. _libpq connection URI format:
https://www.postgresql.org/docs/current/static/\
libpq-connect.html#LIBPQ-CONNSTRING | [
"r",
"A",
"coroutine",
"to",
"establish",
"a",
"connection",
"to",
"a",
"PostgreSQL",
"server",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L1494-L1688 | train | 221,655 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.add_listener | async def add_listener(self, channel, callback):
"""Add a listener for Postgres notifications.
:param str channel: Channel to listen on.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**pid**: PID of the Postgres server that sent the notification;
**channel**: name of the channel the notification was sent to;
**payload**: the payload.
"""
self._check_open()
if channel not in self._listeners:
await self.fetch('LISTEN {}'.format(utils._quote_ident(channel)))
self._listeners[channel] = set()
self._listeners[channel].add(callback) | python | async def add_listener(self, channel, callback):
"""Add a listener for Postgres notifications.
:param str channel: Channel to listen on.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**pid**: PID of the Postgres server that sent the notification;
**channel**: name of the channel the notification was sent to;
**payload**: the payload.
"""
self._check_open()
if channel not in self._listeners:
await self.fetch('LISTEN {}'.format(utils._quote_ident(channel)))
self._listeners[channel] = set()
self._listeners[channel].add(callback) | [
"async",
"def",
"add_listener",
"(",
"self",
",",
"channel",
",",
"callback",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"if",
"channel",
"not",
"in",
"self",
".",
"_listeners",
":",
"await",
"self",
".",
"fetch",
"(",
"'LISTEN {}'",
".",
"format",
... | Add a listener for Postgres notifications.
:param str channel: Channel to listen on.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**pid**: PID of the Postgres server that sent the notification;
**channel**: name of the channel the notification was sent to;
**payload**: the payload. | [
"Add",
"a",
"listener",
"for",
"Postgres",
"notifications",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L126-L142 | train | 221,656 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.remove_listener | async def remove_listener(self, channel, callback):
"""Remove a listening callback on the specified channel."""
if self.is_closed():
return
if channel not in self._listeners:
return
if callback not in self._listeners[channel]:
return
self._listeners[channel].remove(callback)
if not self._listeners[channel]:
del self._listeners[channel]
await self.fetch('UNLISTEN {}'.format(utils._quote_ident(channel))) | python | async def remove_listener(self, channel, callback):
"""Remove a listening callback on the specified channel."""
if self.is_closed():
return
if channel not in self._listeners:
return
if callback not in self._listeners[channel]:
return
self._listeners[channel].remove(callback)
if not self._listeners[channel]:
del self._listeners[channel]
await self.fetch('UNLISTEN {}'.format(utils._quote_ident(channel))) | [
"async",
"def",
"remove_listener",
"(",
"self",
",",
"channel",
",",
"callback",
")",
":",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"return",
"if",
"channel",
"not",
"in",
"self",
".",
"_listeners",
":",
"return",
"if",
"callback",
"not",
"in",
"... | Remove a listening callback on the specified channel. | [
"Remove",
"a",
"listening",
"callback",
"on",
"the",
"specified",
"channel",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L144-L155 | train | 221,657 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.add_log_listener | def add_log_listener(self, callback):
"""Add a listener for Postgres log messages.
It will be called when asyncronous NoticeResponse is received
from the connection. Possible message types are: WARNING, NOTICE,
DEBUG, INFO, or LOG.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**message**: the `exceptions.PostgresLogMessage` message.
.. versionadded:: 0.12.0
"""
if self.is_closed():
raise exceptions.InterfaceError('connection is closed')
self._log_listeners.add(callback) | python | def add_log_listener(self, callback):
"""Add a listener for Postgres log messages.
It will be called when asyncronous NoticeResponse is received
from the connection. Possible message types are: WARNING, NOTICE,
DEBUG, INFO, or LOG.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**message**: the `exceptions.PostgresLogMessage` message.
.. versionadded:: 0.12.0
"""
if self.is_closed():
raise exceptions.InterfaceError('connection is closed')
self._log_listeners.add(callback) | [
"def",
"add_log_listener",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"raise",
"exceptions",
".",
"InterfaceError",
"(",
"'connection is closed'",
")",
"self",
".",
"_log_listeners",
".",
"add",
"(",
"callback",
")... | Add a listener for Postgres log messages.
It will be called when asyncronous NoticeResponse is received
from the connection. Possible message types are: WARNING, NOTICE,
DEBUG, INFO, or LOG.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**message**: the `exceptions.PostgresLogMessage` message.
.. versionadded:: 0.12.0 | [
"Add",
"a",
"listener",
"for",
"Postgres",
"log",
"messages",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L157-L173 | train | 221,658 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.copy_from_table | async def copy_from_table(self, table_name, *, output,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, delimiter=None,
null=None, header=None, quote=None,
escape=None, force_quote=None, encoding=None):
"""Copy table contents to a file or file-like object.
:param str table_name:
The name of the table to copy data from.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_table(
... 'mytable', columns=('foo', 'bar'),
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 100'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
else:
cols = ''
opts = self._format_copy_opts(
format=format, oids=oids, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_quote=force_quote, encoding=encoding
)
copy_stmt = 'COPY {tab}{cols} TO STDOUT {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_out(copy_stmt, output, timeout) | python | async def copy_from_table(self, table_name, *, output,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, delimiter=None,
null=None, header=None, quote=None,
escape=None, force_quote=None, encoding=None):
"""Copy table contents to a file or file-like object.
:param str table_name:
The name of the table to copy data from.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_table(
... 'mytable', columns=('foo', 'bar'),
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 100'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
else:
cols = ''
opts = self._format_copy_opts(
format=format, oids=oids, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_quote=force_quote, encoding=encoding
)
copy_stmt = 'COPY {tab}{cols} TO STDOUT {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_out(copy_stmt, output, timeout) | [
"async",
"def",
"copy_from_table",
"(",
"self",
",",
"table_name",
",",
"*",
",",
"output",
",",
"columns",
"=",
"None",
",",
"schema_name",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"format",
"=",
"None",
",",
"oids",
"=",
"None",
",",
"delimiter... | Copy table contents to a file or file-like object.
:param str table_name:
The name of the table to copy data from.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_table(
... 'mytable', columns=('foo', 'bar'),
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 100'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0 | [
"Copy",
"table",
"contents",
"to",
"a",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L460-L530 | train | 221,659 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.copy_from_query | async def copy_from_query(self, query, *args, output,
timeout=None, format=None, oids=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
encoding=None):
"""Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_query(
... 'SELECT foo, bar FROM mytable WHERE foo > $1', 10,
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 10'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
opts = self._format_copy_opts(
format=format, oids=oids, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_quote=force_quote, encoding=encoding
)
if args:
query = await utils._mogrify(self, query, args)
copy_stmt = 'COPY ({query}) TO STDOUT {opts}'.format(
query=query, opts=opts)
return await self._copy_out(copy_stmt, output, timeout) | python | async def copy_from_query(self, query, *args, output,
timeout=None, format=None, oids=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
encoding=None):
"""Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_query(
... 'SELECT foo, bar FROM mytable WHERE foo > $1', 10,
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 10'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
opts = self._format_copy_opts(
format=format, oids=oids, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_quote=force_quote, encoding=encoding
)
if args:
query = await utils._mogrify(self, query, args)
copy_stmt = 'COPY ({query}) TO STDOUT {opts}'.format(
query=query, opts=opts)
return await self._copy_out(copy_stmt, output, timeout) | [
"async",
"def",
"copy_from_query",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"output",
",",
"timeout",
"=",
"None",
",",
"format",
"=",
"None",
",",
"oids",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"null",
"=",
"None",
",",
"header",
... | Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
a :term:`coroutine function <python:coroutine function>`
that takes a ``bytes`` instance as a sole argument.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_from_query(
... 'SELECT foo, bar FROM mytable WHERE foo > $1', 10,
... output='file.csv', format='csv')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 10'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0 | [
"Copy",
"the",
"results",
"of",
"a",
"query",
"to",
"a",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L532-L592 | train | 221,660 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.copy_to_table | async def copy_to_table(self, table_name, *, source,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, freeze=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
force_not_null=None, force_null=None,
encoding=None):
"""Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterable <python:asynchronous iterable>`
that returns ``bytes``, or an object supporting the
:ref:`buffer protocol <python:bufferobjects>`.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_to_table(
... 'mytable', source='datafile.tbl')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 140000'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
else:
cols = ''
opts = self._format_copy_opts(
format=format, oids=oids, freeze=freeze, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_not_null=force_not_null, force_null=force_null,
encoding=encoding
)
copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_in(copy_stmt, source, timeout) | python | async def copy_to_table(self, table_name, *, source,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, freeze=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
force_not_null=None, force_null=None,
encoding=None):
"""Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterable <python:asynchronous iterable>`
that returns ``bytes``, or an object supporting the
:ref:`buffer protocol <python:bufferobjects>`.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_to_table(
... 'mytable', source='datafile.tbl')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 140000'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
else:
cols = ''
opts = self._format_copy_opts(
format=format, oids=oids, freeze=freeze, delimiter=delimiter,
null=null, header=header, quote=quote, escape=escape,
force_not_null=force_not_null, force_null=force_null,
encoding=encoding
)
copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_in(copy_stmt, source, timeout) | [
"async",
"def",
"copy_to_table",
"(",
"self",
",",
"table_name",
",",
"*",
",",
"source",
",",
"columns",
"=",
"None",
",",
"schema_name",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"format",
"=",
"None",
",",
"oids",
"=",
"None",
",",
"freeze",
... | Copy data to the specified table.
:param str table_name:
The name of the table to copy data to.
:param source:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <python:file-like object>`, or
an :term:`asynchronous iterable <python:asynchronous iterable>`
that returns ``bytes``, or an object supporting the
:ref:`buffer protocol <python:bufferobjects>`.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
The remaining keyword arguments are ``COPY`` statement options,
see `COPY statement documentation`_ for details.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_to_table(
... 'mytable', source='datafile.tbl')
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 140000'
.. _`COPY statement documentation`:
https://www.postgresql.org/docs/current/static/sql-copy.html
.. versionadded:: 0.11.0 | [
"Copy",
"data",
"to",
"the",
"specified",
"table",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L594-L667 | train | 221,661 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.copy_records_to_table | async def copy_records_to_table(self, table_name, *, records,
columns=None, schema_name=None,
timeout=None):
"""Copy a list of records to the specified table using binary COPY.
:param str table_name:
The name of the table to copy data to.
:param records:
An iterable returning row tuples to copy into the table.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_records_to_table(
... 'mytable', records=[
... (1, 'foo', 'bar'),
... (2, 'ham', 'spam')])
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 2'
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
col_list = ', '.join(utils._quote_ident(c) for c in columns)
cols = '({})'.format(col_list)
else:
col_list = '*'
cols = ''
intro_query = 'SELECT {cols} FROM {tab} LIMIT 1'.format(
tab=tabname, cols=col_list)
intro_ps = await self._prepare(intro_query, use_cache=True)
opts = '(FORMAT binary)'
copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_in_records(
copy_stmt, records, intro_ps._state, timeout) | python | async def copy_records_to_table(self, table_name, *, records,
columns=None, schema_name=None,
timeout=None):
"""Copy a list of records to the specified table using binary COPY.
:param str table_name:
The name of the table to copy data to.
:param records:
An iterable returning row tuples to copy into the table.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_records_to_table(
... 'mytable', records=[
... (1, 'foo', 'bar'),
... (2, 'ham', 'spam')])
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 2'
.. versionadded:: 0.11.0
"""
tabname = utils._quote_ident(table_name)
if schema_name:
tabname = utils._quote_ident(schema_name) + '.' + tabname
if columns:
col_list = ', '.join(utils._quote_ident(c) for c in columns)
cols = '({})'.format(col_list)
else:
col_list = '*'
cols = ''
intro_query = 'SELECT {cols} FROM {tab} LIMIT 1'.format(
tab=tabname, cols=col_list)
intro_ps = await self._prepare(intro_query, use_cache=True)
opts = '(FORMAT binary)'
copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts}'.format(
tab=tabname, cols=cols, opts=opts)
return await self._copy_in_records(
copy_stmt, records, intro_ps._state, timeout) | [
"async",
"def",
"copy_records_to_table",
"(",
"self",
",",
"table_name",
",",
"*",
",",
"records",
",",
"columns",
"=",
"None",
",",
"schema_name",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"tabname",
"=",
"utils",
".",
"_quote_ident",
"(",
"ta... | Copy a list of records to the specified table using binary COPY.
:param str table_name:
The name of the table to copy data to.
:param records:
An iterable returning row tuples to copy into the table.
:param list columns:
An optional list of column names to copy.
:param str schema_name:
An optional schema name to qualify the table.
:param float timeout:
Optional timeout value in seconds.
:return: The status string of the COPY command.
Example:
.. code-block:: pycon
>>> import asyncpg
>>> import asyncio
>>> async def run():
... con = await asyncpg.connect(user='postgres')
... result = await con.copy_records_to_table(
... 'mytable', records=[
... (1, 'foo', 'bar'),
... (2, 'ham', 'spam')])
... print(result)
...
>>> asyncio.get_event_loop().run_until_complete(run())
'COPY 2'
.. versionadded:: 0.11.0 | [
"Copy",
"a",
"list",
"of",
"records",
"to",
"the",
"specified",
"table",
"using",
"binary",
"COPY",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L669-L732 | train | 221,662 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.set_builtin_type_codec | async def set_builtin_type_codec(self, typename, *,
schema='public', codec_name,
format=None):
"""Set a builtin codec for the specified scalar data type.
This method has two uses. The first is to register a builtin
codec for an extension type without a stable OID, such as 'hstore'.
The second use is to declare that an extension type or a
user-defined type is wire-compatible with a certain builtin
data type and should be exchanged as such.
:param typename:
Name of the data type the codec is for.
:param schema:
Schema name of the data type the codec is for
(defaults to ``'public'``).
:param codec_name:
The name of the builtin codec to use for the type.
This should be either the name of a known core type
(such as ``"int"``), or the name of a supported extension
type. Currently, the only supported extension type is
``"pg_contrib.hstore"``.
:param format:
If *format* is ``None`` (the default), all formats supported
by the target codec are declared to be supported for *typename*.
If *format* is ``'text'`` or ``'binary'``, then only the
specified format is declared to be supported for *typename*.
.. versionchanged:: 0.18.0
The *codec_name* argument can be the name of any known
core data type. Added the *format* keyword argument.
"""
self._check_open()
typeinfo = await self.fetchrow(
introspection.TYPE_BY_NAME, typename, schema)
if not typeinfo:
raise exceptions.InterfaceError(
'unknown type: {}.{}'.format(schema, typename))
if not introspection.is_scalar_type(typeinfo):
raise exceptions.InterfaceError(
'cannot alias non-scalar type {}.{}'.format(
schema, typename))
oid = typeinfo['oid']
self._protocol.get_settings().set_builtin_type_codec(
oid, typename, schema, 'scalar', codec_name, format)
# Statement cache is no longer valid due to codec changes.
self._drop_local_statement_cache() | python | async def set_builtin_type_codec(self, typename, *,
schema='public', codec_name,
format=None):
"""Set a builtin codec for the specified scalar data type.
This method has two uses. The first is to register a builtin
codec for an extension type without a stable OID, such as 'hstore'.
The second use is to declare that an extension type or a
user-defined type is wire-compatible with a certain builtin
data type and should be exchanged as such.
:param typename:
Name of the data type the codec is for.
:param schema:
Schema name of the data type the codec is for
(defaults to ``'public'``).
:param codec_name:
The name of the builtin codec to use for the type.
This should be either the name of a known core type
(such as ``"int"``), or the name of a supported extension
type. Currently, the only supported extension type is
``"pg_contrib.hstore"``.
:param format:
If *format* is ``None`` (the default), all formats supported
by the target codec are declared to be supported for *typename*.
If *format* is ``'text'`` or ``'binary'``, then only the
specified format is declared to be supported for *typename*.
.. versionchanged:: 0.18.0
The *codec_name* argument can be the name of any known
core data type. Added the *format* keyword argument.
"""
self._check_open()
typeinfo = await self.fetchrow(
introspection.TYPE_BY_NAME, typename, schema)
if not typeinfo:
raise exceptions.InterfaceError(
'unknown type: {}.{}'.format(schema, typename))
if not introspection.is_scalar_type(typeinfo):
raise exceptions.InterfaceError(
'cannot alias non-scalar type {}.{}'.format(
schema, typename))
oid = typeinfo['oid']
self._protocol.get_settings().set_builtin_type_codec(
oid, typename, schema, 'scalar', codec_name, format)
# Statement cache is no longer valid due to codec changes.
self._drop_local_statement_cache() | [
"async",
"def",
"set_builtin_type_codec",
"(",
"self",
",",
"typename",
",",
"*",
",",
"schema",
"=",
"'public'",
",",
"codec_name",
",",
"format",
"=",
"None",
")",
":",
"self",
".",
"_check_open",
"(",
")",
"typeinfo",
"=",
"await",
"self",
".",
"fetch... | Set a builtin codec for the specified scalar data type.
This method has two uses. The first is to register a builtin
codec for an extension type without a stable OID, such as 'hstore'.
The second use is to declare that an extension type or a
user-defined type is wire-compatible with a certain builtin
data type and should be exchanged as such.
:param typename:
Name of the data type the codec is for.
:param schema:
Schema name of the data type the codec is for
(defaults to ``'public'``).
:param codec_name:
The name of the builtin codec to use for the type.
This should be either the name of a known core type
(such as ``"int"``), or the name of a supported extension
type. Currently, the only supported extension type is
``"pg_contrib.hstore"``.
:param format:
If *format* is ``None`` (the default), all formats supported
by the target codec are declared to be supported for *typename*.
If *format* is ``'text'`` or ``'binary'``, then only the
specified format is declared to be supported for *typename*.
.. versionchanged:: 0.18.0
The *codec_name* argument can be the name of any known
core data type. Added the *format* keyword argument. | [
"Set",
"a",
"builtin",
"codec",
"for",
"the",
"specified",
"scalar",
"data",
"type",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L1007-L1061 | train | 221,663 |
MagicStack/asyncpg | asyncpg/connection.py | Connection.close | async def close(self, *, timeout=None):
"""Close the connection gracefully.
:param float timeout:
Optional timeout value in seconds.
.. versionchanged:: 0.14.0
Added the *timeout* parameter.
"""
try:
if not self.is_closed():
await self._protocol.close(timeout)
except Exception:
# If we fail to close gracefully, abort the connection.
self._abort()
raise
finally:
self._cleanup() | python | async def close(self, *, timeout=None):
"""Close the connection gracefully.
:param float timeout:
Optional timeout value in seconds.
.. versionchanged:: 0.14.0
Added the *timeout* parameter.
"""
try:
if not self.is_closed():
await self._protocol.close(timeout)
except Exception:
# If we fail to close gracefully, abort the connection.
self._abort()
raise
finally:
self._cleanup() | [
"async",
"def",
"close",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"await",
"self",
".",
"_protocol",
".",
"close",
"(",
"timeout",
")",
"except",
"Exception",
":... | Close the connection gracefully.
:param float timeout:
Optional timeout value in seconds.
.. versionchanged:: 0.14.0
Added the *timeout* parameter. | [
"Close",
"the",
"connection",
"gracefully",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connection.py#L1071-L1088 | train | 221,664 |
MagicStack/asyncpg | asyncpg/pool.py | create_pool | def create_pool(dsn=None, *,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
connection_class=connection.Connection,
**connect_kwargs):
r"""Create a connection pool.
Can be used either with an ``async with`` block:
.. code-block:: python
async with asyncpg.create_pool(user='postgres',
command_timeout=60) as pool:
async with pool.acquire() as con:
await con.fetch('SELECT 1')
Or directly with ``await``:
.. code-block:: python
pool = await asyncpg.create_pool(user='postgres', command_timeout=60)
con = await pool.acquire()
try:
await con.fetch('SELECT 1')
finally:
await pool.release(con)
.. warning::
Prepared statements and cursors returned by
:meth:`Connection.prepare() <connection.Connection.prepare>` and
:meth:`Connection.cursor() <connection.Connection.cursor>` become
invalid once the connection is released. Likewise, all notification
and log listeners are removed, and ``asyncpg`` will issue a warning
if there are any listener callbacks registered on a connection that
is being released to the pool.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
:param Connection connection_class:
The class to use for connections. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:param int min_size:
Number of connection the pool will be initialized with.
:param int max_size:
Max number of connections in the pool.
:param int max_queries:
Number of queries after a connection is closed and replaced
with a new connection.
:param float max_inactive_connection_lifetime:
Number of seconds after which inactive connections in the
pool will be closed. Pass ``0`` to disable this mechanism.
:param coroutine setup:
A coroutine to prepare a connection right before it is returned
from :meth:`Pool.acquire() <pool.Pool.acquire>`. An example use
case would be to automatically set up notifications listeners for
all connections of a pool.
:param coroutine init:
A coroutine to initialize a connection when it is created.
An example use case would be to setup type codecs with
:meth:`Connection.set_builtin_type_codec() <\
asyncpg.connection.Connection.set_builtin_type_codec>`
or :meth:`Connection.set_type_codec() <\
asyncpg.connection.Connection.set_type_codec>`.
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:return: An instance of :class:`~asyncpg.pool.Pool`.
.. versionchanged:: 0.10.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a released connection.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a prepared statement or a cursor created
on a connection that has been released to the pool.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceWarning` will be produced
if there are any active listeners (added via
:meth:`Connection.add_listener() <connection.Connection.add_listener>`
or :meth:`Connection.add_log_listener()
<connection.Connection.add_log_listener>`) present on the connection
at the moment of its release to the pool.
"""
return Pool(
dsn,
connection_class=connection_class,
min_size=min_size, max_size=max_size,
max_queries=max_queries, loop=loop, setup=setup, init=init,
max_inactive_connection_lifetime=max_inactive_connection_lifetime,
**connect_kwargs) | python | def create_pool(dsn=None, *,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
connection_class=connection.Connection,
**connect_kwargs):
r"""Create a connection pool.
Can be used either with an ``async with`` block:
.. code-block:: python
async with asyncpg.create_pool(user='postgres',
command_timeout=60) as pool:
async with pool.acquire() as con:
await con.fetch('SELECT 1')
Or directly with ``await``:
.. code-block:: python
pool = await asyncpg.create_pool(user='postgres', command_timeout=60)
con = await pool.acquire()
try:
await con.fetch('SELECT 1')
finally:
await pool.release(con)
.. warning::
Prepared statements and cursors returned by
:meth:`Connection.prepare() <connection.Connection.prepare>` and
:meth:`Connection.cursor() <connection.Connection.cursor>` become
invalid once the connection is released. Likewise, all notification
and log listeners are removed, and ``asyncpg`` will issue a warning
if there are any listener callbacks registered on a connection that
is being released to the pool.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
:param Connection connection_class:
The class to use for connections. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:param int min_size:
Number of connection the pool will be initialized with.
:param int max_size:
Max number of connections in the pool.
:param int max_queries:
Number of queries after a connection is closed and replaced
with a new connection.
:param float max_inactive_connection_lifetime:
Number of seconds after which inactive connections in the
pool will be closed. Pass ``0`` to disable this mechanism.
:param coroutine setup:
A coroutine to prepare a connection right before it is returned
from :meth:`Pool.acquire() <pool.Pool.acquire>`. An example use
case would be to automatically set up notifications listeners for
all connections of a pool.
:param coroutine init:
A coroutine to initialize a connection when it is created.
An example use case would be to setup type codecs with
:meth:`Connection.set_builtin_type_codec() <\
asyncpg.connection.Connection.set_builtin_type_codec>`
or :meth:`Connection.set_type_codec() <\
asyncpg.connection.Connection.set_type_codec>`.
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:return: An instance of :class:`~asyncpg.pool.Pool`.
.. versionchanged:: 0.10.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a released connection.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a prepared statement or a cursor created
on a connection that has been released to the pool.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceWarning` will be produced
if there are any active listeners (added via
:meth:`Connection.add_listener() <connection.Connection.add_listener>`
or :meth:`Connection.add_log_listener()
<connection.Connection.add_log_listener>`) present on the connection
at the moment of its release to the pool.
"""
return Pool(
dsn,
connection_class=connection_class,
min_size=min_size, max_size=max_size,
max_queries=max_queries, loop=loop, setup=setup, init=init,
max_inactive_connection_lifetime=max_inactive_connection_lifetime,
**connect_kwargs) | [
"def",
"create_pool",
"(",
"dsn",
"=",
"None",
",",
"*",
",",
"min_size",
"=",
"10",
",",
"max_size",
"=",
"10",
",",
"max_queries",
"=",
"50000",
",",
"max_inactive_connection_lifetime",
"=",
"300.0",
",",
"setup",
"=",
"None",
",",
"init",
"=",
"None",... | r"""Create a connection pool.
Can be used either with an ``async with`` block:
.. code-block:: python
async with asyncpg.create_pool(user='postgres',
command_timeout=60) as pool:
async with pool.acquire() as con:
await con.fetch('SELECT 1')
Or directly with ``await``:
.. code-block:: python
pool = await asyncpg.create_pool(user='postgres', command_timeout=60)
con = await pool.acquire()
try:
await con.fetch('SELECT 1')
finally:
await pool.release(con)
.. warning::
Prepared statements and cursors returned by
:meth:`Connection.prepare() <connection.Connection.prepare>` and
:meth:`Connection.cursor() <connection.Connection.cursor>` become
invalid once the connection is released. Likewise, all notification
and log listeners are removed, and ``asyncpg`` will issue a warning
if there are any listener callbacks registered on a connection that
is being released to the pool.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
:param Connection connection_class:
The class to use for connections. Must be a subclass of
:class:`~asyncpg.connection.Connection`.
:param int min_size:
Number of connection the pool will be initialized with.
:param int max_size:
Max number of connections in the pool.
:param int max_queries:
Number of queries after a connection is closed and replaced
with a new connection.
:param float max_inactive_connection_lifetime:
Number of seconds after which inactive connections in the
pool will be closed. Pass ``0`` to disable this mechanism.
:param coroutine setup:
A coroutine to prepare a connection right before it is returned
from :meth:`Pool.acquire() <pool.Pool.acquire>`. An example use
case would be to automatically set up notifications listeners for
all connections of a pool.
:param coroutine init:
A coroutine to initialize a connection when it is created.
An example use case would be to setup type codecs with
:meth:`Connection.set_builtin_type_codec() <\
asyncpg.connection.Connection.set_builtin_type_codec>`
or :meth:`Connection.set_type_codec() <\
asyncpg.connection.Connection.set_type_codec>`.
:param loop:
An asyncio event loop instance. If ``None``, the default
event loop will be used.
:return: An instance of :class:`~asyncpg.pool.Pool`.
.. versionchanged:: 0.10.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a released connection.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any
attempted operation on a prepared statement or a cursor created
on a connection that has been released to the pool.
.. versionchanged:: 0.13.0
An :exc:`~asyncpg.exceptions.InterfaceWarning` will be produced
if there are any active listeners (added via
:meth:`Connection.add_listener() <connection.Connection.add_listener>`
or :meth:`Connection.add_log_listener()
<connection.Connection.add_log_listener>`) present on the connection
at the moment of its release to the pool. | [
"r",
"Create",
"a",
"connection",
"pool",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L778-L889 | train | 221,665 |
MagicStack/asyncpg | asyncpg/pool.py | PoolConnectionHolder._release | def _release(self):
"""Release this connection holder."""
if self._in_use is None:
# The holder is not checked out.
return
if not self._in_use.done():
self._in_use.set_result(None)
self._in_use = None
# Deinitialize the connection proxy. All subsequent
# operations on it will fail.
if self._proxy is not None:
self._proxy._detach()
self._proxy = None
# Put ourselves back to the pool queue.
self._pool._queue.put_nowait(self) | python | def _release(self):
"""Release this connection holder."""
if self._in_use is None:
# The holder is not checked out.
return
if not self._in_use.done():
self._in_use.set_result(None)
self._in_use = None
# Deinitialize the connection proxy. All subsequent
# operations on it will fail.
if self._proxy is not None:
self._proxy._detach()
self._proxy = None
# Put ourselves back to the pool queue.
self._pool._queue.put_nowait(self) | [
"def",
"_release",
"(",
"self",
")",
":",
"if",
"self",
".",
"_in_use",
"is",
"None",
":",
"# The holder is not checked out.",
"return",
"if",
"not",
"self",
".",
"_in_use",
".",
"done",
"(",
")",
":",
"self",
".",
"_in_use",
".",
"set_result",
"(",
"Non... | Release this connection holder. | [
"Release",
"this",
"connection",
"holder",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L276-L293 | train | 221,666 |
MagicStack/asyncpg | asyncpg/pool.py | Pool.set_connect_args | def set_connect_args(self, dsn=None, **connect_kwargs):
r"""Set the new connection arguments for this pool.
The new connection arguments will be used for all subsequent
new connection attempts. Existing connections will remain until
they expire. Use :meth:`Pool.expire_connections()
<asyncpg.pool.Pool.expire_connections>` to expedite the connection
expiry.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
.. versionadded:: 0.16.0
"""
self._connect_args = [dsn]
self._connect_kwargs = connect_kwargs
self._working_addr = None
self._working_config = None
self._working_params = None | python | def set_connect_args(self, dsn=None, **connect_kwargs):
r"""Set the new connection arguments for this pool.
The new connection arguments will be used for all subsequent
new connection attempts. Existing connections will remain until
they expire. Use :meth:`Pool.expire_connections()
<asyncpg.pool.Pool.expire_connections>` to expedite the connection
expiry.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
.. versionadded:: 0.16.0
"""
self._connect_args = [dsn]
self._connect_kwargs = connect_kwargs
self._working_addr = None
self._working_config = None
self._working_params = None | [
"def",
"set_connect_args",
"(",
"self",
",",
"dsn",
"=",
"None",
",",
"*",
"*",
"connect_kwargs",
")",
":",
"self",
".",
"_connect_args",
"=",
"[",
"dsn",
"]",
"self",
".",
"_connect_kwargs",
"=",
"connect_kwargs",
"self",
".",
"_working_addr",
"=",
"None"... | r"""Set the new connection arguments for this pool.
The new connection arguments will be used for all subsequent
new connection attempts. Existing connections will remain until
they expire. Use :meth:`Pool.expire_connections()
<asyncpg.pool.Pool.expire_connections>` to expedite the connection
expiry.
:param str dsn:
Connection arguments specified using as a single string in
the following format:
``postgres://user:pass@host:port/database?option=value``.
:param \*\*connect_kwargs:
Keyword arguments for the :func:`~asyncpg.connection.connect`
function.
.. versionadded:: 0.16.0 | [
"r",
"Set",
"the",
"new",
"connection",
"arguments",
"for",
"this",
"pool",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L429-L454 | train | 221,667 |
MagicStack/asyncpg | asyncpg/pool.py | Pool.release | async def release(self, connection, *, timeout=None):
"""Release a database connection back to the pool.
:param Connection connection:
A :class:`~asyncpg.connection.Connection` object to release.
:param float timeout:
A timeout for releasing the connection. If not specified, defaults
to the timeout provided in the corresponding call to the
:meth:`Pool.acquire() <asyncpg.pool.Pool.acquire>` method.
.. versionchanged:: 0.14.0
Added the *timeout* parameter.
"""
if (type(connection) is not PoolConnectionProxy or
connection._holder._pool is not self):
raise exceptions.InterfaceError(
'Pool.release() received invalid connection: '
'{connection!r} is not a member of this pool'.format(
connection=connection))
if connection._con is None:
# Already released, do nothing.
return
self._check_init()
# Let the connection do its internal housekeeping when its released.
connection._con._on_release()
ch = connection._holder
if timeout is None:
timeout = ch._timeout
# Use asyncio.shield() to guarantee that task cancellation
# does not prevent the connection from being returned to the
# pool properly.
return await asyncio.shield(ch.release(timeout), loop=self._loop) | python | async def release(self, connection, *, timeout=None):
"""Release a database connection back to the pool.
:param Connection connection:
A :class:`~asyncpg.connection.Connection` object to release.
:param float timeout:
A timeout for releasing the connection. If not specified, defaults
to the timeout provided in the corresponding call to the
:meth:`Pool.acquire() <asyncpg.pool.Pool.acquire>` method.
.. versionchanged:: 0.14.0
Added the *timeout* parameter.
"""
if (type(connection) is not PoolConnectionProxy or
connection._holder._pool is not self):
raise exceptions.InterfaceError(
'Pool.release() received invalid connection: '
'{connection!r} is not a member of this pool'.format(
connection=connection))
if connection._con is None:
# Already released, do nothing.
return
self._check_init()
# Let the connection do its internal housekeeping when its released.
connection._con._on_release()
ch = connection._holder
if timeout is None:
timeout = ch._timeout
# Use asyncio.shield() to guarantee that task cancellation
# does not prevent the connection from being returned to the
# pool properly.
return await asyncio.shield(ch.release(timeout), loop=self._loop) | [
"async",
"def",
"release",
"(",
"self",
",",
"connection",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"(",
"type",
"(",
"connection",
")",
"is",
"not",
"PoolConnectionProxy",
"or",
"connection",
".",
"_holder",
".",
"_pool",
"is",
"not",
"s... | Release a database connection back to the pool.
:param Connection connection:
A :class:`~asyncpg.connection.Connection` object to release.
:param float timeout:
A timeout for releasing the connection. If not specified, defaults
to the timeout provided in the corresponding call to the
:meth:`Pool.acquire() <asyncpg.pool.Pool.acquire>` method.
.. versionchanged:: 0.14.0
Added the *timeout* parameter. | [
"Release",
"a",
"database",
"connection",
"back",
"to",
"the",
"pool",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L609-L645 | train | 221,668 |
MagicStack/asyncpg | asyncpg/pool.py | Pool.close | async def close(self):
"""Attempt to gracefully close all connections in the pool.
Wait until all pool connections are released, close them and
shut down the pool. If any error (including cancellation) occurs
in ``close()`` the pool will terminate by calling
:meth:`Pool.terminate() <pool.Pool.terminate>`.
It is advisable to use :func:`python:asyncio.wait_for` to set
a timeout.
.. versionchanged:: 0.16.0
``close()`` now waits until all pool connections are released
before closing them and the pool. Errors raised in ``close()``
will cause immediate pool termination.
"""
if self._closed:
return
self._check_init()
self._closing = True
warning_callback = None
try:
warning_callback = self._loop.call_later(
60, self._warn_on_long_close)
release_coros = [
ch.wait_until_released() for ch in self._holders]
await asyncio.gather(*release_coros, loop=self._loop)
close_coros = [
ch.close() for ch in self._holders]
await asyncio.gather(*close_coros, loop=self._loop)
except Exception:
self.terminate()
raise
finally:
if warning_callback is not None:
warning_callback.cancel()
self._closed = True
self._closing = False | python | async def close(self):
"""Attempt to gracefully close all connections in the pool.
Wait until all pool connections are released, close them and
shut down the pool. If any error (including cancellation) occurs
in ``close()`` the pool will terminate by calling
:meth:`Pool.terminate() <pool.Pool.terminate>`.
It is advisable to use :func:`python:asyncio.wait_for` to set
a timeout.
.. versionchanged:: 0.16.0
``close()`` now waits until all pool connections are released
before closing them and the pool. Errors raised in ``close()``
will cause immediate pool termination.
"""
if self._closed:
return
self._check_init()
self._closing = True
warning_callback = None
try:
warning_callback = self._loop.call_later(
60, self._warn_on_long_close)
release_coros = [
ch.wait_until_released() for ch in self._holders]
await asyncio.gather(*release_coros, loop=self._loop)
close_coros = [
ch.close() for ch in self._holders]
await asyncio.gather(*close_coros, loop=self._loop)
except Exception:
self.terminate()
raise
finally:
if warning_callback is not None:
warning_callback.cancel()
self._closed = True
self._closing = False | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"self",
".",
"_check_init",
"(",
")",
"self",
".",
"_closing",
"=",
"True",
"warning_callback",
"=",
"None",
"try",
":",
"warning_callback",
"=",
"self",
".",
... | Attempt to gracefully close all connections in the pool.
Wait until all pool connections are released, close them and
shut down the pool. If any error (including cancellation) occurs
in ``close()`` the pool will terminate by calling
:meth:`Pool.terminate() <pool.Pool.terminate>`.
It is advisable to use :func:`python:asyncio.wait_for` to set
a timeout.
.. versionchanged:: 0.16.0
``close()`` now waits until all pool connections are released
before closing them and the pool. Errors raised in ``close()``
will cause immediate pool termination. | [
"Attempt",
"to",
"gracefully",
"close",
"all",
"connections",
"in",
"the",
"pool",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L647-L690 | train | 221,669 |
MagicStack/asyncpg | asyncpg/pool.py | Pool.terminate | def terminate(self):
"""Terminate all connections in the pool."""
if self._closed:
return
self._check_init()
for ch in self._holders:
ch.terminate()
self._closed = True | python | def terminate(self):
"""Terminate all connections in the pool."""
if self._closed:
return
self._check_init()
for ch in self._holders:
ch.terminate()
self._closed = True | [
"def",
"terminate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"self",
".",
"_check_init",
"(",
")",
"for",
"ch",
"in",
"self",
".",
"_holders",
":",
"ch",
".",
"terminate",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | Terminate all connections in the pool. | [
"Terminate",
"all",
"connections",
"in",
"the",
"pool",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/pool.py#L698-L705 | train | 221,670 |
MagicStack/asyncpg | asyncpg/transaction.py | Transaction.start | async def start(self):
"""Enter the transaction or savepoint block."""
self.__check_state_base('start')
if self._state is TransactionState.STARTED:
raise apg_errors.InterfaceError(
'cannot start; the transaction is already started')
con = self._connection
if con._top_xact is None:
if con._protocol.is_in_transaction():
raise apg_errors.InterfaceError(
'cannot use Connection.transaction() in '
'a manually started transaction')
con._top_xact = self
else:
# Nested transaction block
top_xact = con._top_xact
if self._isolation != top_xact._isolation:
raise apg_errors.InterfaceError(
'nested transaction has a different isolation level: '
'current {!r} != outer {!r}'.format(
self._isolation, top_xact._isolation))
self._nested = True
if self._nested:
self._id = con._get_unique_id('savepoint')
query = 'SAVEPOINT {};'.format(self._id)
else:
if self._isolation == 'read_committed':
query = 'BEGIN;'
elif self._isolation == 'repeatable_read':
query = 'BEGIN ISOLATION LEVEL REPEATABLE READ;'
else:
query = 'BEGIN ISOLATION LEVEL SERIALIZABLE'
if self._readonly:
query += ' READ ONLY'
if self._deferrable:
query += ' DEFERRABLE'
query += ';'
try:
await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.STARTED | python | async def start(self):
"""Enter the transaction or savepoint block."""
self.__check_state_base('start')
if self._state is TransactionState.STARTED:
raise apg_errors.InterfaceError(
'cannot start; the transaction is already started')
con = self._connection
if con._top_xact is None:
if con._protocol.is_in_transaction():
raise apg_errors.InterfaceError(
'cannot use Connection.transaction() in '
'a manually started transaction')
con._top_xact = self
else:
# Nested transaction block
top_xact = con._top_xact
if self._isolation != top_xact._isolation:
raise apg_errors.InterfaceError(
'nested transaction has a different isolation level: '
'current {!r} != outer {!r}'.format(
self._isolation, top_xact._isolation))
self._nested = True
if self._nested:
self._id = con._get_unique_id('savepoint')
query = 'SAVEPOINT {};'.format(self._id)
else:
if self._isolation == 'read_committed':
query = 'BEGIN;'
elif self._isolation == 'repeatable_read':
query = 'BEGIN ISOLATION LEVEL REPEATABLE READ;'
else:
query = 'BEGIN ISOLATION LEVEL SERIALIZABLE'
if self._readonly:
query += ' READ ONLY'
if self._deferrable:
query += ' DEFERRABLE'
query += ';'
try:
await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.STARTED | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"__check_state_base",
"(",
"'start'",
")",
"if",
"self",
".",
"_state",
"is",
"TransactionState",
".",
"STARTED",
":",
"raise",
"apg_errors",
".",
"InterfaceError",
"(",
"'cannot start; the transaction... | Enter the transaction or savepoint block. | [
"Enter",
"the",
"transaction",
"or",
"savepoint",
"block",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/transaction.py#L96-L143 | train | 221,671 |
MagicStack/asyncpg | asyncpg/prepared_stmt.py | PreparedStatement.get_statusmsg | def get_statusmsg(self) -> str:
"""Return the status of the executed command.
Example::
stmt = await connection.prepare('CREATE TABLE mytab (a int)')
await stmt.fetch()
assert stmt.get_statusmsg() == "CREATE TABLE"
"""
if self._last_status is None:
return self._last_status
return self._last_status.decode() | python | def get_statusmsg(self) -> str:
"""Return the status of the executed command.
Example::
stmt = await connection.prepare('CREATE TABLE mytab (a int)')
await stmt.fetch()
assert stmt.get_statusmsg() == "CREATE TABLE"
"""
if self._last_status is None:
return self._last_status
return self._last_status.decode() | [
"def",
"get_statusmsg",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_last_status",
"is",
"None",
":",
"return",
"self",
".",
"_last_status",
"return",
"self",
".",
"_last_status",
".",
"decode",
"(",
")"
] | Return the status of the executed command.
Example::
stmt = await connection.prepare('CREATE TABLE mytab (a int)')
await stmt.fetch()
assert stmt.get_statusmsg() == "CREATE TABLE" | [
"Return",
"the",
"status",
"of",
"the",
"executed",
"command",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/prepared_stmt.py#L39-L50 | train | 221,672 |
MagicStack/asyncpg | asyncpg/prepared_stmt.py | PreparedStatement.explain | async def explain(self, *args, analyze=False):
"""Return the execution plan of the statement.
:param args: Query arguments.
:param analyze: If ``True``, the statement will be executed and
the run time statitics added to the return value.
:return: An object representing the execution plan. This value
is actually a deserialized JSON output of the SQL
``EXPLAIN`` command.
"""
query = 'EXPLAIN (FORMAT JSON, VERBOSE'
if analyze:
query += ', ANALYZE) '
else:
query += ') '
query += self._state.query
if analyze:
# From PostgreSQL docs:
# Important: Keep in mind that the statement is actually
# executed when the ANALYZE option is used. Although EXPLAIN
# will discard any output that a SELECT would return, other
# side effects of the statement will happen as usual. If you
# wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE,
# CREATE TABLE AS, or EXECUTE statement without letting the
# command affect your data, use this approach:
# BEGIN;
# EXPLAIN ANALYZE ...;
# ROLLBACK;
tr = self._connection.transaction()
await tr.start()
try:
data = await self._connection.fetchval(query, *args)
finally:
await tr.rollback()
else:
data = await self._connection.fetchval(query, *args)
return json.loads(data) | python | async def explain(self, *args, analyze=False):
"""Return the execution plan of the statement.
:param args: Query arguments.
:param analyze: If ``True``, the statement will be executed and
the run time statitics added to the return value.
:return: An object representing the execution plan. This value
is actually a deserialized JSON output of the SQL
``EXPLAIN`` command.
"""
query = 'EXPLAIN (FORMAT JSON, VERBOSE'
if analyze:
query += ', ANALYZE) '
else:
query += ') '
query += self._state.query
if analyze:
# From PostgreSQL docs:
# Important: Keep in mind that the statement is actually
# executed when the ANALYZE option is used. Although EXPLAIN
# will discard any output that a SELECT would return, other
# side effects of the statement will happen as usual. If you
# wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE,
# CREATE TABLE AS, or EXECUTE statement without letting the
# command affect your data, use this approach:
# BEGIN;
# EXPLAIN ANALYZE ...;
# ROLLBACK;
tr = self._connection.transaction()
await tr.start()
try:
data = await self._connection.fetchval(query, *args)
finally:
await tr.rollback()
else:
data = await self._connection.fetchval(query, *args)
return json.loads(data) | [
"async",
"def",
"explain",
"(",
"self",
",",
"*",
"args",
",",
"analyze",
"=",
"False",
")",
":",
"query",
"=",
"'EXPLAIN (FORMAT JSON, VERBOSE'",
"if",
"analyze",
":",
"query",
"+=",
"', ANALYZE) '",
"else",
":",
"query",
"+=",
"') '",
"query",
"+=",
"sel... | Return the execution plan of the statement.
:param args: Query arguments.
:param analyze: If ``True``, the statement will be executed and
the run time statitics added to the return value.
:return: An object representing the execution plan. This value
is actually a deserialized JSON output of the SQL
``EXPLAIN`` command. | [
"Return",
"the",
"execution",
"plan",
"of",
"the",
"statement",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/prepared_stmt.py#L111-L150 | train | 221,673 |
MagicStack/asyncpg | asyncpg/prepared_stmt.py | PreparedStatement.fetchval | async def fetchval(self, *args, column=0, timeout=None):
"""Execute the statement and return a value in the first row.
:param args: Query arguments.
:param int column: Numeric index within the record of the value to
return (defaults to 0).
:param float timeout: Optional timeout value in seconds.
If not specified, defaults to the value of
``command_timeout`` argument to the ``Connection``
instance constructor.
:return: The value of the specified column of the first record.
"""
data = await self.__bind_execute(args, 1, timeout)
if not data:
return None
return data[0][column] | python | async def fetchval(self, *args, column=0, timeout=None):
"""Execute the statement and return a value in the first row.
:param args: Query arguments.
:param int column: Numeric index within the record of the value to
return (defaults to 0).
:param float timeout: Optional timeout value in seconds.
If not specified, defaults to the value of
``command_timeout`` argument to the ``Connection``
instance constructor.
:return: The value of the specified column of the first record.
"""
data = await self.__bind_execute(args, 1, timeout)
if not data:
return None
return data[0][column] | [
"async",
"def",
"fetchval",
"(",
"self",
",",
"*",
"args",
",",
"column",
"=",
"0",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"await",
"self",
".",
"__bind_execute",
"(",
"args",
",",
"1",
",",
"timeout",
")",
"if",
"not",
"data",
":",
... | Execute the statement and return a value in the first row.
:param args: Query arguments.
:param int column: Numeric index within the record of the value to
return (defaults to 0).
:param float timeout: Optional timeout value in seconds.
If not specified, defaults to the value of
``command_timeout`` argument to the ``Connection``
instance constructor.
:return: The value of the specified column of the first record. | [
"Execute",
"the",
"statement",
"and",
"return",
"a",
"value",
"in",
"the",
"first",
"row",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/prepared_stmt.py#L166-L182 | train | 221,674 |
MagicStack/asyncpg | asyncpg/prepared_stmt.py | PreparedStatement.fetchrow | async def fetchrow(self, *args, timeout=None):
"""Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance.
"""
data = await self.__bind_execute(args, 1, timeout)
if not data:
return None
return data[0] | python | async def fetchrow(self, *args, timeout=None):
"""Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance.
"""
data = await self.__bind_execute(args, 1, timeout)
if not data:
return None
return data[0] | [
"async",
"def",
"fetchrow",
"(",
"self",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"await",
"self",
".",
"__bind_execute",
"(",
"args",
",",
"1",
",",
"timeout",
")",
"if",
"not",
"data",
":",
"return",
"None",
"return",
... | Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance. | [
"Execute",
"the",
"statement",
"and",
"return",
"the",
"first",
"row",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/prepared_stmt.py#L185-L197 | train | 221,675 |
MagicStack/asyncpg | asyncpg/connect_utils.py | _read_password_from_pgpass | def _read_password_from_pgpass(
*, passfile: typing.Optional[pathlib.Path],
hosts: typing.List[str],
ports: typing.List[int],
database: str,
user: str):
"""Parse the pgpass file and return the matching password.
:return:
Password string, if found, ``None`` otherwise.
"""
passtab = _read_password_file(passfile)
if not passtab:
return None
for host, port in zip(hosts, ports):
if host.startswith('/'):
# Unix sockets get normalized into 'localhost'
host = 'localhost'
for phost, pport, pdatabase, puser, ppassword in passtab:
if phost != '*' and phost != host:
continue
if pport != '*' and pport != str(port):
continue
if pdatabase != '*' and pdatabase != database:
continue
if puser != '*' and puser != user:
continue
# Found a match.
return ppassword
return None | python | def _read_password_from_pgpass(
*, passfile: typing.Optional[pathlib.Path],
hosts: typing.List[str],
ports: typing.List[int],
database: str,
user: str):
"""Parse the pgpass file and return the matching password.
:return:
Password string, if found, ``None`` otherwise.
"""
passtab = _read_password_file(passfile)
if not passtab:
return None
for host, port in zip(hosts, ports):
if host.startswith('/'):
# Unix sockets get normalized into 'localhost'
host = 'localhost'
for phost, pport, pdatabase, puser, ppassword in passtab:
if phost != '*' and phost != host:
continue
if pport != '*' and pport != str(port):
continue
if pdatabase != '*' and pdatabase != database:
continue
if puser != '*' and puser != user:
continue
# Found a match.
return ppassword
return None | [
"def",
"_read_password_from_pgpass",
"(",
"*",
",",
"passfile",
":",
"typing",
".",
"Optional",
"[",
"pathlib",
".",
"Path",
"]",
",",
"hosts",
":",
"typing",
".",
"List",
"[",
"str",
"]",
",",
"ports",
":",
"typing",
".",
"List",
"[",
"int",
"]",
",... | Parse the pgpass file and return the matching password.
:return:
Password string, if found, ``None`` otherwise. | [
"Parse",
"the",
"pgpass",
"file",
"and",
"return",
"the",
"matching",
"password",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connect_utils.py#L105-L139 | train | 221,676 |
MagicStack/asyncpg | asyncpg/utils.py | _mogrify | async def _mogrify(conn, query, args):
"""Safely inline arguments to query text."""
# Introspect the target query for argument types and
# build a list of safely-quoted fully-qualified type names.
ps = await conn.prepare(query)
paramtypes = []
for t in ps.get_parameters():
if t.name.endswith('[]'):
pname = '_' + t.name[:-2]
else:
pname = t.name
paramtypes.append('{}.{}'.format(
_quote_ident(t.schema), _quote_ident(pname)))
del ps
# Use Postgres to convert arguments to text representation
# by casting each value to text.
cols = ['quote_literal(${}::{}::text)'.format(i, t)
for i, t in enumerate(paramtypes, start=1)]
textified = await conn.fetchrow(
'SELECT {cols}'.format(cols=', '.join(cols)), *args)
# Finally, replace $n references with text values.
return re.sub(
r'\$(\d+)\b', lambda m: textified[int(m.group(1)) - 1], query) | python | async def _mogrify(conn, query, args):
"""Safely inline arguments to query text."""
# Introspect the target query for argument types and
# build a list of safely-quoted fully-qualified type names.
ps = await conn.prepare(query)
paramtypes = []
for t in ps.get_parameters():
if t.name.endswith('[]'):
pname = '_' + t.name[:-2]
else:
pname = t.name
paramtypes.append('{}.{}'.format(
_quote_ident(t.schema), _quote_ident(pname)))
del ps
# Use Postgres to convert arguments to text representation
# by casting each value to text.
cols = ['quote_literal(${}::{}::text)'.format(i, t)
for i, t in enumerate(paramtypes, start=1)]
textified = await conn.fetchrow(
'SELECT {cols}'.format(cols=', '.join(cols)), *args)
# Finally, replace $n references with text values.
return re.sub(
r'\$(\d+)\b', lambda m: textified[int(m.group(1)) - 1], query) | [
"async",
"def",
"_mogrify",
"(",
"conn",
",",
"query",
",",
"args",
")",
":",
"# Introspect the target query for argument types and",
"# build a list of safely-quoted fully-qualified type names.",
"ps",
"=",
"await",
"conn",
".",
"prepare",
"(",
"query",
")",
"paramtypes"... | Safely inline arguments to query text. | [
"Safely",
"inline",
"arguments",
"to",
"query",
"text",
"."
] | 92c2d81256a1efd8cab12c0118d74ccd1c18131b | https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/utils.py#L19-L45 | train | 221,677 |
jrfonseca/gprof2dot | gprof2dot.py | Event.aggregate | def aggregate(self, val1, val2):
"""Aggregate two event values."""
assert val1 is not None
assert val2 is not None
return self._aggregator(val1, val2) | python | def aggregate(self, val1, val2):
"""Aggregate two event values."""
assert val1 is not None
assert val2 is not None
return self._aggregator(val1, val2) | [
"def",
"aggregate",
"(",
"self",
",",
"val1",
",",
"val2",
")",
":",
"assert",
"val1",
"is",
"not",
"None",
"assert",
"val2",
"is",
"not",
"None",
"return",
"self",
".",
"_aggregator",
"(",
"val1",
",",
"val2",
")"
] | Aggregate two event values. | [
"Aggregate",
"two",
"event",
"values",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L121-L125 | train | 221,678 |
jrfonseca/gprof2dot | gprof2dot.py | Function.stripped_name | def stripped_name(self):
"""Remove extraneous information from C++ demangled function names."""
name = self.name
# Strip function parameters from name by recursively removing paired parenthesis
while True:
name, n = self._parenthesis_re.subn('', name)
if not n:
break
# Strip const qualifier
name = self._const_re.sub('', name)
# Strip template parameters from name by recursively removing paired angles
while True:
name, n = self._angles_re.subn('', name)
if not n:
break
return name | python | def stripped_name(self):
"""Remove extraneous information from C++ demangled function names."""
name = self.name
# Strip function parameters from name by recursively removing paired parenthesis
while True:
name, n = self._parenthesis_re.subn('', name)
if not n:
break
# Strip const qualifier
name = self._const_re.sub('', name)
# Strip template parameters from name by recursively removing paired angles
while True:
name, n = self._angles_re.subn('', name)
if not n:
break
return name | [
"def",
"stripped_name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"# Strip function parameters from name by recursively removing paired parenthesis",
"while",
"True",
":",
"name",
",",
"n",
"=",
"self",
".",
"_parenthesis_re",
".",
"subn",
"(",
"''",
... | Remove extraneous information from C++ demangled function names. | [
"Remove",
"extraneous",
"information",
"from",
"C",
"++",
"demangled",
"function",
"names",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L244-L264 | train | 221,679 |
jrfonseca/gprof2dot | gprof2dot.py | Profile.validate | def validate(self):
"""Validate the edges."""
for function in compat_itervalues(self.functions):
for callee_id in compat_keys(function.calls):
assert function.calls[callee_id].callee_id == callee_id
if callee_id not in self.functions:
sys.stderr.write('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name))
del function.calls[callee_id] | python | def validate(self):
"""Validate the edges."""
for function in compat_itervalues(self.functions):
for callee_id in compat_keys(function.calls):
assert function.calls[callee_id].callee_id == callee_id
if callee_id not in self.functions:
sys.stderr.write('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name))
del function.calls[callee_id] | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",
")",
":",
"for",
"callee_id",
"in",
"compat_keys",
"(",
"function",
".",
"calls",
")",
":",
"assert",
"function",
".",
"calls",
"[",
"c... | Validate the edges. | [
"Validate",
"the",
"edges",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L305-L313 | train | 221,680 |
jrfonseca/gprof2dot | gprof2dot.py | Profile.find_cycles | def find_cycles(self):
"""Find cycles using Tarjan's strongly connected components algorithm."""
# Apply the Tarjan's algorithm successively until all functions are visited
stack = []
data = {}
order = 0
for function in compat_itervalues(self.functions):
order = self._tarjan(function, order, stack, data)
cycles = []
for function in compat_itervalues(self.functions):
if function.cycle is not None and function.cycle not in cycles:
cycles.append(function.cycle)
self.cycles = cycles
if 0:
for cycle in cycles:
sys.stderr.write("Cycle:\n")
for member in cycle.functions:
sys.stderr.write("\tFunction %s\n" % member.name) | python | def find_cycles(self):
"""Find cycles using Tarjan's strongly connected components algorithm."""
# Apply the Tarjan's algorithm successively until all functions are visited
stack = []
data = {}
order = 0
for function in compat_itervalues(self.functions):
order = self._tarjan(function, order, stack, data)
cycles = []
for function in compat_itervalues(self.functions):
if function.cycle is not None and function.cycle not in cycles:
cycles.append(function.cycle)
self.cycles = cycles
if 0:
for cycle in cycles:
sys.stderr.write("Cycle:\n")
for member in cycle.functions:
sys.stderr.write("\tFunction %s\n" % member.name) | [
"def",
"find_cycles",
"(",
"self",
")",
":",
"# Apply the Tarjan's algorithm successively until all functions are visited",
"stack",
"=",
"[",
"]",
"data",
"=",
"{",
"}",
"order",
"=",
"0",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",... | Find cycles using Tarjan's strongly connected components algorithm. | [
"Find",
"cycles",
"using",
"Tarjan",
"s",
"strongly",
"connected",
"components",
"algorithm",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L315-L333 | train | 221,681 |
jrfonseca/gprof2dot | gprof2dot.py | Profile._tarjan | def _tarjan(self, function, order, stack, data):
"""Tarjan's strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
"""
try:
func_data = data[function.id]
return order
except KeyError:
func_data = self._TarjanData(order)
data[function.id] = func_data
order += 1
pos = len(stack)
stack.append(function)
func_data.onstack = True
for call in compat_itervalues(function.calls):
try:
callee_data = data[call.callee_id]
if callee_data.onstack:
func_data.lowlink = min(func_data.lowlink, callee_data.order)
except KeyError:
callee = self.functions[call.callee_id]
order = self._tarjan(callee, order, stack, data)
callee_data = data[call.callee_id]
func_data.lowlink = min(func_data.lowlink, callee_data.lowlink)
if func_data.lowlink == func_data.order:
# Strongly connected component found
members = stack[pos:]
del stack[pos:]
if len(members) > 1:
cycle = Cycle()
for member in members:
cycle.add_function(member)
data[member.id].onstack = False
else:
for member in members:
data[member.id].onstack = False
return order | python | def _tarjan(self, function, order, stack, data):
"""Tarjan's strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
"""
try:
func_data = data[function.id]
return order
except KeyError:
func_data = self._TarjanData(order)
data[function.id] = func_data
order += 1
pos = len(stack)
stack.append(function)
func_data.onstack = True
for call in compat_itervalues(function.calls):
try:
callee_data = data[call.callee_id]
if callee_data.onstack:
func_data.lowlink = min(func_data.lowlink, callee_data.order)
except KeyError:
callee = self.functions[call.callee_id]
order = self._tarjan(callee, order, stack, data)
callee_data = data[call.callee_id]
func_data.lowlink = min(func_data.lowlink, callee_data.lowlink)
if func_data.lowlink == func_data.order:
# Strongly connected component found
members = stack[pos:]
del stack[pos:]
if len(members) > 1:
cycle = Cycle()
for member in members:
cycle.add_function(member)
data[member.id].onstack = False
else:
for member in members:
data[member.id].onstack = False
return order | [
"def",
"_tarjan",
"(",
"self",
",",
"function",
",",
"order",
",",
"stack",
",",
"data",
")",
":",
"try",
":",
"func_data",
"=",
"data",
"[",
"function",
".",
"id",
"]",
"return",
"order",
"except",
"KeyError",
":",
"func_data",
"=",
"self",
".",
"_T... | Tarjan's strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm | [
"Tarjan",
"s",
"strongly",
"connected",
"components",
"algorithm",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L402-L441 | train | 221,682 |
jrfonseca/gprof2dot | gprof2dot.py | Profile.integrate | def integrate(self, outevent, inevent):
"""Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html
"""
# Sanity checking
assert outevent not in self
for function in compat_itervalues(self.functions):
assert outevent not in function
assert inevent in function
for call in compat_itervalues(function.calls):
assert outevent not in call
if call.callee_id != function.id:
assert call.ratio is not None
# Aggregate the input for each cycle
for cycle in self.cycles:
total = inevent.null()
for function in compat_itervalues(self.functions):
total = inevent.aggregate(total, function[inevent])
self[inevent] = total
# Integrate along the edges
total = inevent.null()
for function in compat_itervalues(self.functions):
total = inevent.aggregate(total, function[inevent])
self._integrate_function(function, outevent, inevent)
self[outevent] = total | python | def integrate(self, outevent, inevent):
"""Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html
"""
# Sanity checking
assert outevent not in self
for function in compat_itervalues(self.functions):
assert outevent not in function
assert inevent in function
for call in compat_itervalues(function.calls):
assert outevent not in call
if call.callee_id != function.id:
assert call.ratio is not None
# Aggregate the input for each cycle
for cycle in self.cycles:
total = inevent.null()
for function in compat_itervalues(self.functions):
total = inevent.aggregate(total, function[inevent])
self[inevent] = total
# Integrate along the edges
total = inevent.null()
for function in compat_itervalues(self.functions):
total = inevent.aggregate(total, function[inevent])
self._integrate_function(function, outevent, inevent)
self[outevent] = total | [
"def",
"integrate",
"(",
"self",
",",
"outevent",
",",
"inevent",
")",
":",
"# Sanity checking",
"assert",
"outevent",
"not",
"in",
"self",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",
")",
":",
"assert",
"outevent",
"not",
"i... | Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html | [
"Propagate",
"function",
"time",
"ratio",
"along",
"the",
"function",
"calls",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L484-L515 | train | 221,683 |
jrfonseca/gprof2dot | gprof2dot.py | Profile._rank_cycle_function | def _rank_cycle_function(self, cycle, function, ranks):
"""Dijkstra's shortest paths algorithm.
See also:
- http://en.wikipedia.org/wiki/Dijkstra's_algorithm
"""
import heapq
Q = []
Qd = {}
p = {}
visited = set([function])
ranks[function] = 0
for call in compat_itervalues(function.calls):
if call.callee_id != function.id:
callee = self.functions[call.callee_id]
if callee.cycle is cycle:
ranks[callee] = 1
item = [ranks[callee], function, callee]
heapq.heappush(Q, item)
Qd[callee] = item
while Q:
cost, parent, member = heapq.heappop(Q)
if member not in visited:
p[member]= parent
visited.add(member)
for call in compat_itervalues(member.calls):
if call.callee_id != member.id:
callee = self.functions[call.callee_id]
if callee.cycle is cycle:
member_rank = ranks[member]
rank = ranks.get(callee)
if rank is not None:
if rank > 1 + member_rank:
rank = 1 + member_rank
ranks[callee] = rank
Qd_callee = Qd[callee]
Qd_callee[0] = rank
Qd_callee[1] = member
heapq._siftdown(Q, 0, Q.index(Qd_callee))
else:
rank = 1 + member_rank
ranks[callee] = rank
item = [rank, member, callee]
heapq.heappush(Q, item)
Qd[callee] = item | python | def _rank_cycle_function(self, cycle, function, ranks):
"""Dijkstra's shortest paths algorithm.
See also:
- http://en.wikipedia.org/wiki/Dijkstra's_algorithm
"""
import heapq
Q = []
Qd = {}
p = {}
visited = set([function])
ranks[function] = 0
for call in compat_itervalues(function.calls):
if call.callee_id != function.id:
callee = self.functions[call.callee_id]
if callee.cycle is cycle:
ranks[callee] = 1
item = [ranks[callee], function, callee]
heapq.heappush(Q, item)
Qd[callee] = item
while Q:
cost, parent, member = heapq.heappop(Q)
if member not in visited:
p[member]= parent
visited.add(member)
for call in compat_itervalues(member.calls):
if call.callee_id != member.id:
callee = self.functions[call.callee_id]
if callee.cycle is cycle:
member_rank = ranks[member]
rank = ranks.get(callee)
if rank is not None:
if rank > 1 + member_rank:
rank = 1 + member_rank
ranks[callee] = rank
Qd_callee = Qd[callee]
Qd_callee[0] = rank
Qd_callee[1] = member
heapq._siftdown(Q, 0, Q.index(Qd_callee))
else:
rank = 1 + member_rank
ranks[callee] = rank
item = [rank, member, callee]
heapq.heappush(Q, item)
Qd[callee] = item | [
"def",
"_rank_cycle_function",
"(",
"self",
",",
"cycle",
",",
"function",
",",
"ranks",
")",
":",
"import",
"heapq",
"Q",
"=",
"[",
"]",
"Qd",
"=",
"{",
"}",
"p",
"=",
"{",
"}",
"visited",
"=",
"set",
"(",
"[",
"function",
"]",
")",
"ranks",
"["... | Dijkstra's shortest paths algorithm.
See also:
- http://en.wikipedia.org/wiki/Dijkstra's_algorithm | [
"Dijkstra",
"s",
"shortest",
"paths",
"algorithm",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L582-L629 | train | 221,684 |
jrfonseca/gprof2dot | gprof2dot.py | Profile.aggregate | def aggregate(self, event):
"""Aggregate an event for the whole profile."""
total = event.null()
for function in compat_itervalues(self.functions):
try:
total = event.aggregate(total, function[event])
except UndefinedEvent:
return
self[event] = total | python | def aggregate(self, event):
"""Aggregate an event for the whole profile."""
total = event.null()
for function in compat_itervalues(self.functions):
try:
total = event.aggregate(total, function[event])
except UndefinedEvent:
return
self[event] = total | [
"def",
"aggregate",
"(",
"self",
",",
"event",
")",
":",
"total",
"=",
"event",
".",
"null",
"(",
")",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",
")",
":",
"try",
":",
"total",
"=",
"event",
".",
"aggregate",
"(",
"t... | Aggregate an event for the whole profile. | [
"Aggregate",
"an",
"event",
"for",
"the",
"whole",
"profile",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L668-L677 | train | 221,685 |
jrfonseca/gprof2dot | gprof2dot.py | Profile.prune | def prune(self, node_thres, edge_thres, paths, color_nodes_by_selftime):
"""Prune the profile"""
# compute the prune ratios
for function in compat_itervalues(self.functions):
try:
function.weight = function[TOTAL_TIME_RATIO]
except UndefinedEvent:
pass
for call in compat_itervalues(function.calls):
callee = self.functions[call.callee_id]
if TOTAL_TIME_RATIO in call:
# handle exact cases first
call.weight = call[TOTAL_TIME_RATIO]
else:
try:
# make a safe estimate
call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO])
except UndefinedEvent:
pass
# prune the nodes
for function_id in compat_keys(self.functions):
function = self.functions[function_id]
if function.weight is not None:
if function.weight < node_thres:
del self.functions[function_id]
# prune file paths
for function_id in compat_keys(self.functions):
function = self.functions[function_id]
if paths and function.filename and not any(function.filename.startswith(path) for path in paths):
del self.functions[function_id]
elif paths and function.module and not any((function.module.find(path)>-1) for path in paths):
del self.functions[function_id]
# prune the edges
for function in compat_itervalues(self.functions):
for callee_id in compat_keys(function.calls):
call = function.calls[callee_id]
if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres:
del function.calls[callee_id]
if color_nodes_by_selftime:
weights = []
for function in compat_itervalues(self.functions):
try:
weights.append(function[TIME_RATIO])
except UndefinedEvent:
pass
max_ratio = max(weights or [1])
# apply rescaled weights for coloriung
for function in compat_itervalues(self.functions):
try:
function.weight = function[TIME_RATIO] / max_ratio
except (ZeroDivisionError, UndefinedEvent):
pass | python | def prune(self, node_thres, edge_thres, paths, color_nodes_by_selftime):
"""Prune the profile"""
# compute the prune ratios
for function in compat_itervalues(self.functions):
try:
function.weight = function[TOTAL_TIME_RATIO]
except UndefinedEvent:
pass
for call in compat_itervalues(function.calls):
callee = self.functions[call.callee_id]
if TOTAL_TIME_RATIO in call:
# handle exact cases first
call.weight = call[TOTAL_TIME_RATIO]
else:
try:
# make a safe estimate
call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO])
except UndefinedEvent:
pass
# prune the nodes
for function_id in compat_keys(self.functions):
function = self.functions[function_id]
if function.weight is not None:
if function.weight < node_thres:
del self.functions[function_id]
# prune file paths
for function_id in compat_keys(self.functions):
function = self.functions[function_id]
if paths and function.filename and not any(function.filename.startswith(path) for path in paths):
del self.functions[function_id]
elif paths and function.module and not any((function.module.find(path)>-1) for path in paths):
del self.functions[function_id]
# prune the edges
for function in compat_itervalues(self.functions):
for callee_id in compat_keys(function.calls):
call = function.calls[callee_id]
if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres:
del function.calls[callee_id]
if color_nodes_by_selftime:
weights = []
for function in compat_itervalues(self.functions):
try:
weights.append(function[TIME_RATIO])
except UndefinedEvent:
pass
max_ratio = max(weights or [1])
# apply rescaled weights for coloriung
for function in compat_itervalues(self.functions):
try:
function.weight = function[TIME_RATIO] / max_ratio
except (ZeroDivisionError, UndefinedEvent):
pass | [
"def",
"prune",
"(",
"self",
",",
"node_thres",
",",
"edge_thres",
",",
"paths",
",",
"color_nodes_by_selftime",
")",
":",
"# compute the prune ratios",
"for",
"function",
"in",
"compat_itervalues",
"(",
"self",
".",
"functions",
")",
":",
"try",
":",
"function"... | Prune the profile | [
"Prune",
"the",
"profile"
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L692-L751 | train | 221,686 |
jrfonseca/gprof2dot | gprof2dot.py | GprofParser.translate | def translate(self, mo):
"""Extract a structure from a match object, while translating the types in the process."""
attrs = {}
groupdict = mo.groupdict()
for name, value in compat_iteritems(groupdict):
if value is None:
value = None
elif self._int_re.match(value):
value = int(value)
elif self._float_re.match(value):
value = float(value)
attrs[name] = (value)
return Struct(attrs) | python | def translate(self, mo):
"""Extract a structure from a match object, while translating the types in the process."""
attrs = {}
groupdict = mo.groupdict()
for name, value in compat_iteritems(groupdict):
if value is None:
value = None
elif self._int_re.match(value):
value = int(value)
elif self._float_re.match(value):
value = float(value)
attrs[name] = (value)
return Struct(attrs) | [
"def",
"translate",
"(",
"self",
",",
"mo",
")",
":",
"attrs",
"=",
"{",
"}",
"groupdict",
"=",
"mo",
".",
"groupdict",
"(",
")",
"for",
"name",
",",
"value",
"in",
"compat_iteritems",
"(",
"groupdict",
")",
":",
"if",
"value",
"is",
"None",
":",
"... | Extract a structure from a match object, while translating the types in the process. | [
"Extract",
"a",
"structure",
"from",
"a",
"match",
"object",
"while",
"translating",
"the",
"types",
"in",
"the",
"process",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L1114-L1126 | train | 221,687 |
jrfonseca/gprof2dot | gprof2dot.py | AXEParser.parse_cg | def parse_cg(self):
"""Parse the call graph."""
# skip call graph header
line = self.readline()
while self._cg_header_re.match(line):
line = self.readline()
# process call graph entries
entry_lines = []
# An EOF in readline terminates the program without returning.
while not self._cg_footer_re.match(line):
if line.isspace():
self.parse_cg_entry(entry_lines)
entry_lines = []
else:
entry_lines.append(line)
line = self.readline() | python | def parse_cg(self):
"""Parse the call graph."""
# skip call graph header
line = self.readline()
while self._cg_header_re.match(line):
line = self.readline()
# process call graph entries
entry_lines = []
# An EOF in readline terminates the program without returning.
while not self._cg_footer_re.match(line):
if line.isspace():
self.parse_cg_entry(entry_lines)
entry_lines = []
else:
entry_lines.append(line)
line = self.readline() | [
"def",
"parse_cg",
"(",
"self",
")",
":",
"# skip call graph header",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"while",
"self",
".",
"_cg_header_re",
".",
"match",
"(",
"line",
")",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"# process c... | Parse the call graph. | [
"Parse",
"the",
"call",
"graph",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L1541-L1558 | train | 221,688 |
jrfonseca/gprof2dot | gprof2dot.py | Theme.hsl_to_rgb | def hsl_to_rgb(self, h, s, l):
"""Convert a color from HSL color-model to RGB.
See also:
- http://www.w3.org/TR/css3-color/#hsl-color
"""
h = h % 1.0
s = min(max(s, 0.0), 1.0)
l = min(max(l, 0.0), 1.0)
if l <= 0.5:
m2 = l*(s + 1.0)
else:
m2 = l + s - l*s
m1 = l*2.0 - m2
r = self._hue_to_rgb(m1, m2, h + 1.0/3.0)
g = self._hue_to_rgb(m1, m2, h)
b = self._hue_to_rgb(m1, m2, h - 1.0/3.0)
# Apply gamma correction
r **= self.gamma
g **= self.gamma
b **= self.gamma
return (r, g, b) | python | def hsl_to_rgb(self, h, s, l):
"""Convert a color from HSL color-model to RGB.
See also:
- http://www.w3.org/TR/css3-color/#hsl-color
"""
h = h % 1.0
s = min(max(s, 0.0), 1.0)
l = min(max(l, 0.0), 1.0)
if l <= 0.5:
m2 = l*(s + 1.0)
else:
m2 = l + s - l*s
m1 = l*2.0 - m2
r = self._hue_to_rgb(m1, m2, h + 1.0/3.0)
g = self._hue_to_rgb(m1, m2, h)
b = self._hue_to_rgb(m1, m2, h - 1.0/3.0)
# Apply gamma correction
r **= self.gamma
g **= self.gamma
b **= self.gamma
return (r, g, b) | [
"def",
"hsl_to_rgb",
"(",
"self",
",",
"h",
",",
"s",
",",
"l",
")",
":",
"h",
"=",
"h",
"%",
"1.0",
"s",
"=",
"min",
"(",
"max",
"(",
"s",
",",
"0.0",
")",
",",
"1.0",
")",
"l",
"=",
"min",
"(",
"max",
"(",
"l",
",",
"0.0",
")",
",",
... | Convert a color from HSL color-model to RGB.
See also:
- http://www.w3.org/TR/css3-color/#hsl-color | [
"Convert",
"a",
"color",
"from",
"HSL",
"color",
"-",
"model",
"to",
"RGB",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L2863-L2888 | train | 221,689 |
jrfonseca/gprof2dot | gprof2dot.py | DotWriter.wrap_function_name | def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name | python | def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name | [
"def",
"wrap_function_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"32",
":",
"ratio",
"=",
"2.0",
"/",
"3.0",
"height",
"=",
"max",
"(",
"int",
"(",
"len",
"(",
"name",
")",
"/",
"(",
"1.0",
"-",
"ratio",
")",... | Split the function name on multiple lines. | [
"Split",
"the",
"function",
"name",
"on",
"multiple",
"lines",
"."
] | 0500e89f001e555f5eaa32e70793b4875f2f70db | https://github.com/jrfonseca/gprof2dot/blob/0500e89f001e555f5eaa32e70793b4875f2f70db/gprof2dot.py#L2974-L2989 | train | 221,690 |
danielhrisca/asammdf | asammdf/blocks/utils.py | matlab_compatible | def matlab_compatible(name):
""" make a channel name compatible with Matlab variable naming
Parameters
----------
name : str
channel name
Returns
-------
compatible_name : str
channel name compatible with Matlab
"""
compatible_name = [ch if ch in ALLOWED_MATLAB_CHARS else "_" for ch in name]
compatible_name = "".join(compatible_name)
if compatible_name[0] not in string.ascii_letters:
compatible_name = "M_" + compatible_name
# max variable name is 63 and 3 chars are reserved
# for get_unique_name in case of multiple channel name occurence
return compatible_name[:60] | python | def matlab_compatible(name):
""" make a channel name compatible with Matlab variable naming
Parameters
----------
name : str
channel name
Returns
-------
compatible_name : str
channel name compatible with Matlab
"""
compatible_name = [ch if ch in ALLOWED_MATLAB_CHARS else "_" for ch in name]
compatible_name = "".join(compatible_name)
if compatible_name[0] not in string.ascii_letters:
compatible_name = "M_" + compatible_name
# max variable name is 63 and 3 chars are reserved
# for get_unique_name in case of multiple channel name occurence
return compatible_name[:60] | [
"def",
"matlab_compatible",
"(",
"name",
")",
":",
"compatible_name",
"=",
"[",
"ch",
"if",
"ch",
"in",
"ALLOWED_MATLAB_CHARS",
"else",
"\"_\"",
"for",
"ch",
"in",
"name",
"]",
"compatible_name",
"=",
"\"\"",
".",
"join",
"(",
"compatible_name",
")",
"if",
... | make a channel name compatible with Matlab variable naming
Parameters
----------
name : str
channel name
Returns
-------
compatible_name : str
channel name compatible with Matlab | [
"make",
"a",
"channel",
"name",
"compatible",
"with",
"Matlab",
"variable",
"naming"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L149-L172 | train | 221,691 |
danielhrisca/asammdf | asammdf/blocks/utils.py | get_text_v3 | def get_text_v3(address, stream, mapped=False):
""" faster way to extract strings from mdf versions 2 and 3 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string
"""
if address == 0:
return ""
if mapped:
size, = UINT16_uf(stream, address + 2)
text_bytes = stream[address + 4: address + size]
else:
stream.seek(address + 2)
size = UINT16_u(stream.read(2))[0] - 4
text_bytes = stream.read(size)
try:
text = text_bytes.strip(b" \r\t\n\0").decode("latin-1")
except UnicodeDecodeError as err:
try:
from cchardet import detect
encoding = detect(text_bytes)["encoding"]
text = text_bytes.strip(b" \r\t\n\0").decode(encoding)
except ImportError:
logger.warning(
'Unicode exception occured and "cChardet" package is '
'not installed. Mdf version 3 expects "latin-1" '
"strings and this package may detect if a different"
" encoding was used"
)
raise err
return text | python | def get_text_v3(address, stream, mapped=False):
""" faster way to extract strings from mdf versions 2 and 3 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string
"""
if address == 0:
return ""
if mapped:
size, = UINT16_uf(stream, address + 2)
text_bytes = stream[address + 4: address + size]
else:
stream.seek(address + 2)
size = UINT16_u(stream.read(2))[0] - 4
text_bytes = stream.read(size)
try:
text = text_bytes.strip(b" \r\t\n\0").decode("latin-1")
except UnicodeDecodeError as err:
try:
from cchardet import detect
encoding = detect(text_bytes)["encoding"]
text = text_bytes.strip(b" \r\t\n\0").decode(encoding)
except ImportError:
logger.warning(
'Unicode exception occured and "cChardet" package is '
'not installed. Mdf version 3 expects "latin-1" '
"strings and this package may detect if a different"
" encoding was used"
)
raise err
return text | [
"def",
"get_text_v3",
"(",
"address",
",",
"stream",
",",
"mapped",
"=",
"False",
")",
":",
"if",
"address",
"==",
"0",
":",
"return",
"\"\"",
"if",
"mapped",
":",
"size",
",",
"=",
"UINT16_uf",
"(",
"stream",
",",
"address",
"+",
"2",
")",
"text_byt... | faster way to extract strings from mdf versions 2 and 3 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string | [
"faster",
"way",
"to",
"extract",
"strings",
"from",
"mdf",
"versions",
"2",
"and",
"3",
"TextBlock"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L175-L219 | train | 221,692 |
danielhrisca/asammdf | asammdf/blocks/utils.py | get_text_v4 | def get_text_v4(address, stream, mapped=False):
""" faster way to extract strings from mdf version 4 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string
"""
if address == 0:
return ""
if mapped:
size, _ = TWO_UINT64_uf(stream, address + 8)
text_bytes = stream[address + 24: address + size]
else:
stream.seek(address + 8)
size, _ = TWO_UINT64_u(stream.read(16))
text_bytes = stream.read(size - 24)
try:
text = text_bytes.strip(b" \r\t\n\0").decode("utf-8")
except UnicodeDecodeError as err:
try:
from cchardet import detect
encoding = detect(text_bytes)["encoding"]
text = text_bytes.decode(encoding).strip(" \r\t\n\0")
except ImportError:
logger.warning(
'Unicode exception occured and "cChardet" package is '
'not installed. Mdf version 4 expects "utf-8" '
"strings and this package may detect if a different"
" encoding was used"
)
raise err
return text | python | def get_text_v4(address, stream, mapped=False):
""" faster way to extract strings from mdf version 4 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string
"""
if address == 0:
return ""
if mapped:
size, _ = TWO_UINT64_uf(stream, address + 8)
text_bytes = stream[address + 24: address + size]
else:
stream.seek(address + 8)
size, _ = TWO_UINT64_u(stream.read(16))
text_bytes = stream.read(size - 24)
try:
text = text_bytes.strip(b" \r\t\n\0").decode("utf-8")
except UnicodeDecodeError as err:
try:
from cchardet import detect
encoding = detect(text_bytes)["encoding"]
text = text_bytes.decode(encoding).strip(" \r\t\n\0")
except ImportError:
logger.warning(
'Unicode exception occured and "cChardet" package is '
'not installed. Mdf version 4 expects "utf-8" '
"strings and this package may detect if a different"
" encoding was used"
)
raise err
return text | [
"def",
"get_text_v4",
"(",
"address",
",",
"stream",
",",
"mapped",
"=",
"False",
")",
":",
"if",
"address",
"==",
"0",
":",
"return",
"\"\"",
"if",
"mapped",
":",
"size",
",",
"_",
"=",
"TWO_UINT64_uf",
"(",
"stream",
",",
"address",
"+",
"8",
")",
... | faster way to extract strings from mdf version 4 TextBlock
Parameters
----------
address : int
TextBlock address
stream : handle
file IO handle
Returns
-------
text : str
unicode string | [
"faster",
"way",
"to",
"extract",
"strings",
"from",
"mdf",
"version",
"4",
"TextBlock"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L222-L266 | train | 221,693 |
danielhrisca/asammdf | asammdf/blocks/utils.py | get_fmt_v3 | def get_fmt_v3(data_type, size):
"""convert mdf versions 2 and 3 channel data type to numpy dtype format
string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
Returns
-------
fmt : str
numpy compatible data type format string
"""
if data_type in {v3c.DATA_TYPE_STRING, v3c.DATA_TYPE_BYTEARRAY}:
size = size // 8
if data_type == v3c.DATA_TYPE_STRING:
fmt = f"S{size}"
elif data_type == v3c.DATA_TYPE_BYTEARRAY:
fmt = f"({size},)u1"
else:
if size <= 8:
size = 1
elif size <= 16:
size = 2
elif size <= 32:
size = 4
elif size <= 64:
size = 8
else:
size = size // 8
if data_type in (v3c.DATA_TYPE_UNSIGNED_INTEL, v3c.DATA_TYPE_UNSIGNED):
fmt = f"<u{size}".format()
elif data_type == v3c.DATA_TYPE_UNSIGNED_MOTOROLA:
fmt = f">u{size}"
elif data_type in (v3c.DATA_TYPE_SIGNED_INTEL, v3c.DATA_TYPE_SIGNED):
fmt = f"<i{size}"
elif data_type == v3c.DATA_TYPE_SIGNED_MOTOROLA:
fmt = f">i{size}"
elif data_type in {
v3c.DATA_TYPE_FLOAT,
v3c.DATA_TYPE_DOUBLE,
v3c.DATA_TYPE_FLOAT_INTEL,
v3c.DATA_TYPE_DOUBLE_INTEL,
}:
fmt = f"<f{size}"
elif data_type in (v3c.DATA_TYPE_FLOAT_MOTOROLA, v3c.DATA_TYPE_DOUBLE_MOTOROLA):
fmt = f">f{size}"
return fmt | python | def get_fmt_v3(data_type, size):
"""convert mdf versions 2 and 3 channel data type to numpy dtype format
string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
Returns
-------
fmt : str
numpy compatible data type format string
"""
if data_type in {v3c.DATA_TYPE_STRING, v3c.DATA_TYPE_BYTEARRAY}:
size = size // 8
if data_type == v3c.DATA_TYPE_STRING:
fmt = f"S{size}"
elif data_type == v3c.DATA_TYPE_BYTEARRAY:
fmt = f"({size},)u1"
else:
if size <= 8:
size = 1
elif size <= 16:
size = 2
elif size <= 32:
size = 4
elif size <= 64:
size = 8
else:
size = size // 8
if data_type in (v3c.DATA_TYPE_UNSIGNED_INTEL, v3c.DATA_TYPE_UNSIGNED):
fmt = f"<u{size}".format()
elif data_type == v3c.DATA_TYPE_UNSIGNED_MOTOROLA:
fmt = f">u{size}"
elif data_type in (v3c.DATA_TYPE_SIGNED_INTEL, v3c.DATA_TYPE_SIGNED):
fmt = f"<i{size}"
elif data_type == v3c.DATA_TYPE_SIGNED_MOTOROLA:
fmt = f">i{size}"
elif data_type in {
v3c.DATA_TYPE_FLOAT,
v3c.DATA_TYPE_DOUBLE,
v3c.DATA_TYPE_FLOAT_INTEL,
v3c.DATA_TYPE_DOUBLE_INTEL,
}:
fmt = f"<f{size}"
elif data_type in (v3c.DATA_TYPE_FLOAT_MOTOROLA, v3c.DATA_TYPE_DOUBLE_MOTOROLA):
fmt = f">f{size}"
return fmt | [
"def",
"get_fmt_v3",
"(",
"data_type",
",",
"size",
")",
":",
"if",
"data_type",
"in",
"{",
"v3c",
".",
"DATA_TYPE_STRING",
",",
"v3c",
".",
"DATA_TYPE_BYTEARRAY",
"}",
":",
"size",
"=",
"size",
"//",
"8",
"if",
"data_type",
"==",
"v3c",
".",
"DATA_TYPE_... | convert mdf versions 2 and 3 channel data type to numpy dtype format
string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
Returns
-------
fmt : str
numpy compatible data type format string | [
"convert",
"mdf",
"versions",
"2",
"and",
"3",
"channel",
"data",
"type",
"to",
"numpy",
"dtype",
"format",
"string"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L273-L330 | train | 221,694 |
danielhrisca/asammdf | asammdf/blocks/utils.py | get_fmt_v4 | def get_fmt_v4(data_type, size, channel_type=v4c.CHANNEL_TYPE_VALUE):
"""convert mdf version 4 channel data type to numpy dtype format string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
channel_type: int
mdf channel type
Returns
-------
fmt : str
numpy compatible data type format string
"""
if data_type in v4c.NON_SCALAR_TYPES:
size = size // 8
if data_type == v4c.DATA_TYPE_BYTEARRAY:
if channel_type == v4c.CHANNEL_TYPE_VALUE:
fmt = f"({size},)u1"
else:
if size == 4:
fmt = "<u4"
elif size == 8:
fmt = "<u8"
elif data_type in v4c.STRING_TYPES:
if channel_type == v4c.CHANNEL_TYPE_VALUE:
fmt = f"S{size}"
else:
if size == 4:
fmt = "<u4"
elif size == 8:
fmt = "<u8"
elif data_type == v4c.DATA_TYPE_CANOPEN_DATE:
fmt = "V7"
elif data_type == v4c.DATA_TYPE_CANOPEN_TIME:
fmt = "V6"
else:
if size <= 8:
size = 1
elif size <= 16:
size = 2
elif size <= 32:
size = 4
elif size <= 64:
size = 8
else:
size = size // 8
if data_type == v4c.DATA_TYPE_UNSIGNED_INTEL:
fmt = f"<u{size}"
elif data_type == v4c.DATA_TYPE_UNSIGNED_MOTOROLA:
fmt = f">u{size}"
elif data_type == v4c.DATA_TYPE_SIGNED_INTEL:
fmt = f"<i{size}"
elif data_type == v4c.DATA_TYPE_SIGNED_MOTOROLA:
fmt = f">i{size}"
elif data_type == v4c.DATA_TYPE_REAL_INTEL:
fmt = f"<f{size}"
elif data_type == v4c.DATA_TYPE_REAL_MOTOROLA:
fmt = f">f{size}"
return fmt | python | def get_fmt_v4(data_type, size, channel_type=v4c.CHANNEL_TYPE_VALUE):
"""convert mdf version 4 channel data type to numpy dtype format string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
channel_type: int
mdf channel type
Returns
-------
fmt : str
numpy compatible data type format string
"""
if data_type in v4c.NON_SCALAR_TYPES:
size = size // 8
if data_type == v4c.DATA_TYPE_BYTEARRAY:
if channel_type == v4c.CHANNEL_TYPE_VALUE:
fmt = f"({size},)u1"
else:
if size == 4:
fmt = "<u4"
elif size == 8:
fmt = "<u8"
elif data_type in v4c.STRING_TYPES:
if channel_type == v4c.CHANNEL_TYPE_VALUE:
fmt = f"S{size}"
else:
if size == 4:
fmt = "<u4"
elif size == 8:
fmt = "<u8"
elif data_type == v4c.DATA_TYPE_CANOPEN_DATE:
fmt = "V7"
elif data_type == v4c.DATA_TYPE_CANOPEN_TIME:
fmt = "V6"
else:
if size <= 8:
size = 1
elif size <= 16:
size = 2
elif size <= 32:
size = 4
elif size <= 64:
size = 8
else:
size = size // 8
if data_type == v4c.DATA_TYPE_UNSIGNED_INTEL:
fmt = f"<u{size}"
elif data_type == v4c.DATA_TYPE_UNSIGNED_MOTOROLA:
fmt = f">u{size}"
elif data_type == v4c.DATA_TYPE_SIGNED_INTEL:
fmt = f"<i{size}"
elif data_type == v4c.DATA_TYPE_SIGNED_MOTOROLA:
fmt = f">i{size}"
elif data_type == v4c.DATA_TYPE_REAL_INTEL:
fmt = f"<f{size}"
elif data_type == v4c.DATA_TYPE_REAL_MOTOROLA:
fmt = f">f{size}"
return fmt | [
"def",
"get_fmt_v4",
"(",
"data_type",
",",
"size",
",",
"channel_type",
"=",
"v4c",
".",
"CHANNEL_TYPE_VALUE",
")",
":",
"if",
"data_type",
"in",
"v4c",
".",
"NON_SCALAR_TYPES",
":",
"size",
"=",
"size",
"//",
"8",
"if",
"data_type",
"==",
"v4c",
".",
"... | convert mdf version 4 channel data type to numpy dtype format string
Parameters
----------
data_type : int
mdf channel data type
size : int
data bit size
channel_type: int
mdf channel type
Returns
-------
fmt : str
numpy compatible data type format string | [
"convert",
"mdf",
"version",
"4",
"channel",
"data",
"type",
"to",
"numpy",
"dtype",
"format",
"string"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L333-L409 | train | 221,695 |
danielhrisca/asammdf | asammdf/blocks/utils.py | fmt_to_datatype_v3 | def fmt_to_datatype_v3(fmt, shape, array=False):
"""convert numpy dtype format string to mdf versions 2 and 3
channel data type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size
"""
size = fmt.itemsize * 8
if not array and shape[1:] and fmt.itemsize == 1 and fmt.kind == "u":
data_type = v3c.DATA_TYPE_BYTEARRAY
for dim in shape[1:]:
size *= dim
else:
if fmt.kind == "u":
if fmt.byteorder in "=<|":
data_type = v3c.DATA_TYPE_UNSIGNED
else:
data_type = v3c.DATA_TYPE_UNSIGNED_MOTOROLA
elif fmt.kind == "i":
if fmt.byteorder in "=<|":
data_type = v3c.DATA_TYPE_SIGNED
else:
data_type = v3c.DATA_TYPE_SIGNED_MOTOROLA
elif fmt.kind == "f":
if fmt.byteorder in "=<":
if size == 32:
data_type = v3c.DATA_TYPE_FLOAT
else:
data_type = v3c.DATA_TYPE_DOUBLE
else:
if size == 32:
data_type = v3c.DATA_TYPE_FLOAT_MOTOROLA
else:
data_type = v3c.DATA_TYPE_DOUBLE_MOTOROLA
elif fmt.kind in "SV":
data_type = v3c.DATA_TYPE_STRING
elif fmt.kind == "b":
data_type = v3c.DATA_TYPE_UNSIGNED
size = 1
else:
message = f"Unknown type: dtype={fmt}, shape={shape}"
logger.exception(message)
raise MdfException(message)
return data_type, size | python | def fmt_to_datatype_v3(fmt, shape, array=False):
"""convert numpy dtype format string to mdf versions 2 and 3
channel data type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size
"""
size = fmt.itemsize * 8
if not array and shape[1:] and fmt.itemsize == 1 and fmt.kind == "u":
data_type = v3c.DATA_TYPE_BYTEARRAY
for dim in shape[1:]:
size *= dim
else:
if fmt.kind == "u":
if fmt.byteorder in "=<|":
data_type = v3c.DATA_TYPE_UNSIGNED
else:
data_type = v3c.DATA_TYPE_UNSIGNED_MOTOROLA
elif fmt.kind == "i":
if fmt.byteorder in "=<|":
data_type = v3c.DATA_TYPE_SIGNED
else:
data_type = v3c.DATA_TYPE_SIGNED_MOTOROLA
elif fmt.kind == "f":
if fmt.byteorder in "=<":
if size == 32:
data_type = v3c.DATA_TYPE_FLOAT
else:
data_type = v3c.DATA_TYPE_DOUBLE
else:
if size == 32:
data_type = v3c.DATA_TYPE_FLOAT_MOTOROLA
else:
data_type = v3c.DATA_TYPE_DOUBLE_MOTOROLA
elif fmt.kind in "SV":
data_type = v3c.DATA_TYPE_STRING
elif fmt.kind == "b":
data_type = v3c.DATA_TYPE_UNSIGNED
size = 1
else:
message = f"Unknown type: dtype={fmt}, shape={shape}"
logger.exception(message)
raise MdfException(message)
return data_type, size | [
"def",
"fmt_to_datatype_v3",
"(",
"fmt",
",",
"shape",
",",
"array",
"=",
"False",
")",
":",
"size",
"=",
"fmt",
".",
"itemsize",
"*",
"8",
"if",
"not",
"array",
"and",
"shape",
"[",
"1",
":",
"]",
"and",
"fmt",
".",
"itemsize",
"==",
"1",
"and",
... | convert numpy dtype format string to mdf versions 2 and 3
channel data type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size | [
"convert",
"numpy",
"dtype",
"format",
"string",
"to",
"mdf",
"versions",
"2",
"and",
"3",
"channel",
"data",
"type",
"and",
"size"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L412-L469 | train | 221,696 |
danielhrisca/asammdf | asammdf/blocks/utils.py | info_to_datatype_v4 | def info_to_datatype_v4(signed, little_endian):
"""map CAN signal to MDF integer types
Parameters
----------
signed : bool
signal is flagged as signed in the CAN database
little_endian : bool
signal is flagged as little endian (Intel) in the CAN database
Returns
-------
datatype : int
integer code for MDF channel data type
"""
if signed:
if little_endian:
datatype = v4c.DATA_TYPE_SIGNED_INTEL
else:
datatype = v4c.DATA_TYPE_SIGNED_MOTOROLA
else:
if little_endian:
datatype = v4c.DATA_TYPE_UNSIGNED_INTEL
else:
datatype = v4c.DATA_TYPE_UNSIGNED_MOTOROLA
return datatype | python | def info_to_datatype_v4(signed, little_endian):
"""map CAN signal to MDF integer types
Parameters
----------
signed : bool
signal is flagged as signed in the CAN database
little_endian : bool
signal is flagged as little endian (Intel) in the CAN database
Returns
-------
datatype : int
integer code for MDF channel data type
"""
if signed:
if little_endian:
datatype = v4c.DATA_TYPE_SIGNED_INTEL
else:
datatype = v4c.DATA_TYPE_SIGNED_MOTOROLA
else:
if little_endian:
datatype = v4c.DATA_TYPE_UNSIGNED_INTEL
else:
datatype = v4c.DATA_TYPE_UNSIGNED_MOTOROLA
return datatype | [
"def",
"info_to_datatype_v4",
"(",
"signed",
",",
"little_endian",
")",
":",
"if",
"signed",
":",
"if",
"little_endian",
":",
"datatype",
"=",
"v4c",
".",
"DATA_TYPE_SIGNED_INTEL",
"else",
":",
"datatype",
"=",
"v4c",
".",
"DATA_TYPE_SIGNED_MOTOROLA",
"else",
":... | map CAN signal to MDF integer types
Parameters
----------
signed : bool
signal is flagged as signed in the CAN database
little_endian : bool
signal is flagged as little endian (Intel) in the CAN database
Returns
-------
datatype : int
integer code for MDF channel data type | [
"map",
"CAN",
"signal",
"to",
"MDF",
"integer",
"types"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L472-L500 | train | 221,697 |
danielhrisca/asammdf | asammdf/blocks/utils.py | fmt_to_datatype_v4 | def fmt_to_datatype_v4(fmt, shape, array=False):
"""convert numpy dtype format string to mdf version 4 channel data
type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size
"""
size = fmt.itemsize * 8
if not array and shape[1:] and fmt.itemsize == 1 and fmt.kind == "u":
data_type = v4c.DATA_TYPE_BYTEARRAY
for dim in shape[1:]:
size *= dim
else:
if fmt.kind == "u":
if fmt.byteorder in "=<|":
data_type = v4c.DATA_TYPE_UNSIGNED_INTEL
else:
data_type = v4c.DATA_TYPE_UNSIGNED_MOTOROLA
elif fmt.kind == "i":
if fmt.byteorder in "=<|":
data_type = v4c.DATA_TYPE_SIGNED_INTEL
else:
data_type = v4c.DATA_TYPE_SIGNED_MOTOROLA
elif fmt.kind == "f":
if fmt.byteorder in "=<":
data_type = v4c.DATA_TYPE_REAL_INTEL
else:
data_type = v4c.DATA_TYPE_REAL_MOTOROLA
elif fmt.kind in "SV":
data_type = v4c.DATA_TYPE_STRING_LATIN_1
elif fmt.kind == "b":
data_type = v4c.DATA_TYPE_UNSIGNED_INTEL
size = 1
else:
message = f"Unknown type: dtype={fmt}, shape={shape}"
logger.exception(message)
raise MdfException(message)
return data_type, size | python | def fmt_to_datatype_v4(fmt, shape, array=False):
"""convert numpy dtype format string to mdf version 4 channel data
type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size
"""
size = fmt.itemsize * 8
if not array and shape[1:] and fmt.itemsize == 1 and fmt.kind == "u":
data_type = v4c.DATA_TYPE_BYTEARRAY
for dim in shape[1:]:
size *= dim
else:
if fmt.kind == "u":
if fmt.byteorder in "=<|":
data_type = v4c.DATA_TYPE_UNSIGNED_INTEL
else:
data_type = v4c.DATA_TYPE_UNSIGNED_MOTOROLA
elif fmt.kind == "i":
if fmt.byteorder in "=<|":
data_type = v4c.DATA_TYPE_SIGNED_INTEL
else:
data_type = v4c.DATA_TYPE_SIGNED_MOTOROLA
elif fmt.kind == "f":
if fmt.byteorder in "=<":
data_type = v4c.DATA_TYPE_REAL_INTEL
else:
data_type = v4c.DATA_TYPE_REAL_MOTOROLA
elif fmt.kind in "SV":
data_type = v4c.DATA_TYPE_STRING_LATIN_1
elif fmt.kind == "b":
data_type = v4c.DATA_TYPE_UNSIGNED_INTEL
size = 1
else:
message = f"Unknown type: dtype={fmt}, shape={shape}"
logger.exception(message)
raise MdfException(message)
return data_type, size | [
"def",
"fmt_to_datatype_v4",
"(",
"fmt",
",",
"shape",
",",
"array",
"=",
"False",
")",
":",
"size",
"=",
"fmt",
".",
"itemsize",
"*",
"8",
"if",
"not",
"array",
"and",
"shape",
"[",
"1",
":",
"]",
"and",
"fmt",
".",
"itemsize",
"==",
"1",
"and",
... | convert numpy dtype format string to mdf version 4 channel data
type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearray and channel array
Returns
-------
data_type, size : int, int
integer data type as defined by ASAM MDF and bit size | [
"convert",
"numpy",
"dtype",
"format",
"string",
"to",
"mdf",
"version",
"4",
"channel",
"data",
"type",
"and",
"size"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L503-L555 | train | 221,698 |
danielhrisca/asammdf | asammdf/blocks/utils.py | debug_channel | def debug_channel(mdf, group, channel, dependency, file=None):
""" use this to print debug information in case of errors
Parameters
----------
mdf : MDF
source MDF object
group : dict
group
channel : Channel
channel object
dependency : ChannelDependency
channel dependency object
"""
print("MDF", "=" * 76, file=file)
print("name:", mdf.name, file=file)
print("version:", mdf.version, file=file)
print("read fragment size:", mdf._read_fragment_size, file=file)
print("write fragment size:", mdf._write_fragment_size, file=file)
print()
parents, dtypes = mdf._prepare_record(group)
print("GROUP", "=" * 74, file=file)
print("sorted:", group["sorted"], file=file)
print("data location:", group["data_location"], file=file)
print("data size:", group["data_size"], file=file)
print("data blocks:", group.data_blocks, file=file)
print("dependencies", group["channel_dependencies"], file=file)
print("parents:", parents, file=file)
print("dtypes:", dtypes, file=file)
print(file=file)
cg = group["channel_group"]
print("CHANNEL GROUP", "=" * 66, file=file)
print(cg, file=file)
print(file=file)
print("CHANNEL", "=" * 72, file=file)
print(channel, file=file)
print(file=file)
print("CHANNEL ARRAY", "=" * 66, file=file)
print(dependency, file=file)
print(file=file)
print("MASTER CACHE", "=" * 67, file=file)
print(
[(key, len(val)) for key, val in mdf._master_channel_cache.items()], file=file
) | python | def debug_channel(mdf, group, channel, dependency, file=None):
""" use this to print debug information in case of errors
Parameters
----------
mdf : MDF
source MDF object
group : dict
group
channel : Channel
channel object
dependency : ChannelDependency
channel dependency object
"""
print("MDF", "=" * 76, file=file)
print("name:", mdf.name, file=file)
print("version:", mdf.version, file=file)
print("read fragment size:", mdf._read_fragment_size, file=file)
print("write fragment size:", mdf._write_fragment_size, file=file)
print()
parents, dtypes = mdf._prepare_record(group)
print("GROUP", "=" * 74, file=file)
print("sorted:", group["sorted"], file=file)
print("data location:", group["data_location"], file=file)
print("data size:", group["data_size"], file=file)
print("data blocks:", group.data_blocks, file=file)
print("dependencies", group["channel_dependencies"], file=file)
print("parents:", parents, file=file)
print("dtypes:", dtypes, file=file)
print(file=file)
cg = group["channel_group"]
print("CHANNEL GROUP", "=" * 66, file=file)
print(cg, file=file)
print(file=file)
print("CHANNEL", "=" * 72, file=file)
print(channel, file=file)
print(file=file)
print("CHANNEL ARRAY", "=" * 66, file=file)
print(dependency, file=file)
print(file=file)
print("MASTER CACHE", "=" * 67, file=file)
print(
[(key, len(val)) for key, val in mdf._master_channel_cache.items()], file=file
) | [
"def",
"debug_channel",
"(",
"mdf",
",",
"group",
",",
"channel",
",",
"dependency",
",",
"file",
"=",
"None",
")",
":",
"print",
"(",
"\"MDF\"",
",",
"\"=\"",
"*",
"76",
",",
"file",
"=",
"file",
")",
"print",
"(",
"\"name:\"",
",",
"mdf",
".",
"n... | use this to print debug information in case of errors
Parameters
----------
mdf : MDF
source MDF object
group : dict
group
channel : Channel
channel object
dependency : ChannelDependency
channel dependency object | [
"use",
"this",
"to",
"print",
"debug",
"information",
"in",
"case",
"of",
"errors"
] | 3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66 | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/utils.py#L594-L643 | train | 221,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.