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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
bitesofcode/projexui | projexui/widgets/xtoolbar.py | XToolBar.refreshButton | def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
if not btn:
return
btn.setMaximumSize(MAX_SIZE, MAX_SIZE)
# set up a vertical scrollbar
if self.orientation() == Qt.Vertical:
btn.setMaximumHeight(12)
else:
btn.setMaximumWidth(12)
icon = ''
# collapse/expand a vertical toolbar
if self.orientation() == Qt.Vertical:
if collapsed:
self.setFixedWidth(self._collapsedSize)
btn.setMaximumHeight(MAX_SIZE)
btn.setArrowType(Qt.RightArrow)
else:
self.setMaximumWidth(MAX_SIZE)
self._precollapseSize = None
btn.setMaximumHeight(12)
btn.setArrowType(Qt.LeftArrow)
else:
if collapsed:
self.setFixedHeight(self._collapsedSize)
btn.setMaximumWidth(MAX_SIZE)
btn.setArrowType(Qt.DownArrow)
else:
self.setMaximumHeight(1000)
self._precollapseSize = None
btn.setMaximumWidth(12)
btn.setArrowType(Qt.UpArrow)
for index in range(1, self.layout().count()):
item = self.layout().itemAt(index)
if not item.widget():
continue
if collapsed:
item.widget().setMaximumSize(0, 0)
else:
item.widget().setMaximumSize(MAX_SIZE, MAX_SIZE)
if not self.isCollapsable():
btn.hide()
else:
btn.show() | python | def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
if not btn:
return
btn.setMaximumSize(MAX_SIZE, MAX_SIZE)
# set up a vertical scrollbar
if self.orientation() == Qt.Vertical:
btn.setMaximumHeight(12)
else:
btn.setMaximumWidth(12)
icon = ''
# collapse/expand a vertical toolbar
if self.orientation() == Qt.Vertical:
if collapsed:
self.setFixedWidth(self._collapsedSize)
btn.setMaximumHeight(MAX_SIZE)
btn.setArrowType(Qt.RightArrow)
else:
self.setMaximumWidth(MAX_SIZE)
self._precollapseSize = None
btn.setMaximumHeight(12)
btn.setArrowType(Qt.LeftArrow)
else:
if collapsed:
self.setFixedHeight(self._collapsedSize)
btn.setMaximumWidth(MAX_SIZE)
btn.setArrowType(Qt.DownArrow)
else:
self.setMaximumHeight(1000)
self._precollapseSize = None
btn.setMaximumWidth(12)
btn.setArrowType(Qt.UpArrow)
for index in range(1, self.layout().count()):
item = self.layout().itemAt(index)
if not item.widget():
continue
if collapsed:
item.widget().setMaximumSize(0, 0)
else:
item.widget().setMaximumSize(MAX_SIZE, MAX_SIZE)
if not self.isCollapsable():
btn.hide()
else:
btn.show() | [
"def",
"refreshButton",
"(",
"self",
")",
":",
"collapsed",
"=",
"self",
".",
"isCollapsed",
"(",
")",
"btn",
"=",
"self",
".",
"_collapseButton",
"if",
"not",
"btn",
":",
"return",
"btn",
".",
"setMaximumSize",
"(",
"MAX_SIZE",
",",
"MAX_SIZE",
")",
"# set up a vertical scrollbar",
"if",
"self",
".",
"orientation",
"(",
")",
"==",
"Qt",
".",
"Vertical",
":",
"btn",
".",
"setMaximumHeight",
"(",
"12",
")",
"else",
":",
"btn",
".",
"setMaximumWidth",
"(",
"12",
")",
"icon",
"=",
"''",
"# collapse/expand a vertical toolbar",
"if",
"self",
".",
"orientation",
"(",
")",
"==",
"Qt",
".",
"Vertical",
":",
"if",
"collapsed",
":",
"self",
".",
"setFixedWidth",
"(",
"self",
".",
"_collapsedSize",
")",
"btn",
".",
"setMaximumHeight",
"(",
"MAX_SIZE",
")",
"btn",
".",
"setArrowType",
"(",
"Qt",
".",
"RightArrow",
")",
"else",
":",
"self",
".",
"setMaximumWidth",
"(",
"MAX_SIZE",
")",
"self",
".",
"_precollapseSize",
"=",
"None",
"btn",
".",
"setMaximumHeight",
"(",
"12",
")",
"btn",
".",
"setArrowType",
"(",
"Qt",
".",
"LeftArrow",
")",
"else",
":",
"if",
"collapsed",
":",
"self",
".",
"setFixedHeight",
"(",
"self",
".",
"_collapsedSize",
")",
"btn",
".",
"setMaximumWidth",
"(",
"MAX_SIZE",
")",
"btn",
".",
"setArrowType",
"(",
"Qt",
".",
"DownArrow",
")",
"else",
":",
"self",
".",
"setMaximumHeight",
"(",
"1000",
")",
"self",
".",
"_precollapseSize",
"=",
"None",
"btn",
".",
"setMaximumWidth",
"(",
"12",
")",
"btn",
".",
"setArrowType",
"(",
"Qt",
".",
"UpArrow",
")",
"for",
"index",
"in",
"range",
"(",
"1",
",",
"self",
".",
"layout",
"(",
")",
".",
"count",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"layout",
"(",
")",
".",
"itemAt",
"(",
"index",
")",
"if",
"not",
"item",
".",
"widget",
"(",
")",
":",
"continue",
"if",
"collapsed",
":",
"item",
".",
"widget",
"(",
")",
".",
"setMaximumSize",
"(",
"0",
",",
"0",
")",
"else",
":",
"item",
".",
"widget",
"(",
")",
".",
"setMaximumSize",
"(",
"MAX_SIZE",
",",
"MAX_SIZE",
")",
"if",
"not",
"self",
".",
"isCollapsable",
"(",
")",
":",
"btn",
".",
"hide",
"(",
")",
"else",
":",
"btn",
".",
"show",
"(",
")"
] | Refreshes the button for this toolbar. | [
"Refreshes",
"the",
"button",
"for",
"this",
"toolbar",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbar.py#L138-L194 | train |
ubernostrum/django-soapbox | soapbox/models.py | MessageManager.match | def match(self, url):
"""
Return a list of all active Messages which match the given
URL.
"""
return list({
message for message in self.active() if
message.is_global or message.match(url)
}) | python | def match(self, url):
"""
Return a list of all active Messages which match the given
URL.
"""
return list({
message for message in self.active() if
message.is_global or message.match(url)
}) | [
"def",
"match",
"(",
"self",
",",
"url",
")",
":",
"return",
"list",
"(",
"{",
"message",
"for",
"message",
"in",
"self",
".",
"active",
"(",
")",
"if",
"message",
".",
"is_global",
"or",
"message",
".",
"match",
"(",
"url",
")",
"}",
")"
] | Return a list of all active Messages which match the given
URL. | [
"Return",
"a",
"list",
"of",
"all",
"active",
"Messages",
"which",
"match",
"the",
"given",
"URL",
"."
] | f9189e1ddf47175f2392b92c7a0a902817ee1e93 | https://github.com/ubernostrum/django-soapbox/blob/f9189e1ddf47175f2392b92c7a0a902817ee1e93/soapbox/models.py#L36-L45 | train |
bitesofcode/projexui | projexui/widgets/xchart/xchartdatasetitem.py | XChartDatasetItem.paint | def paint(self, painter, option, widget):
"""
Draws this item with the inputed painter. This will call the
scene's renderer to draw this item.
"""
scene = self.scene()
if not scene:
return
scene.chart().renderer().drawItem(self, painter, option) | python | def paint(self, painter, option, widget):
"""
Draws this item with the inputed painter. This will call the
scene's renderer to draw this item.
"""
scene = self.scene()
if not scene:
return
scene.chart().renderer().drawItem(self, painter, option) | [
"def",
"paint",
"(",
"self",
",",
"painter",
",",
"option",
",",
"widget",
")",
":",
"scene",
"=",
"self",
".",
"scene",
"(",
")",
"if",
"not",
"scene",
":",
"return",
"scene",
".",
"chart",
"(",
")",
".",
"renderer",
"(",
")",
".",
"drawItem",
"(",
"self",
",",
"painter",
",",
"option",
")"
] | Draws this item with the inputed painter. This will call the
scene's renderer to draw this item. | [
"Draws",
"this",
"item",
"with",
"the",
"inputed",
"painter",
".",
"This",
"will",
"call",
"the",
"scene",
"s",
"renderer",
"to",
"draw",
"this",
"item",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchartdatasetitem.py#L78-L87 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.is_pg_at_least_nine_two | def is_pg_at_least_nine_two(self):
"""
Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean
"""
if self._is_pg_at_least_nine_two is None:
results = self.version()
regex = re.compile("PostgreSQL (\d+\.\d+\.\d+) on")
matches = regex.match(results[0].version)
version = matches.groups()[0]
if version > '9.2.0':
self._is_pg_at_least_nine_two = True
else:
self._is_pg_at_least_nine_two = False
return self._is_pg_at_least_nine_two | python | def is_pg_at_least_nine_two(self):
"""
Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean
"""
if self._is_pg_at_least_nine_two is None:
results = self.version()
regex = re.compile("PostgreSQL (\d+\.\d+\.\d+) on")
matches = regex.match(results[0].version)
version = matches.groups()[0]
if version > '9.2.0':
self._is_pg_at_least_nine_two = True
else:
self._is_pg_at_least_nine_two = False
return self._is_pg_at_least_nine_two | [
"def",
"is_pg_at_least_nine_two",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_pg_at_least_nine_two",
"is",
"None",
":",
"results",
"=",
"self",
".",
"version",
"(",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"PostgreSQL (\\d+\\.\\d+\\.\\d+) on\"",
")",
"matches",
"=",
"regex",
".",
"match",
"(",
"results",
"[",
"0",
"]",
".",
"version",
")",
"version",
"=",
"matches",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"if",
"version",
">",
"'9.2.0'",
":",
"self",
".",
"_is_pg_at_least_nine_two",
"=",
"True",
"else",
":",
"self",
".",
"_is_pg_at_least_nine_two",
"=",
"False",
"return",
"self",
".",
"_is_pg_at_least_nine_two"
] | Some queries have different syntax depending what version of postgres
we are querying against.
:returns: boolean | [
"Some",
"queries",
"have",
"different",
"syntax",
"depending",
"what",
"version",
"of",
"postgres",
"we",
"are",
"querying",
"against",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L104-L123 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.execute | def execute(self, statement):
"""
Execute the given sql statement.
:param statement: sql statement to run
:returns: list
"""
# Make the sql statement easier to read in case some of the queries we
# run end up in the output
sql = statement.replace('\n', '')
sql = ' '.join(sql.split())
self.cursor.execute(sql)
return self.cursor.fetchall() | python | def execute(self, statement):
"""
Execute the given sql statement.
:param statement: sql statement to run
:returns: list
"""
# Make the sql statement easier to read in case some of the queries we
# run end up in the output
sql = statement.replace('\n', '')
sql = ' '.join(sql.split())
self.cursor.execute(sql)
return self.cursor.fetchall() | [
"def",
"execute",
"(",
"self",
",",
"statement",
")",
":",
"# Make the sql statement easier to read in case some of the queries we",
"# run end up in the output",
"sql",
"=",
"statement",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"sql",
"=",
"' '",
".",
"join",
"(",
"sql",
".",
"split",
"(",
")",
")",
"self",
".",
"cursor",
".",
"execute",
"(",
"sql",
")",
"return",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")"
] | Execute the given sql statement.
:param statement: sql statement to run
:returns: list | [
"Execute",
"the",
"given",
"sql",
"statement",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L132-L146 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.calls | def calls(self, truncate=False):
"""
Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls='845590',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.query output if greater than 40 chars
:returns: list of Records
"""
if self.pg_stat_statement():
if truncate:
select = """
SELECT CASE
WHEN length(query) < 40
THEN query
ELSE substr(query, 0, 38) || '..'
END AS qry,
"""
else:
select = 'SELECT query,'
return self.execute(sql.CALLS.format(select=select))
else:
return [self.get_missing_pg_stat_statement_error()] | python | def calls(self, truncate=False):
"""
Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls='845590',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.query output if greater than 40 chars
:returns: list of Records
"""
if self.pg_stat_statement():
if truncate:
select = """
SELECT CASE
WHEN length(query) < 40
THEN query
ELSE substr(query, 0, 38) || '..'
END AS qry,
"""
else:
select = 'SELECT query,'
return self.execute(sql.CALLS.format(select=select))
else:
return [self.get_missing_pg_stat_statement_error()] | [
"def",
"calls",
"(",
"self",
",",
"truncate",
"=",
"False",
")",
":",
"if",
"self",
".",
"pg_stat_statement",
"(",
")",
":",
"if",
"truncate",
":",
"select",
"=",
"\"\"\"\n SELECT CASE\n WHEN length(query) < 40\n THEN query\n ELSE substr(query, 0, 38) || '..'\n END AS qry,\n \"\"\"",
"else",
":",
"select",
"=",
"'SELECT query,'",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"CALLS",
".",
"format",
"(",
"select",
"=",
"select",
")",
")",
"else",
":",
"return",
"[",
"self",
".",
"get_missing_pg_stat_statement_error",
"(",
")",
"]"
] | Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls='845590',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.query output if greater than 40 chars
:returns: list of Records | [
"Show",
"10",
"most",
"frequently",
"called",
"queries",
".",
"Requires",
"the",
"pg_stat_statements",
"Postgres",
"module",
"to",
"be",
"installed",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L177-L208 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.blocking | def blocking(self):
"""
Display queries holding locks other queries are waiting to be
released.
Record(
pid=40821,
source='',
running_for=datetime.timedelta(0, 0, 2857),
waiting=False,
query='SELECT pg_sleep(10);'
)
:returns: list of Records
"""
return self.execute(
sql.BLOCKING.format(
query_column=self.query_column,
pid_column=self.pid_column
)
) | python | def blocking(self):
"""
Display queries holding locks other queries are waiting to be
released.
Record(
pid=40821,
source='',
running_for=datetime.timedelta(0, 0, 2857),
waiting=False,
query='SELECT pg_sleep(10);'
)
:returns: list of Records
"""
return self.execute(
sql.BLOCKING.format(
query_column=self.query_column,
pid_column=self.pid_column
)
) | [
"def",
"blocking",
"(",
"self",
")",
":",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"BLOCKING",
".",
"format",
"(",
"query_column",
"=",
"self",
".",
"query_column",
",",
"pid_column",
"=",
"self",
".",
"pid_column",
")",
")"
] | Display queries holding locks other queries are waiting to be
released.
Record(
pid=40821,
source='',
running_for=datetime.timedelta(0, 0, 2857),
waiting=False,
query='SELECT pg_sleep(10);'
)
:returns: list of Records | [
"Display",
"queries",
"holding",
"locks",
"other",
"queries",
"are",
"waiting",
"to",
"be",
"released",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L210-L231 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.outliers | def outliers(self, truncate=False):
"""
Show 10 queries that have longest execution time in aggregate. Requires
the pg_stat_statments Postgres module to be installed.
Record(
qry='UPDATE pgbench_tellers SET tbalance = tbalance + ?;',
exec_time=datetime.timedelta(0, 19944, 993099),
prop_exec_time='67.1%',
ncalls='845589',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.qry output if greater than 40 chars
:returns: list of Records
"""
if self.pg_stat_statement():
if truncate:
query = """
CASE WHEN length(query) < 40
THEN query
ELSE substr(query, 0, 38) || '..'
END
"""
else:
query = 'query'
return self.execute(sql.OUTLIERS.format(query=query))
else:
return [self.get_missing_pg_stat_statement_error()] | python | def outliers(self, truncate=False):
"""
Show 10 queries that have longest execution time in aggregate. Requires
the pg_stat_statments Postgres module to be installed.
Record(
qry='UPDATE pgbench_tellers SET tbalance = tbalance + ?;',
exec_time=datetime.timedelta(0, 19944, 993099),
prop_exec_time='67.1%',
ncalls='845589',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.qry output if greater than 40 chars
:returns: list of Records
"""
if self.pg_stat_statement():
if truncate:
query = """
CASE WHEN length(query) < 40
THEN query
ELSE substr(query, 0, 38) || '..'
END
"""
else:
query = 'query'
return self.execute(sql.OUTLIERS.format(query=query))
else:
return [self.get_missing_pg_stat_statement_error()] | [
"def",
"outliers",
"(",
"self",
",",
"truncate",
"=",
"False",
")",
":",
"if",
"self",
".",
"pg_stat_statement",
"(",
")",
":",
"if",
"truncate",
":",
"query",
"=",
"\"\"\"\n CASE WHEN length(query) < 40\n THEN query\n ELSE substr(query, 0, 38) || '..'\n END\n \"\"\"",
"else",
":",
"query",
"=",
"'query'",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"OUTLIERS",
".",
"format",
"(",
"query",
"=",
"query",
")",
")",
"else",
":",
"return",
"[",
"self",
".",
"get_missing_pg_stat_statement_error",
"(",
")",
"]"
] | Show 10 queries that have longest execution time in aggregate. Requires
the pg_stat_statments Postgres module to be installed.
Record(
qry='UPDATE pgbench_tellers SET tbalance = tbalance + ?;',
exec_time=datetime.timedelta(0, 19944, 993099),
prop_exec_time='67.1%',
ncalls='845589',
sync_io_time=datetime.timedelta(0)
)
:param truncate: trim the Record.qry output if greater than 40 chars
:returns: list of Records | [
"Show",
"10",
"queries",
"that",
"have",
"longest",
"execution",
"time",
"in",
"aggregate",
".",
"Requires",
"the",
"pg_stat_statments",
"Postgres",
"module",
"to",
"be",
"installed",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L233-L263 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.long_running_queries | def long_running_queries(self):
"""
Show all queries longer than five minutes by descending duration.
Record(
pid=19578,
duration=datetime.timedelta(0, 19944, 993099),
query='SELECT * FROM students'
)
:returns: list of Records
"""
if self.is_pg_at_least_nine_two():
idle = "AND state <> 'idle'"
else:
idle = "AND current_query <> '<IDLE>'"
return self.execute(
sql.LONG_RUNNING_QUERIES.format(
pid_column=self.pid_column,
query_column=self.query_column,
idle=idle
)
) | python | def long_running_queries(self):
"""
Show all queries longer than five minutes by descending duration.
Record(
pid=19578,
duration=datetime.timedelta(0, 19944, 993099),
query='SELECT * FROM students'
)
:returns: list of Records
"""
if self.is_pg_at_least_nine_two():
idle = "AND state <> 'idle'"
else:
idle = "AND current_query <> '<IDLE>'"
return self.execute(
sql.LONG_RUNNING_QUERIES.format(
pid_column=self.pid_column,
query_column=self.query_column,
idle=idle
)
) | [
"def",
"long_running_queries",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_pg_at_least_nine_two",
"(",
")",
":",
"idle",
"=",
"\"AND state <> 'idle'\"",
"else",
":",
"idle",
"=",
"\"AND current_query <> '<IDLE>'\"",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"LONG_RUNNING_QUERIES",
".",
"format",
"(",
"pid_column",
"=",
"self",
".",
"pid_column",
",",
"query_column",
"=",
"self",
".",
"query_column",
",",
"idle",
"=",
"idle",
")",
")"
] | Show all queries longer than five minutes by descending duration.
Record(
pid=19578,
duration=datetime.timedelta(0, 19944, 993099),
query='SELECT * FROM students'
)
:returns: list of Records | [
"Show",
"all",
"queries",
"longer",
"than",
"five",
"minutes",
"by",
"descending",
"duration",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L303-L327 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.locks | def locks(self):
"""
Display queries with active locks.
Record(
procpid=31776,
relname=None,
transactionid=None,
granted=True,
query_snippet='select * from hello;',
age=datetime.timedelta(0, 0, 288174),
)
:returns: list of Records
"""
return self.execute(
sql.LOCKS.format(
pid_column=self.pid_column,
query_column=self.query_column
)
) | python | def locks(self):
"""
Display queries with active locks.
Record(
procpid=31776,
relname=None,
transactionid=None,
granted=True,
query_snippet='select * from hello;',
age=datetime.timedelta(0, 0, 288174),
)
:returns: list of Records
"""
return self.execute(
sql.LOCKS.format(
pid_column=self.pid_column,
query_column=self.query_column
)
) | [
"def",
"locks",
"(",
"self",
")",
":",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"LOCKS",
".",
"format",
"(",
"pid_column",
"=",
"self",
".",
"pid_column",
",",
"query_column",
"=",
"self",
".",
"query_column",
")",
")"
] | Display queries with active locks.
Record(
procpid=31776,
relname=None,
transactionid=None,
granted=True,
query_snippet='select * from hello;',
age=datetime.timedelta(0, 0, 288174),
)
:returns: list of Records | [
"Display",
"queries",
"with",
"active",
"locks",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L422-L443 | train |
scottwoodall/python-pgextras | pgextras/__init__.py | PgExtras.ps | def ps(self):
"""
View active queries with execution time.
Record(
pid=28023,
source='pgbench',
running_for=datetime.timedelta(0, 0, 288174),
waiting=0,
query='UPDATE pgbench_accounts SET abalance = abalance + 423;'
)
:returns: list of Records
"""
if self.is_pg_at_least_nine_two():
idle = "AND state <> 'idle'"
else:
idle = "AND current_query <> '<IDLE>'"
return self.execute(
sql.PS.format(
pid_column=self.pid_column,
query_column=self.query_column,
idle=idle
)
) | python | def ps(self):
"""
View active queries with execution time.
Record(
pid=28023,
source='pgbench',
running_for=datetime.timedelta(0, 0, 288174),
waiting=0,
query='UPDATE pgbench_accounts SET abalance = abalance + 423;'
)
:returns: list of Records
"""
if self.is_pg_at_least_nine_two():
idle = "AND state <> 'idle'"
else:
idle = "AND current_query <> '<IDLE>'"
return self.execute(
sql.PS.format(
pid_column=self.pid_column,
query_column=self.query_column,
idle=idle
)
) | [
"def",
"ps",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_pg_at_least_nine_two",
"(",
")",
":",
"idle",
"=",
"\"AND state <> 'idle'\"",
"else",
":",
"idle",
"=",
"\"AND current_query <> '<IDLE>'\"",
"return",
"self",
".",
"execute",
"(",
"sql",
".",
"PS",
".",
"format",
"(",
"pid_column",
"=",
"self",
".",
"pid_column",
",",
"query_column",
"=",
"self",
".",
"query_column",
",",
"idle",
"=",
"idle",
")",
")"
] | View active queries with execution time.
Record(
pid=28023,
source='pgbench',
running_for=datetime.timedelta(0, 0, 288174),
waiting=0,
query='UPDATE pgbench_accounts SET abalance = abalance + 423;'
)
:returns: list of Records | [
"View",
"active",
"queries",
"with",
"execution",
"time",
"."
] | d3aa83081d41b14b7c1f003cd837c812a2b5fff5 | https://github.com/scottwoodall/python-pgextras/blob/d3aa83081d41b14b7c1f003cd837c812a2b5fff5/pgextras/__init__.py#L460-L486 | train |
intelsdi-x/snap-plugin-lib-py | examples/publisher/file.py | File.publish | def publish(self, metrics, config):
"""Publishes metrics to a file in JSON format.
This method is called by the Snap deamon during the collection phase
of the execution of a Snap workflow.
In this example we are writing the metrics to a file in json format.
We obtain the path to the file through the config (`ConfigMap`) arg.
Args:
metrics (obj:`list` of :obj:`snap_plugin.v1.Metric`):
List of metrics to be collected.
Returns:
:obj:`list` of :obj:`snap_plugin.v1.Metric`:
List of collected metrics.
"""
if len(metrics) > 0:
with open(config["file"], 'a') as outfile:
for metric in metrics:
outfile.write(
json_format.MessageToJson(
metric._pb, including_default_value_fields=True)) | python | def publish(self, metrics, config):
"""Publishes metrics to a file in JSON format.
This method is called by the Snap deamon during the collection phase
of the execution of a Snap workflow.
In this example we are writing the metrics to a file in json format.
We obtain the path to the file through the config (`ConfigMap`) arg.
Args:
metrics (obj:`list` of :obj:`snap_plugin.v1.Metric`):
List of metrics to be collected.
Returns:
:obj:`list` of :obj:`snap_plugin.v1.Metric`:
List of collected metrics.
"""
if len(metrics) > 0:
with open(config["file"], 'a') as outfile:
for metric in metrics:
outfile.write(
json_format.MessageToJson(
metric._pb, including_default_value_fields=True)) | [
"def",
"publish",
"(",
"self",
",",
"metrics",
",",
"config",
")",
":",
"if",
"len",
"(",
"metrics",
")",
">",
"0",
":",
"with",
"open",
"(",
"config",
"[",
"\"file\"",
"]",
",",
"'a'",
")",
"as",
"outfile",
":",
"for",
"metric",
"in",
"metrics",
":",
"outfile",
".",
"write",
"(",
"json_format",
".",
"MessageToJson",
"(",
"metric",
".",
"_pb",
",",
"including_default_value_fields",
"=",
"True",
")",
")"
] | Publishes metrics to a file in JSON format.
This method is called by the Snap deamon during the collection phase
of the execution of a Snap workflow.
In this example we are writing the metrics to a file in json format.
We obtain the path to the file through the config (`ConfigMap`) arg.
Args:
metrics (obj:`list` of :obj:`snap_plugin.v1.Metric`):
List of metrics to be collected.
Returns:
:obj:`list` of :obj:`snap_plugin.v1.Metric`:
List of collected metrics. | [
"Publishes",
"metrics",
"to",
"a",
"file",
"in",
"JSON",
"format",
"."
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/examples/publisher/file.py#L37-L59 | train |
neithere/eav-django | eav/forms.py | BaseSchemaForm.clean_name | def clean_name(self):
"Avoid name clashes between static and dynamic attributes."
name = self.cleaned_data['name']
reserved_names = self._meta.model._meta.get_all_field_names()
if name not in reserved_names:
return name
raise ValidationError(_('Attribute name must not clash with reserved names'
' ("%s")') % '", "'.join(reserved_names)) | python | def clean_name(self):
"Avoid name clashes between static and dynamic attributes."
name = self.cleaned_data['name']
reserved_names = self._meta.model._meta.get_all_field_names()
if name not in reserved_names:
return name
raise ValidationError(_('Attribute name must not clash with reserved names'
' ("%s")') % '", "'.join(reserved_names)) | [
"def",
"clean_name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"cleaned_data",
"[",
"'name'",
"]",
"reserved_names",
"=",
"self",
".",
"_meta",
".",
"model",
".",
"_meta",
".",
"get_all_field_names",
"(",
")",
"if",
"name",
"not",
"in",
"reserved_names",
":",
"return",
"name",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Attribute name must not clash with reserved names'",
"' (\"%s\")'",
")",
"%",
"'\", \"'",
".",
"join",
"(",
"reserved_names",
")",
")"
] | Avoid name clashes between static and dynamic attributes. | [
"Avoid",
"name",
"clashes",
"between",
"static",
"and",
"dynamic",
"attributes",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/forms.py#L40-L47 | train |
neithere/eav-django | eav/forms.py | BaseDynamicEntityForm.save | def save(self, commit=True):
"""
Saves this ``form``'s cleaned_data into model instance ``self.instance``
and related EAV attributes.
Returns ``instance``.
"""
if self.errors:
raise ValueError("The %s could not be saved because the data didn't"
" validate." % self.instance._meta.object_name)
# create entity instance, don't save yet
instance = super(BaseDynamicEntityForm, self).save(commit=False)
# assign attributes
for name in instance.get_schema_names():
value = self.cleaned_data.get(name)
setattr(instance, name, value)
# save entity and its attributes
if commit:
instance.save()
return instance | python | def save(self, commit=True):
"""
Saves this ``form``'s cleaned_data into model instance ``self.instance``
and related EAV attributes.
Returns ``instance``.
"""
if self.errors:
raise ValueError("The %s could not be saved because the data didn't"
" validate." % self.instance._meta.object_name)
# create entity instance, don't save yet
instance = super(BaseDynamicEntityForm, self).save(commit=False)
# assign attributes
for name in instance.get_schema_names():
value = self.cleaned_data.get(name)
setattr(instance, name, value)
# save entity and its attributes
if commit:
instance.save()
return instance | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"if",
"self",
".",
"errors",
":",
"raise",
"ValueError",
"(",
"\"The %s could not be saved because the data didn't\"",
"\" validate.\"",
"%",
"self",
".",
"instance",
".",
"_meta",
".",
"object_name",
")",
"# create entity instance, don't save yet",
"instance",
"=",
"super",
"(",
"BaseDynamicEntityForm",
",",
"self",
")",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"# assign attributes",
"for",
"name",
"in",
"instance",
".",
"get_schema_names",
"(",
")",
":",
"value",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"name",
")",
"setattr",
"(",
"instance",
",",
"name",
",",
"value",
")",
"# save entity and its attributes",
"if",
"commit",
":",
"instance",
".",
"save",
"(",
")",
"return",
"instance"
] | Saves this ``form``'s cleaned_data into model instance ``self.instance``
and related EAV attributes.
Returns ``instance``. | [
"Saves",
"this",
"form",
"s",
"cleaned_data",
"into",
"model",
"instance",
"self",
".",
"instance",
"and",
"related",
"EAV",
"attributes",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/forms.py#L122-L146 | train |
bitesofcode/projexui | projexui/completers/xorbsearchcompleter.py | XOrbSearchCompleter.refresh | def refresh(self):
"""
Refreshes the contents of the completer based on the current text.
"""
table = self.tableType()
search = nativestring(self._pywidget.text())
if search == self._lastSearch:
return
self._lastSearch = search
if not search:
return
if search in self._cache:
records = self._cache[search]
else:
records = table.select(where = self.baseQuery(),
order = self.order())
records = list(records.search(search, limit=self.limit()))
self._cache[search] = records
self._records = records
self.model().setStringList(map(str, self._records))
self.complete() | python | def refresh(self):
"""
Refreshes the contents of the completer based on the current text.
"""
table = self.tableType()
search = nativestring(self._pywidget.text())
if search == self._lastSearch:
return
self._lastSearch = search
if not search:
return
if search in self._cache:
records = self._cache[search]
else:
records = table.select(where = self.baseQuery(),
order = self.order())
records = list(records.search(search, limit=self.limit()))
self._cache[search] = records
self._records = records
self.model().setStringList(map(str, self._records))
self.complete() | [
"def",
"refresh",
"(",
"self",
")",
":",
"table",
"=",
"self",
".",
"tableType",
"(",
")",
"search",
"=",
"nativestring",
"(",
"self",
".",
"_pywidget",
".",
"text",
"(",
")",
")",
"if",
"search",
"==",
"self",
".",
"_lastSearch",
":",
"return",
"self",
".",
"_lastSearch",
"=",
"search",
"if",
"not",
"search",
":",
"return",
"if",
"search",
"in",
"self",
".",
"_cache",
":",
"records",
"=",
"self",
".",
"_cache",
"[",
"search",
"]",
"else",
":",
"records",
"=",
"table",
".",
"select",
"(",
"where",
"=",
"self",
".",
"baseQuery",
"(",
")",
",",
"order",
"=",
"self",
".",
"order",
"(",
")",
")",
"records",
"=",
"list",
"(",
"records",
".",
"search",
"(",
"search",
",",
"limit",
"=",
"self",
".",
"limit",
"(",
")",
")",
")",
"self",
".",
"_cache",
"[",
"search",
"]",
"=",
"records",
"self",
".",
"_records",
"=",
"records",
"self",
".",
"model",
"(",
")",
".",
"setStringList",
"(",
"map",
"(",
"str",
",",
"self",
".",
"_records",
")",
")",
"self",
".",
"complete",
"(",
")"
] | Refreshes the contents of the completer based on the current text. | [
"Refreshes",
"the",
"contents",
"of",
"the",
"completer",
"based",
"on",
"the",
"current",
"text",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/completers/xorbsearchcompleter.py#L130-L153 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xview.py | XView.initialize | def initialize(self, force=False):
"""
Initializes the view if it is visible or being loaded.
"""
if force or (self.isVisible() and \
not self.isInitialized() and \
not self.signalsBlocked()):
self._initialized = True
self.initialized.emit() | python | def initialize(self, force=False):
"""
Initializes the view if it is visible or being loaded.
"""
if force or (self.isVisible() and \
not self.isInitialized() and \
not self.signalsBlocked()):
self._initialized = True
self.initialized.emit() | [
"def",
"initialize",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
"or",
"(",
"self",
".",
"isVisible",
"(",
")",
"and",
"not",
"self",
".",
"isInitialized",
"(",
")",
"and",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"self",
".",
"_initialized",
"=",
"True",
"self",
".",
"initialized",
".",
"emit",
"(",
")"
] | Initializes the view if it is visible or being loaded. | [
"Initializes",
"the",
"view",
"if",
"it",
"is",
"visible",
"or",
"being",
"loaded",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xview.py#L321-L330 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xview.py | XView.destroySingleton | def destroySingleton(cls):
"""
Destroys the singleton instance of this class, if one exists.
"""
singleton_key = '_{0}__singleton'.format(cls.__name__)
singleton = getattr(cls, singleton_key, None)
if singleton is not None:
setattr(cls, singleton_key, None)
singleton.close()
singleton.deleteLater() | python | def destroySingleton(cls):
"""
Destroys the singleton instance of this class, if one exists.
"""
singleton_key = '_{0}__singleton'.format(cls.__name__)
singleton = getattr(cls, singleton_key, None)
if singleton is not None:
setattr(cls, singleton_key, None)
singleton.close()
singleton.deleteLater() | [
"def",
"destroySingleton",
"(",
"cls",
")",
":",
"singleton_key",
"=",
"'_{0}__singleton'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
"singleton",
"=",
"getattr",
"(",
"cls",
",",
"singleton_key",
",",
"None",
")",
"if",
"singleton",
"is",
"not",
"None",
":",
"setattr",
"(",
"cls",
",",
"singleton_key",
",",
"None",
")",
"singleton",
".",
"close",
"(",
")",
"singleton",
".",
"deleteLater",
"(",
")"
] | Destroys the singleton instance of this class, if one exists. | [
"Destroys",
"the",
"singleton",
"instance",
"of",
"this",
"class",
"if",
"one",
"exists",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xview.py#L739-L750 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.adjustSize | def adjustSize(self):
"""
Adjusts the size of this widget as the parent resizes.
"""
# adjust the close button
align = self.closeAlignment()
if align & QtCore.Qt.AlignTop:
y = 6
else:
y = self.height() - 38
if align & QtCore.Qt.AlignLeft:
x = 6
else:
x = self.width() - 38
self._closeButton.move(x, y)
# adjust the central widget
widget = self.centralWidget()
if widget is not None:
center = self.rect().center()
widget.move(center.x() - widget.width() / 2, center.y() - widget.height() / 2) | python | def adjustSize(self):
"""
Adjusts the size of this widget as the parent resizes.
"""
# adjust the close button
align = self.closeAlignment()
if align & QtCore.Qt.AlignTop:
y = 6
else:
y = self.height() - 38
if align & QtCore.Qt.AlignLeft:
x = 6
else:
x = self.width() - 38
self._closeButton.move(x, y)
# adjust the central widget
widget = self.centralWidget()
if widget is not None:
center = self.rect().center()
widget.move(center.x() - widget.width() / 2, center.y() - widget.height() / 2) | [
"def",
"adjustSize",
"(",
"self",
")",
":",
"# adjust the close button",
"align",
"=",
"self",
".",
"closeAlignment",
"(",
")",
"if",
"align",
"&",
"QtCore",
".",
"Qt",
".",
"AlignTop",
":",
"y",
"=",
"6",
"else",
":",
"y",
"=",
"self",
".",
"height",
"(",
")",
"-",
"38",
"if",
"align",
"&",
"QtCore",
".",
"Qt",
".",
"AlignLeft",
":",
"x",
"=",
"6",
"else",
":",
"x",
"=",
"self",
".",
"width",
"(",
")",
"-",
"38",
"self",
".",
"_closeButton",
".",
"move",
"(",
"x",
",",
"y",
")",
"# adjust the central widget",
"widget",
"=",
"self",
".",
"centralWidget",
"(",
")",
"if",
"widget",
"is",
"not",
"None",
":",
"center",
"=",
"self",
".",
"rect",
"(",
")",
".",
"center",
"(",
")",
"widget",
".",
"move",
"(",
"center",
".",
"x",
"(",
")",
"-",
"widget",
".",
"width",
"(",
")",
"/",
"2",
",",
"center",
".",
"y",
"(",
")",
"-",
"widget",
".",
"height",
"(",
")",
"/",
"2",
")"
] | Adjusts the size of this widget as the parent resizes. | [
"Adjusts",
"the",
"size",
"of",
"this",
"widget",
"as",
"the",
"parent",
"resizes",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L48-L70 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.keyPressEvent | def keyPressEvent(self, event):
"""
Exits the modal window on an escape press.
:param event | <QtCore.QKeyPressEvent>
"""
if event.key() == QtCore.Qt.Key_Escape:
self.reject()
super(XOverlayWidget, self).keyPressEvent(event) | python | def keyPressEvent(self, event):
"""
Exits the modal window on an escape press.
:param event | <QtCore.QKeyPressEvent>
"""
if event.key() == QtCore.Qt.Key_Escape:
self.reject()
super(XOverlayWidget, self).keyPressEvent(event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Escape",
":",
"self",
".",
"reject",
"(",
")",
"super",
"(",
"XOverlayWidget",
",",
"self",
")",
".",
"keyPressEvent",
"(",
"event",
")"
] | Exits the modal window on an escape press.
:param event | <QtCore.QKeyPressEvent> | [
"Exits",
"the",
"modal",
"window",
"on",
"an",
"escape",
"press",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L97-L106 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.eventFilter | def eventFilter(self, object, event):
"""
Resizes this overlay as the widget resizes.
:param object | <QtCore.QObject>
event | <QtCore.QEvent>
:return <bool>
"""
if object == self.parent() and event.type() == QtCore.QEvent.Resize:
self.resize(event.size())
elif event.type() == QtCore.QEvent.Close:
self.setResult(0)
return False | python | def eventFilter(self, object, event):
"""
Resizes this overlay as the widget resizes.
:param object | <QtCore.QObject>
event | <QtCore.QEvent>
:return <bool>
"""
if object == self.parent() and event.type() == QtCore.QEvent.Resize:
self.resize(event.size())
elif event.type() == QtCore.QEvent.Close:
self.setResult(0)
return False | [
"def",
"eventFilter",
"(",
"self",
",",
"object",
",",
"event",
")",
":",
"if",
"object",
"==",
"self",
".",
"parent",
"(",
")",
"and",
"event",
".",
"type",
"(",
")",
"==",
"QtCore",
".",
"QEvent",
".",
"Resize",
":",
"self",
".",
"resize",
"(",
"event",
".",
"size",
"(",
")",
")",
"elif",
"event",
".",
"type",
"(",
")",
"==",
"QtCore",
".",
"QEvent",
".",
"Close",
":",
"self",
".",
"setResult",
"(",
"0",
")",
"return",
"False"
] | Resizes this overlay as the widget resizes.
:param object | <QtCore.QObject>
event | <QtCore.QEvent>
:return <bool> | [
"Resizes",
"this",
"overlay",
"as",
"the",
"widget",
"resizes",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L108-L121 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.resizeEvent | def resizeEvent(self, event):
"""
Handles a resize event for this overlay, centering the central widget if
one is found.
:param event | <QtCore.QEvent>
"""
super(XOverlayWidget, self).resizeEvent(event)
self.adjustSize() | python | def resizeEvent(self, event):
"""
Handles a resize event for this overlay, centering the central widget if
one is found.
:param event | <QtCore.QEvent>
"""
super(XOverlayWidget, self).resizeEvent(event)
self.adjustSize() | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XOverlayWidget",
",",
"self",
")",
".",
"resizeEvent",
"(",
"event",
")",
"self",
".",
"adjustSize",
"(",
")"
] | Handles a resize event for this overlay, centering the central widget if
one is found.
:param event | <QtCore.QEvent> | [
"Handles",
"a",
"resize",
"event",
"for",
"this",
"overlay",
"centering",
"the",
"central",
"widget",
"if",
"one",
"is",
"found",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L153-L161 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.setCentralWidget | def setCentralWidget(self, widget):
"""
Sets the central widget for this overlay to the inputed widget.
:param widget | <QtGui.QWidget>
"""
self._centralWidget = widget
if widget is not None:
widget.setParent(self)
widget.installEventFilter(self)
# create the drop shadow effect
effect = QtGui.QGraphicsDropShadowEffect(self)
effect.setColor(QtGui.QColor('black'))
effect.setBlurRadius(80)
effect.setOffset(0, 0)
widget.setGraphicsEffect(effect) | python | def setCentralWidget(self, widget):
"""
Sets the central widget for this overlay to the inputed widget.
:param widget | <QtGui.QWidget>
"""
self._centralWidget = widget
if widget is not None:
widget.setParent(self)
widget.installEventFilter(self)
# create the drop shadow effect
effect = QtGui.QGraphicsDropShadowEffect(self)
effect.setColor(QtGui.QColor('black'))
effect.setBlurRadius(80)
effect.setOffset(0, 0)
widget.setGraphicsEffect(effect) | [
"def",
"setCentralWidget",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"_centralWidget",
"=",
"widget",
"if",
"widget",
"is",
"not",
"None",
":",
"widget",
".",
"setParent",
"(",
"self",
")",
"widget",
".",
"installEventFilter",
"(",
"self",
")",
"# create the drop shadow effect",
"effect",
"=",
"QtGui",
".",
"QGraphicsDropShadowEffect",
"(",
"self",
")",
"effect",
".",
"setColor",
"(",
"QtGui",
".",
"QColor",
"(",
"'black'",
")",
")",
"effect",
".",
"setBlurRadius",
"(",
"80",
")",
"effect",
".",
"setOffset",
"(",
"0",
",",
"0",
")",
"widget",
".",
"setGraphicsEffect",
"(",
"effect",
")"
] | Sets the central widget for this overlay to the inputed widget.
:param widget | <QtGui.QWidget> | [
"Sets",
"the",
"central",
"widget",
"for",
"this",
"overlay",
"to",
"the",
"inputed",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L163-L181 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.setClosable | def setClosable(self, state):
"""
Sets whether or not the user should be able to close this overlay widget.
:param state | <bool>
"""
self._closable = state
if state:
self._closeButton.show()
else:
self._closeButton.hide() | python | def setClosable(self, state):
"""
Sets whether or not the user should be able to close this overlay widget.
:param state | <bool>
"""
self._closable = state
if state:
self._closeButton.show()
else:
self._closeButton.hide() | [
"def",
"setClosable",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_closable",
"=",
"state",
"if",
"state",
":",
"self",
".",
"_closeButton",
".",
"show",
"(",
")",
"else",
":",
"self",
".",
"_closeButton",
".",
"hide",
"(",
")"
] | Sets whether or not the user should be able to close this overlay widget.
:param state | <bool> | [
"Sets",
"whether",
"or",
"not",
"the",
"user",
"should",
"be",
"able",
"to",
"close",
"this",
"overlay",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L183-L193 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.setVisible | def setVisible(self, state):
"""
Closes this widget and kills the result.
"""
super(XOverlayWidget, self).setVisible(state)
if not state:
self.setResult(0) | python | def setVisible(self, state):
"""
Closes this widget and kills the result.
"""
super(XOverlayWidget, self).setVisible(state)
if not state:
self.setResult(0) | [
"def",
"setVisible",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"XOverlayWidget",
",",
"self",
")",
".",
"setVisible",
"(",
"state",
")",
"if",
"not",
"state",
":",
"self",
".",
"setResult",
"(",
"0",
")"
] | Closes this widget and kills the result. | [
"Closes",
"this",
"widget",
"and",
"kills",
"the",
"result",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L211-L218 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.showEvent | def showEvent(self, event):
"""
Ensures this widget is the top-most widget for its parent.
:param event | <QtCore.QEvent>
"""
super(XOverlayWidget, self).showEvent(event)
# raise to the top
self.raise_()
self._closeButton.setVisible(self.isClosable())
widget = self.centralWidget()
if widget:
center = self.rect().center()
start_x = end_x = center.x() - widget.width() / 2
start_y = -widget.height()
end_y = center.y() - widget.height() / 2
start = QtCore.QPoint(start_x, start_y)
end = QtCore.QPoint(end_x, end_y)
# create the movement animation
anim = QtCore.QPropertyAnimation(self)
anim.setPropertyName('pos')
anim.setTargetObject(widget)
anim.setStartValue(start)
anim.setEndValue(end)
anim.setDuration(500)
anim.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
anim.finished.connect(anim.deleteLater)
anim.start() | python | def showEvent(self, event):
"""
Ensures this widget is the top-most widget for its parent.
:param event | <QtCore.QEvent>
"""
super(XOverlayWidget, self).showEvent(event)
# raise to the top
self.raise_()
self._closeButton.setVisible(self.isClosable())
widget = self.centralWidget()
if widget:
center = self.rect().center()
start_x = end_x = center.x() - widget.width() / 2
start_y = -widget.height()
end_y = center.y() - widget.height() / 2
start = QtCore.QPoint(start_x, start_y)
end = QtCore.QPoint(end_x, end_y)
# create the movement animation
anim = QtCore.QPropertyAnimation(self)
anim.setPropertyName('pos')
anim.setTargetObject(widget)
anim.setStartValue(start)
anim.setEndValue(end)
anim.setDuration(500)
anim.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
anim.finished.connect(anim.deleteLater)
anim.start() | [
"def",
"showEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XOverlayWidget",
",",
"self",
")",
".",
"showEvent",
"(",
"event",
")",
"# raise to the top",
"self",
".",
"raise_",
"(",
")",
"self",
".",
"_closeButton",
".",
"setVisible",
"(",
"self",
".",
"isClosable",
"(",
")",
")",
"widget",
"=",
"self",
".",
"centralWidget",
"(",
")",
"if",
"widget",
":",
"center",
"=",
"self",
".",
"rect",
"(",
")",
".",
"center",
"(",
")",
"start_x",
"=",
"end_x",
"=",
"center",
".",
"x",
"(",
")",
"-",
"widget",
".",
"width",
"(",
")",
"/",
"2",
"start_y",
"=",
"-",
"widget",
".",
"height",
"(",
")",
"end_y",
"=",
"center",
".",
"y",
"(",
")",
"-",
"widget",
".",
"height",
"(",
")",
"/",
"2",
"start",
"=",
"QtCore",
".",
"QPoint",
"(",
"start_x",
",",
"start_y",
")",
"end",
"=",
"QtCore",
".",
"QPoint",
"(",
"end_x",
",",
"end_y",
")",
"# create the movement animation",
"anim",
"=",
"QtCore",
".",
"QPropertyAnimation",
"(",
"self",
")",
"anim",
".",
"setPropertyName",
"(",
"'pos'",
")",
"anim",
".",
"setTargetObject",
"(",
"widget",
")",
"anim",
".",
"setStartValue",
"(",
"start",
")",
"anim",
".",
"setEndValue",
"(",
"end",
")",
"anim",
".",
"setDuration",
"(",
"500",
")",
"anim",
".",
"setEasingCurve",
"(",
"QtCore",
".",
"QEasingCurve",
".",
"InOutQuad",
")",
"anim",
".",
"finished",
".",
"connect",
"(",
"anim",
".",
"deleteLater",
")",
"anim",
".",
"start",
"(",
")"
] | Ensures this widget is the top-most widget for its parent.
:param event | <QtCore.QEvent> | [
"Ensures",
"this",
"widget",
"is",
"the",
"top",
"-",
"most",
"widget",
"for",
"its",
"parent",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L220-L251 | train |
bitesofcode/projexui | projexui/widgets/xoverlaywidget.py | XOverlayWidget.modal | def modal(widget, parent=None, align=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight, blurred=True):
"""
Creates a modal dialog for this overlay with the inputed widget. If the user
accepts the widget, then 1 will be returned, otherwise, 0 will be returned.
:param widget | <QtCore.QWidget>
"""
if parent is None:
parent = QtGui.QApplication.instance().activeWindow()
overlay = XOverlayWidget(parent)
overlay.setAttribute(QtCore.Qt.WA_DeleteOnClose)
overlay.setCentralWidget(widget)
overlay.setCloseAlignment(align)
overlay.show()
return overlay | python | def modal(widget, parent=None, align=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight, blurred=True):
"""
Creates a modal dialog for this overlay with the inputed widget. If the user
accepts the widget, then 1 will be returned, otherwise, 0 will be returned.
:param widget | <QtCore.QWidget>
"""
if parent is None:
parent = QtGui.QApplication.instance().activeWindow()
overlay = XOverlayWidget(parent)
overlay.setAttribute(QtCore.Qt.WA_DeleteOnClose)
overlay.setCentralWidget(widget)
overlay.setCloseAlignment(align)
overlay.show()
return overlay | [
"def",
"modal",
"(",
"widget",
",",
"parent",
"=",
"None",
",",
"align",
"=",
"QtCore",
".",
"Qt",
".",
"AlignTop",
"|",
"QtCore",
".",
"Qt",
".",
"AlignRight",
",",
"blurred",
"=",
"True",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"QtGui",
".",
"QApplication",
".",
"instance",
"(",
")",
".",
"activeWindow",
"(",
")",
"overlay",
"=",
"XOverlayWidget",
"(",
"parent",
")",
"overlay",
".",
"setAttribute",
"(",
"QtCore",
".",
"Qt",
".",
"WA_DeleteOnClose",
")",
"overlay",
".",
"setCentralWidget",
"(",
"widget",
")",
"overlay",
".",
"setCloseAlignment",
"(",
"align",
")",
"overlay",
".",
"show",
"(",
")",
"return",
"overlay"
] | Creates a modal dialog for this overlay with the inputed widget. If the user
accepts the widget, then 1 will be returned, otherwise, 0 will be returned.
:param widget | <QtCore.QWidget> | [
"Creates",
"a",
"modal",
"dialog",
"for",
"this",
"overlay",
"with",
"the",
"inputed",
"widget",
".",
"If",
"the",
"user",
"accepts",
"the",
"widget",
"then",
"1",
"will",
"be",
"returned",
"otherwise",
"0",
"will",
"be",
"returned",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L254-L269 | train |
bitesofcode/projexui | projexui/widgets/xconsoleedit.py | XConsoleEdit.applyCommand | def applyCommand(self):
"""
Applies the current line of code as an interactive python command.
"""
# generate the command information
cursor = self.textCursor()
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
at_end = cursor.atEnd()
modifiers = QApplication.instance().keyboardModifiers()
mod_mode = at_end or modifiers == Qt.ShiftModifier
# test the line for information
if mod_mode and line.endswith(':'):
cursor.movePosition(cursor.EndOfLine)
line = re.sub('^>>> ', '', line)
line = re.sub('^\.\.\. ', '', line)
count = len(line) - len(line.lstrip()) + 4
self.insertPlainText('\n... ' + count * ' ')
return False
elif mod_mode and line.startswith('...') and \
(line.strip() != '...' or not at_end):
cursor.movePosition(cursor.EndOfLine)
line = re.sub('^\.\.\. ', '', line)
count = len(line) - len(line.lstrip())
self.insertPlainText('\n... ' + count * ' ')
return False
# if we're not at the end of the console, then add it to the end
elif line.startswith('>>>') or line.startswith('...'):
# move to the top of the command structure
line = projex.text.nativestring(cursor.block().text())
while line.startswith('...'):
cursor.movePosition(cursor.PreviousBlock)
line = projex.text.nativestring(cursor.block().text())
# calculate the command
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
ended = False
lines = []
while True:
# add the new block
lines.append(line)
if cursor.atEnd():
ended = True
break
# move to the next line
cursor.movePosition(cursor.NextBlock)
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
# check for a new command or the end of the command
if not line.startswith('...'):
break
command = '\n'.join(lines)
# if we did not end up at the end of the command block, then
# copy it for modification
if not (ended and command):
self.waitForInput()
self.insertPlainText(command.replace('>>> ', ''))
cursor.movePosition(cursor.End)
return False
else:
self.waitForInput()
return False
self.executeCommand(command)
return True | python | def applyCommand(self):
"""
Applies the current line of code as an interactive python command.
"""
# generate the command information
cursor = self.textCursor()
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
at_end = cursor.atEnd()
modifiers = QApplication.instance().keyboardModifiers()
mod_mode = at_end or modifiers == Qt.ShiftModifier
# test the line for information
if mod_mode and line.endswith(':'):
cursor.movePosition(cursor.EndOfLine)
line = re.sub('^>>> ', '', line)
line = re.sub('^\.\.\. ', '', line)
count = len(line) - len(line.lstrip()) + 4
self.insertPlainText('\n... ' + count * ' ')
return False
elif mod_mode and line.startswith('...') and \
(line.strip() != '...' or not at_end):
cursor.movePosition(cursor.EndOfLine)
line = re.sub('^\.\.\. ', '', line)
count = len(line) - len(line.lstrip())
self.insertPlainText('\n... ' + count * ' ')
return False
# if we're not at the end of the console, then add it to the end
elif line.startswith('>>>') or line.startswith('...'):
# move to the top of the command structure
line = projex.text.nativestring(cursor.block().text())
while line.startswith('...'):
cursor.movePosition(cursor.PreviousBlock)
line = projex.text.nativestring(cursor.block().text())
# calculate the command
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
ended = False
lines = []
while True:
# add the new block
lines.append(line)
if cursor.atEnd():
ended = True
break
# move to the next line
cursor.movePosition(cursor.NextBlock)
cursor.movePosition(cursor.EndOfLine)
line = projex.text.nativestring(cursor.block().text())
# check for a new command or the end of the command
if not line.startswith('...'):
break
command = '\n'.join(lines)
# if we did not end up at the end of the command block, then
# copy it for modification
if not (ended and command):
self.waitForInput()
self.insertPlainText(command.replace('>>> ', ''))
cursor.movePosition(cursor.End)
return False
else:
self.waitForInput()
return False
self.executeCommand(command)
return True | [
"def",
"applyCommand",
"(",
"self",
")",
":",
"# generate the command information\r",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"line",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"at_end",
"=",
"cursor",
".",
"atEnd",
"(",
")",
"modifiers",
"=",
"QApplication",
".",
"instance",
"(",
")",
".",
"keyboardModifiers",
"(",
")",
"mod_mode",
"=",
"at_end",
"or",
"modifiers",
"==",
"Qt",
".",
"ShiftModifier",
"# test the line for information\r",
"if",
"mod_mode",
"and",
"line",
".",
"endswith",
"(",
"':'",
")",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"'^>>> '",
",",
"''",
",",
"line",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"'^\\.\\.\\. '",
",",
"''",
",",
"line",
")",
"count",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"+",
"4",
"self",
".",
"insertPlainText",
"(",
"'\\n... '",
"+",
"count",
"*",
"' '",
")",
"return",
"False",
"elif",
"mod_mode",
"and",
"line",
".",
"startswith",
"(",
"'...'",
")",
"and",
"(",
"line",
".",
"strip",
"(",
")",
"!=",
"'...'",
"or",
"not",
"at_end",
")",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"line",
"=",
"re",
".",
"sub",
"(",
"'^\\.\\.\\. '",
",",
"''",
",",
"line",
")",
"count",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"self",
".",
"insertPlainText",
"(",
"'\\n... '",
"+",
"count",
"*",
"' '",
")",
"return",
"False",
"# if we're not at the end of the console, then add it to the end\r",
"elif",
"line",
".",
"startswith",
"(",
"'>>>'",
")",
"or",
"line",
".",
"startswith",
"(",
"'...'",
")",
":",
"# move to the top of the command structure\r",
"line",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"while",
"line",
".",
"startswith",
"(",
"'...'",
")",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"PreviousBlock",
")",
"line",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"# calculate the command\r",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"line",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"ended",
"=",
"False",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"# add the new block\r",
"lines",
".",
"append",
"(",
"line",
")",
"if",
"cursor",
".",
"atEnd",
"(",
")",
":",
"ended",
"=",
"True",
"break",
"# move to the next line\r",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"NextBlock",
")",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"line",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"# check for a new command or the end of the command\r",
"if",
"not",
"line",
".",
"startswith",
"(",
"'...'",
")",
":",
"break",
"command",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"# if we did not end up at the end of the command block, then\r",
"# copy it for modification\r",
"if",
"not",
"(",
"ended",
"and",
"command",
")",
":",
"self",
".",
"waitForInput",
"(",
")",
"self",
".",
"insertPlainText",
"(",
"command",
".",
"replace",
"(",
"'>>> '",
",",
"''",
")",
")",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"End",
")",
"return",
"False",
"else",
":",
"self",
".",
"waitForInput",
"(",
")",
"return",
"False",
"self",
".",
"executeCommand",
"(",
"command",
")",
"return",
"True"
] | Applies the current line of code as an interactive python command. | [
"Applies",
"the",
"current",
"line",
"of",
"code",
"as",
"an",
"interactive",
"python",
"command",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xconsoleedit.py#L198-L277 | train |
bitesofcode/projexui | projexui/widgets/xconsoleedit.py | XConsoleEdit.gotoHome | def gotoHome(self):
"""
Navigates to the home position for the edit.
"""
mode = QTextCursor.MoveAnchor
# select the home
if QApplication.instance().keyboardModifiers() == Qt.ShiftModifier:
mode = QTextCursor.KeepAnchor
cursor = self.textCursor()
block = projex.text.nativestring(cursor.block().text())
cursor.movePosition( QTextCursor.StartOfBlock, mode )
if block.startswith('>>> '):
cursor.movePosition(QTextCursor.Right, mode, 4)
elif block.startswith('... '):
match = re.match('...\s*', block)
cursor.movePosition(QTextCursor.Right, mode, match.end())
self.setTextCursor(cursor) | python | def gotoHome(self):
"""
Navigates to the home position for the edit.
"""
mode = QTextCursor.MoveAnchor
# select the home
if QApplication.instance().keyboardModifiers() == Qt.ShiftModifier:
mode = QTextCursor.KeepAnchor
cursor = self.textCursor()
block = projex.text.nativestring(cursor.block().text())
cursor.movePosition( QTextCursor.StartOfBlock, mode )
if block.startswith('>>> '):
cursor.movePosition(QTextCursor.Right, mode, 4)
elif block.startswith('... '):
match = re.match('...\s*', block)
cursor.movePosition(QTextCursor.Right, mode, match.end())
self.setTextCursor(cursor) | [
"def",
"gotoHome",
"(",
"self",
")",
":",
"mode",
"=",
"QTextCursor",
".",
"MoveAnchor",
"# select the home\r",
"if",
"QApplication",
".",
"instance",
"(",
")",
".",
"keyboardModifiers",
"(",
")",
"==",
"Qt",
".",
"ShiftModifier",
":",
"mode",
"=",
"QTextCursor",
".",
"KeepAnchor",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"block",
"=",
"projex",
".",
"text",
".",
"nativestring",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"StartOfBlock",
",",
"mode",
")",
"if",
"block",
".",
"startswith",
"(",
"'>>> '",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"Right",
",",
"mode",
",",
"4",
")",
"elif",
"block",
".",
"startswith",
"(",
"'... '",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'...\\s*'",
",",
"block",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"Right",
",",
"mode",
",",
"match",
".",
"end",
"(",
")",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")"
] | Navigates to the home position for the edit. | [
"Navigates",
"to",
"the",
"home",
"position",
"for",
"the",
"edit",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xconsoleedit.py#L452-L472 | train |
bitesofcode/projexui | projexui/widgets/xconsoleedit.py | XConsoleEdit.waitForInput | def waitForInput(self):
"""
Inserts a new input command into the console editor.
"""
self._waitingForInput = False
try:
if self.isDestroyed() or self.isReadOnly():
return
except RuntimeError:
return
self.moveCursor(QTextCursor.End)
if self.textCursor().block().text() == '>>> ':
return
# if there is already text on the line, then start a new line
newln = '>>> '
if projex.text.nativestring(self.textCursor().block().text()):
newln = '\n' + newln
# insert the text
self.setCurrentMode('standard')
self.insertPlainText(newln)
self.scrollToEnd()
self._blankCache = '' | python | def waitForInput(self):
"""
Inserts a new input command into the console editor.
"""
self._waitingForInput = False
try:
if self.isDestroyed() or self.isReadOnly():
return
except RuntimeError:
return
self.moveCursor(QTextCursor.End)
if self.textCursor().block().text() == '>>> ':
return
# if there is already text on the line, then start a new line
newln = '>>> '
if projex.text.nativestring(self.textCursor().block().text()):
newln = '\n' + newln
# insert the text
self.setCurrentMode('standard')
self.insertPlainText(newln)
self.scrollToEnd()
self._blankCache = '' | [
"def",
"waitForInput",
"(",
"self",
")",
":",
"self",
".",
"_waitingForInput",
"=",
"False",
"try",
":",
"if",
"self",
".",
"isDestroyed",
"(",
")",
"or",
"self",
".",
"isReadOnly",
"(",
")",
":",
"return",
"except",
"RuntimeError",
":",
"return",
"self",
".",
"moveCursor",
"(",
"QTextCursor",
".",
"End",
")",
"if",
"self",
".",
"textCursor",
"(",
")",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
"==",
"'>>> '",
":",
"return",
"# if there is already text on the line, then start a new line\r",
"newln",
"=",
"'>>> '",
"if",
"projex",
".",
"text",
".",
"nativestring",
"(",
"self",
".",
"textCursor",
"(",
")",
".",
"block",
"(",
")",
".",
"text",
"(",
")",
")",
":",
"newln",
"=",
"'\\n'",
"+",
"newln",
"# insert the text\r",
"self",
".",
"setCurrentMode",
"(",
"'standard'",
")",
"self",
".",
"insertPlainText",
"(",
"newln",
")",
"self",
".",
"scrollToEnd",
"(",
")",
"self",
".",
"_blankCache",
"=",
"''"
] | Inserts a new input command into the console editor. | [
"Inserts",
"a",
"new",
"input",
"command",
"into",
"the",
"console",
"editor",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xconsoleedit.py#L771-L797 | train |
bitesofcode/projexui | projexui/dialogs/xconfigdialog/xconfigdialog.py | XConfigDialog.accept | def accept( self ):
"""
Saves all the current widgets and closes down.
"""
for i in range(self.uiConfigSTACK.count()):
widget = self.uiConfigSTACK.widget(i)
if ( not widget ):
continue
if ( not widget.save() ):
self.uiConfigSTACK.setCurrentWidget(widget)
return False
# close all the widgets in the stack
for i in range(self.uiConfigSTACK.count()):
widget = self.uiConfigSTACK.widget(i)
if ( not widget ):
continue
widget.close()
if ( self == XConfigDialog._instance ):
XConfigDialog._instance = None
super(XConfigDialog, self).accept() | python | def accept( self ):
"""
Saves all the current widgets and closes down.
"""
for i in range(self.uiConfigSTACK.count()):
widget = self.uiConfigSTACK.widget(i)
if ( not widget ):
continue
if ( not widget.save() ):
self.uiConfigSTACK.setCurrentWidget(widget)
return False
# close all the widgets in the stack
for i in range(self.uiConfigSTACK.count()):
widget = self.uiConfigSTACK.widget(i)
if ( not widget ):
continue
widget.close()
if ( self == XConfigDialog._instance ):
XConfigDialog._instance = None
super(XConfigDialog, self).accept() | [
"def",
"accept",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"uiConfigSTACK",
".",
"count",
"(",
")",
")",
":",
"widget",
"=",
"self",
".",
"uiConfigSTACK",
".",
"widget",
"(",
"i",
")",
"if",
"(",
"not",
"widget",
")",
":",
"continue",
"if",
"(",
"not",
"widget",
".",
"save",
"(",
")",
")",
":",
"self",
".",
"uiConfigSTACK",
".",
"setCurrentWidget",
"(",
"widget",
")",
"return",
"False",
"# close all the widgets in the stack",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"uiConfigSTACK",
".",
"count",
"(",
")",
")",
":",
"widget",
"=",
"self",
".",
"uiConfigSTACK",
".",
"widget",
"(",
"i",
")",
"if",
"(",
"not",
"widget",
")",
":",
"continue",
"widget",
".",
"close",
"(",
")",
"if",
"(",
"self",
"==",
"XConfigDialog",
".",
"_instance",
")",
":",
"XConfigDialog",
".",
"_instance",
"=",
"None",
"super",
"(",
"XConfigDialog",
",",
"self",
")",
".",
"accept",
"(",
")"
] | Saves all the current widgets and closes down. | [
"Saves",
"all",
"the",
"current",
"widgets",
"and",
"closes",
"down",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xconfigdialog/xconfigdialog.py#L71-L95 | train |
bitesofcode/projexui | projexui/dialogs/xconfigdialog/xconfigdialog.py | XConfigDialog.reject | def reject( self ):
"""
Overloads the reject method to clear up the instance variable.
"""
if ( self == XConfigDialog._instance ):
XConfigDialog._instance = None
super(XConfigDialog, self).reject() | python | def reject( self ):
"""
Overloads the reject method to clear up the instance variable.
"""
if ( self == XConfigDialog._instance ):
XConfigDialog._instance = None
super(XConfigDialog, self).reject() | [
"def",
"reject",
"(",
"self",
")",
":",
"if",
"(",
"self",
"==",
"XConfigDialog",
".",
"_instance",
")",
":",
"XConfigDialog",
".",
"_instance",
"=",
"None",
"super",
"(",
"XConfigDialog",
",",
"self",
")",
".",
"reject",
"(",
")"
] | Overloads the reject method to clear up the instance variable. | [
"Overloads",
"the",
"reject",
"method",
"to",
"clear",
"up",
"the",
"instance",
"variable",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xconfigdialog/xconfigdialog.py#L127-L134 | train |
bitesofcode/projexui | projexui/dialogs/xconfigdialog/xconfigdialog.py | XConfigDialog.showConfig | def showConfig( self ):
"""
Show the config widget for the currently selected plugin.
"""
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueName())
if ( not widget ):
widget = plugin.createWidget(self)
widget.setObjectName(plugin.uniqueName())
self.uiConfigSTACK.addWidget(widget)
self.uiConfigSTACK.setCurrentWidget(widget) | python | def showConfig( self ):
"""
Show the config widget for the currently selected plugin.
"""
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueName())
if ( not widget ):
widget = plugin.createWidget(self)
widget.setObjectName(plugin.uniqueName())
self.uiConfigSTACK.addWidget(widget)
self.uiConfigSTACK.setCurrentWidget(widget) | [
"def",
"showConfig",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiPluginTREE",
".",
"currentItem",
"(",
")",
"if",
"not",
"isinstance",
"(",
"item",
",",
"PluginItem",
")",
":",
"return",
"plugin",
"=",
"item",
".",
"plugin",
"(",
")",
"widget",
"=",
"self",
".",
"findChild",
"(",
"QWidget",
",",
"plugin",
".",
"uniqueName",
"(",
")",
")",
"if",
"(",
"not",
"widget",
")",
":",
"widget",
"=",
"plugin",
".",
"createWidget",
"(",
"self",
")",
"widget",
".",
"setObjectName",
"(",
"plugin",
".",
"uniqueName",
"(",
")",
")",
"self",
".",
"uiConfigSTACK",
".",
"addWidget",
"(",
"widget",
")",
"self",
".",
"uiConfigSTACK",
".",
"setCurrentWidget",
"(",
"widget",
")"
] | Show the config widget for the currently selected plugin. | [
"Show",
"the",
"config",
"widget",
"for",
"the",
"currently",
"selected",
"plugin",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xconfigdialog/xconfigdialog.py#L209-L225 | train |
talkincode/txradius | txradius/openvpn/client_kill.py | cli | def cli(server,port,client):
""" OpenVPN client_kill method
"""
tn = telnetlib.Telnet(host=server,port=port)
tn.write('kill %s\n'%client.encode('utf-8'))
tn.write('exit\n')
os._exit(0) | python | def cli(server,port,client):
""" OpenVPN client_kill method
"""
tn = telnetlib.Telnet(host=server,port=port)
tn.write('kill %s\n'%client.encode('utf-8'))
tn.write('exit\n')
os._exit(0) | [
"def",
"cli",
"(",
"server",
",",
"port",
",",
"client",
")",
":",
"tn",
"=",
"telnetlib",
".",
"Telnet",
"(",
"host",
"=",
"server",
",",
"port",
"=",
"port",
")",
"tn",
".",
"write",
"(",
"'kill %s\\n'",
"%",
"client",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"tn",
".",
"write",
"(",
"'exit\\n'",
")",
"os",
".",
"_exit",
"(",
"0",
")"
] | OpenVPN client_kill method | [
"OpenVPN",
"client_kill",
"method"
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/client_kill.py#L11-L17 | train |
bitesofcode/projexui | projexui/widgets/xtabwidget.py | XTabWidget.adjustButtons | def adjustButtons( self ):
"""
Updates the position of the buttons based on the current geometry.
"""
tabbar = self.tabBar()
tabbar.adjustSize()
w = self.width() - self._optionsButton.width() - 2
self._optionsButton.move(w, 0)
if self.count():
need_update = self._addButton.property('alone') != False
if need_update:
self._addButton.setProperty('alone', False)
self._addButton.move(tabbar.width(), 1)
self._addButton.setFixedHeight(tabbar.height())
else:
need_update = self._addButton.property('alone') != True
if need_update:
self._addButton.setProperty('alone', True)
self._addButton.move(tabbar.width() + 2, 1)
self._addButton.stackUnder(self.currentWidget())
# force refresh on the stylesheet (Qt limitation for updates)
if need_update:
app = QApplication.instance()
app.setStyleSheet(app.styleSheet()) | python | def adjustButtons( self ):
"""
Updates the position of the buttons based on the current geometry.
"""
tabbar = self.tabBar()
tabbar.adjustSize()
w = self.width() - self._optionsButton.width() - 2
self._optionsButton.move(w, 0)
if self.count():
need_update = self._addButton.property('alone') != False
if need_update:
self._addButton.setProperty('alone', False)
self._addButton.move(tabbar.width(), 1)
self._addButton.setFixedHeight(tabbar.height())
else:
need_update = self._addButton.property('alone') != True
if need_update:
self._addButton.setProperty('alone', True)
self._addButton.move(tabbar.width() + 2, 1)
self._addButton.stackUnder(self.currentWidget())
# force refresh on the stylesheet (Qt limitation for updates)
if need_update:
app = QApplication.instance()
app.setStyleSheet(app.styleSheet()) | [
"def",
"adjustButtons",
"(",
"self",
")",
":",
"tabbar",
"=",
"self",
".",
"tabBar",
"(",
")",
"tabbar",
".",
"adjustSize",
"(",
")",
"w",
"=",
"self",
".",
"width",
"(",
")",
"-",
"self",
".",
"_optionsButton",
".",
"width",
"(",
")",
"-",
"2",
"self",
".",
"_optionsButton",
".",
"move",
"(",
"w",
",",
"0",
")",
"if",
"self",
".",
"count",
"(",
")",
":",
"need_update",
"=",
"self",
".",
"_addButton",
".",
"property",
"(",
"'alone'",
")",
"!=",
"False",
"if",
"need_update",
":",
"self",
".",
"_addButton",
".",
"setProperty",
"(",
"'alone'",
",",
"False",
")",
"self",
".",
"_addButton",
".",
"move",
"(",
"tabbar",
".",
"width",
"(",
")",
",",
"1",
")",
"self",
".",
"_addButton",
".",
"setFixedHeight",
"(",
"tabbar",
".",
"height",
"(",
")",
")",
"else",
":",
"need_update",
"=",
"self",
".",
"_addButton",
".",
"property",
"(",
"'alone'",
")",
"!=",
"True",
"if",
"need_update",
":",
"self",
".",
"_addButton",
".",
"setProperty",
"(",
"'alone'",
",",
"True",
")",
"self",
".",
"_addButton",
".",
"move",
"(",
"tabbar",
".",
"width",
"(",
")",
"+",
"2",
",",
"1",
")",
"self",
".",
"_addButton",
".",
"stackUnder",
"(",
"self",
".",
"currentWidget",
"(",
")",
")",
"# force refresh on the stylesheet (Qt limitation for updates)\r",
"if",
"need_update",
":",
"app",
"=",
"QApplication",
".",
"instance",
"(",
")",
"app",
".",
"setStyleSheet",
"(",
"app",
".",
"styleSheet",
"(",
")",
")"
] | Updates the position of the buttons based on the current geometry. | [
"Updates",
"the",
"position",
"of",
"the",
"buttons",
"based",
"on",
"the",
"current",
"geometry",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtabwidget.py#L101-L131 | train |
viatoriche/microservices | microservices/queues/client.py | _exchange.publish | def publish(self, message, routing_key=None):
"""Publish message to exchange
:param message: message for publishing
:type message: any serializable object
:param routing_key: routing key for queue
:return: None
"""
if routing_key is None:
routing_key = self.routing_key
return self.client.publish_to_exchange(self.name, message=message, routing_key=routing_key) | python | def publish(self, message, routing_key=None):
"""Publish message to exchange
:param message: message for publishing
:type message: any serializable object
:param routing_key: routing key for queue
:return: None
"""
if routing_key is None:
routing_key = self.routing_key
return self.client.publish_to_exchange(self.name, message=message, routing_key=routing_key) | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"routing_key",
"=",
"None",
")",
":",
"if",
"routing_key",
"is",
"None",
":",
"routing_key",
"=",
"self",
".",
"routing_key",
"return",
"self",
".",
"client",
".",
"publish_to_exchange",
"(",
"self",
".",
"name",
",",
"message",
"=",
"message",
",",
"routing_key",
"=",
"routing_key",
")"
] | Publish message to exchange
:param message: message for publishing
:type message: any serializable object
:param routing_key: routing key for queue
:return: None | [
"Publish",
"message",
"to",
"exchange"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/queues/client.py#L32-L42 | train |
viatoriche/microservices | microservices/queues/client.py | _queue.publish | def publish(self, message):
"""Publish message to queue
:param message: message for publishing
:type message: any serializable object
:return: None
"""
return self.client.publish_to_queue(self.name, message=message) | python | def publish(self, message):
"""Publish message to queue
:param message: message for publishing
:type message: any serializable object
:return: None
"""
return self.client.publish_to_queue(self.name, message=message) | [
"def",
"publish",
"(",
"self",
",",
"message",
")",
":",
"return",
"self",
".",
"client",
".",
"publish_to_queue",
"(",
"self",
".",
"name",
",",
"message",
"=",
"message",
")"
] | Publish message to queue
:param message: message for publishing
:type message: any serializable object
:return: None | [
"Publish",
"message",
"to",
"queue"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/queues/client.py#L63-L70 | train |
bitesofcode/projexui | projexui/widgets/xpopupwidget.py | XPopupWidget.adjustContentsMargins | def adjustContentsMargins( self ):
"""
Adjusts the contents for this widget based on the anchor and \
mode.
"""
anchor = self.anchor()
mode = self.currentMode()
# margins for a dialog
if ( mode == XPopupWidget.Mode.Dialog ):
self.setContentsMargins(0, 0, 0, 0)
# margins for a top anchor point
elif ( anchor & (XPopupWidget.Anchor.TopLeft |
XPopupWidget.Anchor.TopCenter |
XPopupWidget.Anchor.TopRight) ):
self.setContentsMargins(0, self.popupPadding() + 5, 0, 0)
# margins for a bottom anchor point
elif ( anchor & (XPopupWidget.Anchor.BottomLeft |
XPopupWidget.Anchor.BottomCenter |
XPopupWidget.Anchor.BottomRight) ):
self.setContentsMargins(0, 0, 0, self.popupPadding())
# margins for a left anchor point
elif ( anchor & (XPopupWidget.Anchor.LeftTop |
XPopupWidget.Anchor.LeftCenter |
XPopupWidget.Anchor.LeftBottom) ):
self.setContentsMargins(self.popupPadding(), 0, 0, 0)
# margins for a right anchor point
else:
self.setContentsMargins(0, 0, self.popupPadding(), 0)
self.adjustMask() | python | def adjustContentsMargins( self ):
"""
Adjusts the contents for this widget based on the anchor and \
mode.
"""
anchor = self.anchor()
mode = self.currentMode()
# margins for a dialog
if ( mode == XPopupWidget.Mode.Dialog ):
self.setContentsMargins(0, 0, 0, 0)
# margins for a top anchor point
elif ( anchor & (XPopupWidget.Anchor.TopLeft |
XPopupWidget.Anchor.TopCenter |
XPopupWidget.Anchor.TopRight) ):
self.setContentsMargins(0, self.popupPadding() + 5, 0, 0)
# margins for a bottom anchor point
elif ( anchor & (XPopupWidget.Anchor.BottomLeft |
XPopupWidget.Anchor.BottomCenter |
XPopupWidget.Anchor.BottomRight) ):
self.setContentsMargins(0, 0, 0, self.popupPadding())
# margins for a left anchor point
elif ( anchor & (XPopupWidget.Anchor.LeftTop |
XPopupWidget.Anchor.LeftCenter |
XPopupWidget.Anchor.LeftBottom) ):
self.setContentsMargins(self.popupPadding(), 0, 0, 0)
# margins for a right anchor point
else:
self.setContentsMargins(0, 0, self.popupPadding(), 0)
self.adjustMask() | [
"def",
"adjustContentsMargins",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"anchor",
"(",
")",
"mode",
"=",
"self",
".",
"currentMode",
"(",
")",
"# margins for a dialog\r",
"if",
"(",
"mode",
"==",
"XPopupWidget",
".",
"Mode",
".",
"Dialog",
")",
":",
"self",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"# margins for a top anchor point\r",
"elif",
"(",
"anchor",
"&",
"(",
"XPopupWidget",
".",
"Anchor",
".",
"TopLeft",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"TopCenter",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"TopRight",
")",
")",
":",
"self",
".",
"setContentsMargins",
"(",
"0",
",",
"self",
".",
"popupPadding",
"(",
")",
"+",
"5",
",",
"0",
",",
"0",
")",
"# margins for a bottom anchor point\r",
"elif",
"(",
"anchor",
"&",
"(",
"XPopupWidget",
".",
"Anchor",
".",
"BottomLeft",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"BottomCenter",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"BottomRight",
")",
")",
":",
"self",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"popupPadding",
"(",
")",
")",
"# margins for a left anchor point\r",
"elif",
"(",
"anchor",
"&",
"(",
"XPopupWidget",
".",
"Anchor",
".",
"LeftTop",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"LeftCenter",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"LeftBottom",
")",
")",
":",
"self",
".",
"setContentsMargins",
"(",
"self",
".",
"popupPadding",
"(",
")",
",",
"0",
",",
"0",
",",
"0",
")",
"# margins for a right anchor point\r",
"else",
":",
"self",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"self",
".",
"popupPadding",
"(",
")",
",",
"0",
")",
"self",
".",
"adjustMask",
"(",
")"
] | Adjusts the contents for this widget based on the anchor and \
mode. | [
"Adjusts",
"the",
"contents",
"for",
"this",
"widget",
"based",
"on",
"the",
"anchor",
"and",
"\\",
"mode",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L188-L222 | train |
bitesofcode/projexui | projexui/widgets/xpopupwidget.py | XPopupWidget.adjustMask | def adjustMask(self):
"""
Updates the alpha mask for this popup widget.
"""
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask()
return
path = self.borderPath()
bitmap = QBitmap(self.width(), self.height())
bitmap.fill(QColor('white'))
with XPainter(bitmap) as painter:
painter.setRenderHint(XPainter.Antialiasing)
pen = QPen(QColor('black'))
pen.setWidthF(0.75)
painter.setPen(pen)
painter.setBrush(QColor('black'))
painter.drawPath(path)
self.setMask(bitmap) | python | def adjustMask(self):
"""
Updates the alpha mask for this popup widget.
"""
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask()
return
path = self.borderPath()
bitmap = QBitmap(self.width(), self.height())
bitmap.fill(QColor('white'))
with XPainter(bitmap) as painter:
painter.setRenderHint(XPainter.Antialiasing)
pen = QPen(QColor('black'))
pen.setWidthF(0.75)
painter.setPen(pen)
painter.setBrush(QColor('black'))
painter.drawPath(path)
self.setMask(bitmap) | [
"def",
"adjustMask",
"(",
"self",
")",
":",
"if",
"self",
".",
"currentMode",
"(",
")",
"==",
"XPopupWidget",
".",
"Mode",
".",
"Dialog",
":",
"self",
".",
"clearMask",
"(",
")",
"return",
"path",
"=",
"self",
".",
"borderPath",
"(",
")",
"bitmap",
"=",
"QBitmap",
"(",
"self",
".",
"width",
"(",
")",
",",
"self",
".",
"height",
"(",
")",
")",
"bitmap",
".",
"fill",
"(",
"QColor",
"(",
"'white'",
")",
")",
"with",
"XPainter",
"(",
"bitmap",
")",
"as",
"painter",
":",
"painter",
".",
"setRenderHint",
"(",
"XPainter",
".",
"Antialiasing",
")",
"pen",
"=",
"QPen",
"(",
"QColor",
"(",
"'black'",
")",
")",
"pen",
".",
"setWidthF",
"(",
"0.75",
")",
"painter",
".",
"setPen",
"(",
"pen",
")",
"painter",
".",
"setBrush",
"(",
"QColor",
"(",
"'black'",
")",
")",
"painter",
".",
"drawPath",
"(",
"path",
")",
"self",
".",
"setMask",
"(",
"bitmap",
")"
] | Updates the alpha mask for this popup widget. | [
"Updates",
"the",
"alpha",
"mask",
"for",
"this",
"popup",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L224-L244 | train |
bitesofcode/projexui | projexui/widgets/xpopupwidget.py | XPopupWidget.adjustSize | def adjustSize(self):
"""
Adjusts the size of this popup to best fit the new widget size.
"""
widget = self.centralWidget()
if widget is None:
super(XPopupWidget, self).adjustSize()
return
widget.adjustSize()
hint = widget.minimumSizeHint()
size = widget.minimumSize()
width = max(size.width(), hint.width())
height = max(size.height(), hint.height())
width += 20
height += 20
if self._buttonBoxVisible:
height += self.buttonBox().height() + 10
if self._titleBarVisible:
height += max(self._dialogButton.height(),
self._closeButton.height()) + 10
curr_w = self.width()
curr_h = self.height()
# determine if we need to move based on our anchor
anchor = self.anchor()
if anchor & (self.Anchor.LeftBottom | self.Anchor.RightBottom | \
self.Anchor.BottomLeft | self.Anchor.BottomCenter | \
self.Anchor.BottomRight):
delta_y = height - curr_h
elif anchor & (self.Anchor.LeftCenter | self.Anchor.RightCenter):
delta_y = (height - curr_h) / 2
else:
delta_y = 0
if anchor & (self.Anchor.RightTop | self.Anchor.RightCenter | \
self.Anchor.RightTop | self.Anchor.TopRight):
delta_x = width - curr_w
elif anchor & (self.Anchor.TopCenter | self.Anchor.BottomCenter):
delta_x = (width - curr_w) / 2
else:
delta_x = 0
self.setMinimumSize(width, height)
self.resize(width, height)
pos = self.pos()
pos.setX(pos.x() - delta_x)
pos.setY(pos.y() - delta_y)
self.move(pos) | python | def adjustSize(self):
"""
Adjusts the size of this popup to best fit the new widget size.
"""
widget = self.centralWidget()
if widget is None:
super(XPopupWidget, self).adjustSize()
return
widget.adjustSize()
hint = widget.minimumSizeHint()
size = widget.minimumSize()
width = max(size.width(), hint.width())
height = max(size.height(), hint.height())
width += 20
height += 20
if self._buttonBoxVisible:
height += self.buttonBox().height() + 10
if self._titleBarVisible:
height += max(self._dialogButton.height(),
self._closeButton.height()) + 10
curr_w = self.width()
curr_h = self.height()
# determine if we need to move based on our anchor
anchor = self.anchor()
if anchor & (self.Anchor.LeftBottom | self.Anchor.RightBottom | \
self.Anchor.BottomLeft | self.Anchor.BottomCenter | \
self.Anchor.BottomRight):
delta_y = height - curr_h
elif anchor & (self.Anchor.LeftCenter | self.Anchor.RightCenter):
delta_y = (height - curr_h) / 2
else:
delta_y = 0
if anchor & (self.Anchor.RightTop | self.Anchor.RightCenter | \
self.Anchor.RightTop | self.Anchor.TopRight):
delta_x = width - curr_w
elif anchor & (self.Anchor.TopCenter | self.Anchor.BottomCenter):
delta_x = (width - curr_w) / 2
else:
delta_x = 0
self.setMinimumSize(width, height)
self.resize(width, height)
pos = self.pos()
pos.setX(pos.x() - delta_x)
pos.setY(pos.y() - delta_y)
self.move(pos) | [
"def",
"adjustSize",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"centralWidget",
"(",
")",
"if",
"widget",
"is",
"None",
":",
"super",
"(",
"XPopupWidget",
",",
"self",
")",
".",
"adjustSize",
"(",
")",
"return",
"widget",
".",
"adjustSize",
"(",
")",
"hint",
"=",
"widget",
".",
"minimumSizeHint",
"(",
")",
"size",
"=",
"widget",
".",
"minimumSize",
"(",
")",
"width",
"=",
"max",
"(",
"size",
".",
"width",
"(",
")",
",",
"hint",
".",
"width",
"(",
")",
")",
"height",
"=",
"max",
"(",
"size",
".",
"height",
"(",
")",
",",
"hint",
".",
"height",
"(",
")",
")",
"width",
"+=",
"20",
"height",
"+=",
"20",
"if",
"self",
".",
"_buttonBoxVisible",
":",
"height",
"+=",
"self",
".",
"buttonBox",
"(",
")",
".",
"height",
"(",
")",
"+",
"10",
"if",
"self",
".",
"_titleBarVisible",
":",
"height",
"+=",
"max",
"(",
"self",
".",
"_dialogButton",
".",
"height",
"(",
")",
",",
"self",
".",
"_closeButton",
".",
"height",
"(",
")",
")",
"+",
"10",
"curr_w",
"=",
"self",
".",
"width",
"(",
")",
"curr_h",
"=",
"self",
".",
"height",
"(",
")",
"# determine if we need to move based on our anchor\r",
"anchor",
"=",
"self",
".",
"anchor",
"(",
")",
"if",
"anchor",
"&",
"(",
"self",
".",
"Anchor",
".",
"LeftBottom",
"|",
"self",
".",
"Anchor",
".",
"RightBottom",
"|",
"self",
".",
"Anchor",
".",
"BottomLeft",
"|",
"self",
".",
"Anchor",
".",
"BottomCenter",
"|",
"self",
".",
"Anchor",
".",
"BottomRight",
")",
":",
"delta_y",
"=",
"height",
"-",
"curr_h",
"elif",
"anchor",
"&",
"(",
"self",
".",
"Anchor",
".",
"LeftCenter",
"|",
"self",
".",
"Anchor",
".",
"RightCenter",
")",
":",
"delta_y",
"=",
"(",
"height",
"-",
"curr_h",
")",
"/",
"2",
"else",
":",
"delta_y",
"=",
"0",
"if",
"anchor",
"&",
"(",
"self",
".",
"Anchor",
".",
"RightTop",
"|",
"self",
".",
"Anchor",
".",
"RightCenter",
"|",
"self",
".",
"Anchor",
".",
"RightTop",
"|",
"self",
".",
"Anchor",
".",
"TopRight",
")",
":",
"delta_x",
"=",
"width",
"-",
"curr_w",
"elif",
"anchor",
"&",
"(",
"self",
".",
"Anchor",
".",
"TopCenter",
"|",
"self",
".",
"Anchor",
".",
"BottomCenter",
")",
":",
"delta_x",
"=",
"(",
"width",
"-",
"curr_w",
")",
"/",
"2",
"else",
":",
"delta_x",
"=",
"0",
"self",
".",
"setMinimumSize",
"(",
"width",
",",
"height",
")",
"self",
".",
"resize",
"(",
"width",
",",
"height",
")",
"pos",
"=",
"self",
".",
"pos",
"(",
")",
"pos",
".",
"setX",
"(",
"pos",
".",
"x",
"(",
")",
"-",
"delta_x",
")",
"pos",
".",
"setY",
"(",
"pos",
".",
"y",
"(",
")",
"-",
"delta_y",
")",
"self",
".",
"move",
"(",
"pos",
")"
] | Adjusts the size of this popup to best fit the new widget size. | [
"Adjusts",
"the",
"size",
"of",
"this",
"popup",
"to",
"best",
"fit",
"the",
"new",
"widget",
"size",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L246-L305 | train |
bitesofcode/projexui | projexui/widgets/xpopupwidget.py | XPopupWidget.close | def close(self):
"""
Closes the popup widget and central widget.
"""
widget = self.centralWidget()
if widget and not widget.close():
return
super(XPopupWidget, self).close() | python | def close(self):
"""
Closes the popup widget and central widget.
"""
widget = self.centralWidget()
if widget and not widget.close():
return
super(XPopupWidget, self).close() | [
"def",
"close",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"centralWidget",
"(",
")",
"if",
"widget",
"and",
"not",
"widget",
".",
"close",
"(",
")",
":",
"return",
"super",
"(",
"XPopupWidget",
",",
"self",
")",
".",
"close",
"(",
")"
] | Closes the popup widget and central widget. | [
"Closes",
"the",
"popup",
"widget",
"and",
"central",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L530-L538 | train |
bitesofcode/projexui | projexui/widgets/xpageswidget.py | XPagesWidget.refreshLabels | def refreshLabels( self ):
"""
Refreshes the labels to display the proper title and count information.
"""
itemCount = self.itemCount()
title = self.itemsTitle()
if ( not itemCount ):
self._itemsLabel.setText(' %s per page' % title)
else:
msg = ' %s per page, %i %s total' % (title, itemCount, title)
self._itemsLabel.setText(msg) | python | def refreshLabels( self ):
"""
Refreshes the labels to display the proper title and count information.
"""
itemCount = self.itemCount()
title = self.itemsTitle()
if ( not itemCount ):
self._itemsLabel.setText(' %s per page' % title)
else:
msg = ' %s per page, %i %s total' % (title, itemCount, title)
self._itemsLabel.setText(msg) | [
"def",
"refreshLabels",
"(",
"self",
")",
":",
"itemCount",
"=",
"self",
".",
"itemCount",
"(",
")",
"title",
"=",
"self",
".",
"itemsTitle",
"(",
")",
"if",
"(",
"not",
"itemCount",
")",
":",
"self",
".",
"_itemsLabel",
".",
"setText",
"(",
"' %s per page'",
"%",
"title",
")",
"else",
":",
"msg",
"=",
"' %s per page, %i %s total'",
"%",
"(",
"title",
",",
"itemCount",
",",
"title",
")",
"self",
".",
"_itemsLabel",
".",
"setText",
"(",
"msg",
")"
] | Refreshes the labels to display the proper title and count information. | [
"Refreshes",
"the",
"labels",
"to",
"display",
"the",
"proper",
"title",
"and",
"count",
"information",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpageswidget.py#L207-L218 | train |
mikhaildubov/AST-text-analysis | east/utils.py | import_modules_from_package | def import_modules_from_package(package):
"""Import modules from package and append into sys.modules
:param package: full package name, e.g. east.asts
"""
path = [os.path.dirname(__file__), '..'] + package.split('.')
path = os.path.join(*path)
for root, dirs, files in os.walk(path):
for filename in files:
if filename.startswith('__') or not filename.endswith('.py'):
continue
new_package = ".".join(root.split(os.sep)).split("....")[1]
module_name = '%s.%s' % (new_package, filename[:-3])
if module_name not in sys.modules:
__import__(module_name) | python | def import_modules_from_package(package):
"""Import modules from package and append into sys.modules
:param package: full package name, e.g. east.asts
"""
path = [os.path.dirname(__file__), '..'] + package.split('.')
path = os.path.join(*path)
for root, dirs, files in os.walk(path):
for filename in files:
if filename.startswith('__') or not filename.endswith('.py'):
continue
new_package = ".".join(root.split(os.sep)).split("....")[1]
module_name = '%s.%s' % (new_package, filename[:-3])
if module_name not in sys.modules:
__import__(module_name) | [
"def",
"import_modules_from_package",
"(",
"package",
")",
":",
"path",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
"]",
"+",
"package",
".",
"split",
"(",
"'.'",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"path",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"filename",
"in",
"files",
":",
"if",
"filename",
".",
"startswith",
"(",
"'__'",
")",
"or",
"not",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
":",
"continue",
"new_package",
"=",
"\".\"",
".",
"join",
"(",
"root",
".",
"split",
"(",
"os",
".",
"sep",
")",
")",
".",
"split",
"(",
"\"....\"",
")",
"[",
"1",
"]",
"module_name",
"=",
"'%s.%s'",
"%",
"(",
"new_package",
",",
"filename",
"[",
":",
"-",
"3",
"]",
")",
"if",
"module_name",
"not",
"in",
"sys",
".",
"modules",
":",
"__import__",
"(",
"module_name",
")"
] | Import modules from package and append into sys.modules
:param package: full package name, e.g. east.asts | [
"Import",
"modules",
"from",
"package",
"and",
"append",
"into",
"sys",
".",
"modules"
] | 055ad8d2492c100bbbaa25309ec1074bdf1dfaa5 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/utils.py#L119-L133 | train |
bearyinnovative/bearychat.py | bearychat/openapi/client.py | Requester.request | def request(self, request_method, api_method, *args, **kwargs):
"""Perform a request.
Args:
request_method: HTTP method for this request.
api_method: API method name for this request.
*args: Extra arguments to pass to the request.
**kwargs: Extra keyword arguments to pass to the request.
Returns:
A dict contains the request response data.
Raises:
RequestFailedError: Raises when BearyChat's OpenAPI responses
with status code != 2xx
"""
url = self._build_url(api_method)
resp = requests.request(request_method, url, *args, **kwargs)
try:
rv = resp.json()
except ValueError:
raise RequestFailedError(resp, 'not a json body')
if not resp.ok:
raise RequestFailedError(resp, rv.get('error'))
return rv | python | def request(self, request_method, api_method, *args, **kwargs):
"""Perform a request.
Args:
request_method: HTTP method for this request.
api_method: API method name for this request.
*args: Extra arguments to pass to the request.
**kwargs: Extra keyword arguments to pass to the request.
Returns:
A dict contains the request response data.
Raises:
RequestFailedError: Raises when BearyChat's OpenAPI responses
with status code != 2xx
"""
url = self._build_url(api_method)
resp = requests.request(request_method, url, *args, **kwargs)
try:
rv = resp.json()
except ValueError:
raise RequestFailedError(resp, 'not a json body')
if not resp.ok:
raise RequestFailedError(resp, rv.get('error'))
return rv | [
"def",
"request",
"(",
"self",
",",
"request_method",
",",
"api_method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"api_method",
")",
"resp",
"=",
"requests",
".",
"request",
"(",
"request_method",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"rv",
"=",
"resp",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"raise",
"RequestFailedError",
"(",
"resp",
",",
"'not a json body'",
")",
"if",
"not",
"resp",
".",
"ok",
":",
"raise",
"RequestFailedError",
"(",
"resp",
",",
"rv",
".",
"get",
"(",
"'error'",
")",
")",
"return",
"rv"
] | Perform a request.
Args:
request_method: HTTP method for this request.
api_method: API method name for this request.
*args: Extra arguments to pass to the request.
**kwargs: Extra keyword arguments to pass to the request.
Returns:
A dict contains the request response data.
Raises:
RequestFailedError: Raises when BearyChat's OpenAPI responses
with status code != 2xx | [
"Perform",
"a",
"request",
"."
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/openapi/client.py#L82-L109 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | XNodeAnimation.updateCurrentValue | def updateCurrentValue(self, value):
"""
Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user.
"""
xsnap = None
ysnap = None
if value != self.endValue():
xsnap = self.targetObject().isXSnappedToGrid()
ysnap = self.targetObject().isYSnappedToGrid()
self.targetObject().setXSnapToGrid(False)
self.targetObject().setYSnapToGrid(False)
super(XNodeAnimation, self).updateCurrentValue(value)
if value != self.endValue():
self.targetObject().setXSnapToGrid(xsnap)
self.targetObject().setYSnapToGrid(ysnap) | python | def updateCurrentValue(self, value):
"""
Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user.
"""
xsnap = None
ysnap = None
if value != self.endValue():
xsnap = self.targetObject().isXSnappedToGrid()
ysnap = self.targetObject().isYSnappedToGrid()
self.targetObject().setXSnapToGrid(False)
self.targetObject().setYSnapToGrid(False)
super(XNodeAnimation, self).updateCurrentValue(value)
if value != self.endValue():
self.targetObject().setXSnapToGrid(xsnap)
self.targetObject().setYSnapToGrid(ysnap) | [
"def",
"updateCurrentValue",
"(",
"self",
",",
"value",
")",
":",
"xsnap",
"=",
"None",
"ysnap",
"=",
"None",
"if",
"value",
"!=",
"self",
".",
"endValue",
"(",
")",
":",
"xsnap",
"=",
"self",
".",
"targetObject",
"(",
")",
".",
"isXSnappedToGrid",
"(",
")",
"ysnap",
"=",
"self",
".",
"targetObject",
"(",
")",
".",
"isYSnappedToGrid",
"(",
")",
"self",
".",
"targetObject",
"(",
")",
".",
"setXSnapToGrid",
"(",
"False",
")",
"self",
".",
"targetObject",
"(",
")",
".",
"setYSnapToGrid",
"(",
"False",
")",
"super",
"(",
"XNodeAnimation",
",",
"self",
")",
".",
"updateCurrentValue",
"(",
"value",
")",
"if",
"value",
"!=",
"self",
".",
"endValue",
"(",
")",
":",
"self",
".",
"targetObject",
"(",
")",
".",
"setXSnapToGrid",
"(",
"xsnap",
")",
"self",
".",
"targetObject",
"(",
")",
".",
"setYSnapToGrid",
"(",
"ysnap",
")"
] | Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user. | [
"Disables",
"snapping",
"during",
"the",
"current",
"value",
"update",
"to",
"ensure",
"a",
"smooth",
"transition",
"for",
"node",
"animations",
".",
"Since",
"this",
"can",
"only",
"be",
"called",
"via",
"code",
"we",
"don",
"t",
"need",
"to",
"worry",
"about",
"snapping",
"to",
"the",
"grid",
"for",
"a",
"user",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L69-L89 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | XNode.adjustTitleFont | def adjustTitleFont(self):
"""
Adjusts the font used for the title based on the current with and \
display name.
"""
left, top, right, bottom = self.contentsMargins()
r = self.roundingRadius()
# include text padding
left += 5 + r / 2
top += 5 + r / 2
right += 5 + r / 2
bottom += 5 + r / 2
r = self.rect()
rect_l = r.left() + left
rect_r = r.right() - right
rect_t = r.top() + top
rect_b = r.bottom() - bottom
# ensure we have a valid rect
rect = QRect(rect_l, rect_t, rect_r - rect_l, rect_b - rect_t)
if rect.width() < 10:
return
font = XFont(QApplication.font())
font.adaptSize(self.displayName(), rect, wordWrap=self.wordWrap())
self._titleFont = font | python | def adjustTitleFont(self):
"""
Adjusts the font used for the title based on the current with and \
display name.
"""
left, top, right, bottom = self.contentsMargins()
r = self.roundingRadius()
# include text padding
left += 5 + r / 2
top += 5 + r / 2
right += 5 + r / 2
bottom += 5 + r / 2
r = self.rect()
rect_l = r.left() + left
rect_r = r.right() - right
rect_t = r.top() + top
rect_b = r.bottom() - bottom
# ensure we have a valid rect
rect = QRect(rect_l, rect_t, rect_r - rect_l, rect_b - rect_t)
if rect.width() < 10:
return
font = XFont(QApplication.font())
font.adaptSize(self.displayName(), rect, wordWrap=self.wordWrap())
self._titleFont = font | [
"def",
"adjustTitleFont",
"(",
"self",
")",
":",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"=",
"self",
".",
"contentsMargins",
"(",
")",
"r",
"=",
"self",
".",
"roundingRadius",
"(",
")",
"# include text padding",
"left",
"+=",
"5",
"+",
"r",
"/",
"2",
"top",
"+=",
"5",
"+",
"r",
"/",
"2",
"right",
"+=",
"5",
"+",
"r",
"/",
"2",
"bottom",
"+=",
"5",
"+",
"r",
"/",
"2",
"r",
"=",
"self",
".",
"rect",
"(",
")",
"rect_l",
"=",
"r",
".",
"left",
"(",
")",
"+",
"left",
"rect_r",
"=",
"r",
".",
"right",
"(",
")",
"-",
"right",
"rect_t",
"=",
"r",
".",
"top",
"(",
")",
"+",
"top",
"rect_b",
"=",
"r",
".",
"bottom",
"(",
")",
"-",
"bottom",
"# ensure we have a valid rect",
"rect",
"=",
"QRect",
"(",
"rect_l",
",",
"rect_t",
",",
"rect_r",
"-",
"rect_l",
",",
"rect_b",
"-",
"rect_t",
")",
"if",
"rect",
".",
"width",
"(",
")",
"<",
"10",
":",
"return",
"font",
"=",
"XFont",
"(",
"QApplication",
".",
"font",
"(",
")",
")",
"font",
".",
"adaptSize",
"(",
"self",
".",
"displayName",
"(",
")",
",",
"rect",
",",
"wordWrap",
"=",
"self",
".",
"wordWrap",
"(",
")",
")",
"self",
".",
"_titleFont",
"=",
"font"
] | Adjusts the font used for the title based on the current with and \
display name. | [
"Adjusts",
"the",
"font",
"used",
"for",
"the",
"title",
"based",
"on",
"the",
"current",
"with",
"and",
"\\",
"display",
"name",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L196-L224 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | XNode.adjustSize | def adjustSize( self ):
"""
Adjusts the size of this node to support the length of its contents.
"""
cell = self.scene().cellWidth() * 2
minheight = cell
minwidth = 2 * cell
# fit to the grid size
metrics = QFontMetrics(QApplication.font())
width = metrics.width(self.displayName()) + 20
width = ((width/cell) * cell) + (cell % width)
height = self.rect().height()
# adjust for the icon
icon = self.icon()
if icon and not icon.isNull():
width += self.iconSize().width() + 2
height = max(height, self.iconSize().height() + 2)
w = max(width, minwidth)
h = max(height, minheight)
max_w = self.maximumWidth()
max_h = self.maximumHeight()
if max_w is not None:
w = min(w, max_w)
if max_h is not None:
h = min(h, max_h)
self.setMinimumWidth(w)
self.setMinimumHeight(h)
self.rebuild() | python | def adjustSize( self ):
"""
Adjusts the size of this node to support the length of its contents.
"""
cell = self.scene().cellWidth() * 2
minheight = cell
minwidth = 2 * cell
# fit to the grid size
metrics = QFontMetrics(QApplication.font())
width = metrics.width(self.displayName()) + 20
width = ((width/cell) * cell) + (cell % width)
height = self.rect().height()
# adjust for the icon
icon = self.icon()
if icon and not icon.isNull():
width += self.iconSize().width() + 2
height = max(height, self.iconSize().height() + 2)
w = max(width, minwidth)
h = max(height, minheight)
max_w = self.maximumWidth()
max_h = self.maximumHeight()
if max_w is not None:
w = min(w, max_w)
if max_h is not None:
h = min(h, max_h)
self.setMinimumWidth(w)
self.setMinimumHeight(h)
self.rebuild() | [
"def",
"adjustSize",
"(",
"self",
")",
":",
"cell",
"=",
"self",
".",
"scene",
"(",
")",
".",
"cellWidth",
"(",
")",
"*",
"2",
"minheight",
"=",
"cell",
"minwidth",
"=",
"2",
"*",
"cell",
"# fit to the grid size",
"metrics",
"=",
"QFontMetrics",
"(",
"QApplication",
".",
"font",
"(",
")",
")",
"width",
"=",
"metrics",
".",
"width",
"(",
"self",
".",
"displayName",
"(",
")",
")",
"+",
"20",
"width",
"=",
"(",
"(",
"width",
"/",
"cell",
")",
"*",
"cell",
")",
"+",
"(",
"cell",
"%",
"width",
")",
"height",
"=",
"self",
".",
"rect",
"(",
")",
".",
"height",
"(",
")",
"# adjust for the icon",
"icon",
"=",
"self",
".",
"icon",
"(",
")",
"if",
"icon",
"and",
"not",
"icon",
".",
"isNull",
"(",
")",
":",
"width",
"+=",
"self",
".",
"iconSize",
"(",
")",
".",
"width",
"(",
")",
"+",
"2",
"height",
"=",
"max",
"(",
"height",
",",
"self",
".",
"iconSize",
"(",
")",
".",
"height",
"(",
")",
"+",
"2",
")",
"w",
"=",
"max",
"(",
"width",
",",
"minwidth",
")",
"h",
"=",
"max",
"(",
"height",
",",
"minheight",
")",
"max_w",
"=",
"self",
".",
"maximumWidth",
"(",
")",
"max_h",
"=",
"self",
".",
"maximumHeight",
"(",
")",
"if",
"max_w",
"is",
"not",
"None",
":",
"w",
"=",
"min",
"(",
"w",
",",
"max_w",
")",
"if",
"max_h",
"is",
"not",
"None",
":",
"h",
"=",
"min",
"(",
"h",
",",
"max_h",
")",
"self",
".",
"setMinimumWidth",
"(",
"w",
")",
"self",
".",
"setMinimumHeight",
"(",
"h",
")",
"self",
".",
"rebuild",
"(",
")"
] | Adjusts the size of this node to support the length of its contents. | [
"Adjusts",
"the",
"size",
"of",
"this",
"node",
"to",
"support",
"the",
"length",
"of",
"its",
"contents",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L226-L261 | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | XNode.isEnabled | def isEnabled( self ):
"""
Returns whether or not this node is enabled.
"""
if ( self._disableWithLayer and self._layer ):
lenabled = self._layer.isEnabled()
else:
lenabled = True
return self._enabled and lenabled | python | def isEnabled( self ):
"""
Returns whether or not this node is enabled.
"""
if ( self._disableWithLayer and self._layer ):
lenabled = self._layer.isEnabled()
else:
lenabled = True
return self._enabled and lenabled | [
"def",
"isEnabled",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_disableWithLayer",
"and",
"self",
".",
"_layer",
")",
":",
"lenabled",
"=",
"self",
".",
"_layer",
".",
"isEnabled",
"(",
")",
"else",
":",
"lenabled",
"=",
"True",
"return",
"self",
".",
"_enabled",
"and",
"lenabled"
] | Returns whether or not this node is enabled. | [
"Returns",
"whether",
"or",
"not",
"this",
"node",
"is",
"enabled",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L1052-L1061 | train |
core/uricore | uricore/wkz_datastructures.py | MultiDict.popitem | def popitem(self):
"""Pop an item from the dict."""
try:
item = dict.popitem(self)
return (item[0], item[1][0])
except KeyError, e:
raise BadRequestKeyError(str(e)) | python | def popitem(self):
"""Pop an item from the dict."""
try:
item = dict.popitem(self)
return (item[0], item[1][0])
except KeyError, e:
raise BadRequestKeyError(str(e)) | [
"def",
"popitem",
"(",
"self",
")",
":",
"try",
":",
"item",
"=",
"dict",
".",
"popitem",
"(",
"self",
")",
"return",
"(",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"except",
"KeyError",
",",
"e",
":",
"raise",
"BadRequestKeyError",
"(",
"str",
"(",
"e",
")",
")"
] | Pop an item from the dict. | [
"Pop",
"an",
"item",
"from",
"the",
"dict",
"."
] | dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_datastructures.py#L333-L339 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.emitCurrentRecordChanged | def emitCurrentRecordChanged(self):
"""
Emits the current record changed signal for this combobox, provided \
the signals aren't blocked.
"""
record = unwrapVariant(self.itemData(self.currentIndex(), Qt.UserRole))
if not Table.recordcheck(record):
record = None
self._currentRecord = record
if not self.signalsBlocked():
self._changedRecord = record
self.currentRecordChanged.emit(record) | python | def emitCurrentRecordChanged(self):
"""
Emits the current record changed signal for this combobox, provided \
the signals aren't blocked.
"""
record = unwrapVariant(self.itemData(self.currentIndex(), Qt.UserRole))
if not Table.recordcheck(record):
record = None
self._currentRecord = record
if not self.signalsBlocked():
self._changedRecord = record
self.currentRecordChanged.emit(record) | [
"def",
"emitCurrentRecordChanged",
"(",
"self",
")",
":",
"record",
"=",
"unwrapVariant",
"(",
"self",
".",
"itemData",
"(",
"self",
".",
"currentIndex",
"(",
")",
",",
"Qt",
".",
"UserRole",
")",
")",
"if",
"not",
"Table",
".",
"recordcheck",
"(",
"record",
")",
":",
"record",
"=",
"None",
"self",
".",
"_currentRecord",
"=",
"record",
"if",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"self",
".",
"_changedRecord",
"=",
"record",
"self",
".",
"currentRecordChanged",
".",
"emit",
"(",
"record",
")"
] | Emits the current record changed signal for this combobox, provided \
the signals aren't blocked. | [
"Emits",
"the",
"current",
"record",
"changed",
"signal",
"for",
"this",
"combobox",
"provided",
"\\",
"the",
"signals",
"aren",
"t",
"blocked",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L358-L370 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.emitCurrentRecordEdited | def emitCurrentRecordEdited(self):
"""
Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time.
"""
if self._changedRecord == -1:
return
if self.signalsBlocked():
return
record = self._changedRecord
self._changedRecord = -1
self.currentRecordEdited.emit(record) | python | def emitCurrentRecordEdited(self):
"""
Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time.
"""
if self._changedRecord == -1:
return
if self.signalsBlocked():
return
record = self._changedRecord
self._changedRecord = -1
self.currentRecordEdited.emit(record) | [
"def",
"emitCurrentRecordEdited",
"(",
"self",
")",
":",
"if",
"self",
".",
"_changedRecord",
"==",
"-",
"1",
":",
"return",
"if",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"return",
"record",
"=",
"self",
".",
"_changedRecord",
"self",
".",
"_changedRecord",
"=",
"-",
"1",
"self",
".",
"currentRecordEdited",
".",
"emit",
"(",
"record",
")"
] | Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time. | [
"Emits",
"the",
"current",
"record",
"edited",
"signal",
"for",
"this",
"combobox",
"provided",
"the",
"signals",
"aren",
"t",
"blocked",
"and",
"the",
"record",
"has",
"changed",
"since",
"the",
"last",
"time",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L372-L385 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.focusInEvent | def focusInEvent(self, event):
"""
When this widget loses focus, try to emit the record changed event
signal.
"""
self._changedRecord = -1
super(XOrbRecordBox, self).focusInEvent(event) | python | def focusInEvent(self, event):
"""
When this widget loses focus, try to emit the record changed event
signal.
"""
self._changedRecord = -1
super(XOrbRecordBox, self).focusInEvent(event) | [
"def",
"focusInEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_changedRecord",
"=",
"-",
"1",
"super",
"(",
"XOrbRecordBox",
",",
"self",
")",
".",
"focusInEvent",
"(",
"event",
")"
] | When this widget loses focus, try to emit the record changed event
signal. | [
"When",
"this",
"widget",
"loses",
"focus",
"try",
"to",
"emit",
"the",
"record",
"changed",
"event",
"signal",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L480-L486 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.hidePopup | def hidePopup(self):
"""
Overloads the hide popup method to handle when the user hides
the popup widget.
"""
if self._treePopupWidget and self.showTreePopup():
self._treePopupWidget.close()
super(XOrbRecordBox, self).hidePopup() | python | def hidePopup(self):
"""
Overloads the hide popup method to handle when the user hides
the popup widget.
"""
if self._treePopupWidget and self.showTreePopup():
self._treePopupWidget.close()
super(XOrbRecordBox, self).hidePopup() | [
"def",
"hidePopup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_treePopupWidget",
"and",
"self",
".",
"showTreePopup",
"(",
")",
":",
"self",
".",
"_treePopupWidget",
".",
"close",
"(",
")",
"super",
"(",
"XOrbRecordBox",
",",
"self",
")",
".",
"hidePopup",
"(",
")"
] | Overloads the hide popup method to handle when the user hides
the popup widget. | [
"Overloads",
"the",
"hide",
"popup",
"method",
"to",
"handle",
"when",
"the",
"user",
"hides",
"the",
"popup",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L499-L507 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.markLoadingStarted | def markLoadingStarted(self):
"""
Marks this widget as loading records.
"""
if self.isThreadEnabled():
XLoaderWidget.start(self)
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setCursor(Qt.WaitCursor)
tree.clear()
tree.setUpdatesEnabled(False)
tree.blockSignals(True)
self._baseHints = (self.hint(), tree.hint())
tree.setHint('Loading records...')
self.setHint('Loading records...')
else:
self._baseHints = (self.hint(), '')
self.setHint('Loading records...')
self.setCursor(Qt.WaitCursor)
self.blockSignals(True)
self.setUpdatesEnabled(False)
# prepare to load
self.clear()
use_dummy = not self.isRequired() or self.isCheckable()
if use_dummy:
self.addItem('')
self.loadingStarted.emit() | python | def markLoadingStarted(self):
"""
Marks this widget as loading records.
"""
if self.isThreadEnabled():
XLoaderWidget.start(self)
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setCursor(Qt.WaitCursor)
tree.clear()
tree.setUpdatesEnabled(False)
tree.blockSignals(True)
self._baseHints = (self.hint(), tree.hint())
tree.setHint('Loading records...')
self.setHint('Loading records...')
else:
self._baseHints = (self.hint(), '')
self.setHint('Loading records...')
self.setCursor(Qt.WaitCursor)
self.blockSignals(True)
self.setUpdatesEnabled(False)
# prepare to load
self.clear()
use_dummy = not self.isRequired() or self.isCheckable()
if use_dummy:
self.addItem('')
self.loadingStarted.emit() | [
"def",
"markLoadingStarted",
"(",
"self",
")",
":",
"if",
"self",
".",
"isThreadEnabled",
"(",
")",
":",
"XLoaderWidget",
".",
"start",
"(",
"self",
")",
"if",
"self",
".",
"showTreePopup",
"(",
")",
":",
"tree",
"=",
"self",
".",
"treePopupWidget",
"(",
")",
"tree",
".",
"setCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
"tree",
".",
"clear",
"(",
")",
"tree",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"tree",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"_baseHints",
"=",
"(",
"self",
".",
"hint",
"(",
")",
",",
"tree",
".",
"hint",
"(",
")",
")",
"tree",
".",
"setHint",
"(",
"'Loading records...'",
")",
"self",
".",
"setHint",
"(",
"'Loading records...'",
")",
"else",
":",
"self",
".",
"_baseHints",
"=",
"(",
"self",
".",
"hint",
"(",
")",
",",
"''",
")",
"self",
".",
"setHint",
"(",
"'Loading records...'",
")",
"self",
".",
"setCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"# prepare to load\r",
"self",
".",
"clear",
"(",
")",
"use_dummy",
"=",
"not",
"self",
".",
"isRequired",
"(",
")",
"or",
"self",
".",
"isCheckable",
"(",
")",
"if",
"use_dummy",
":",
"self",
".",
"addItem",
"(",
"''",
")",
"self",
".",
"loadingStarted",
".",
"emit",
"(",
")"
] | Marks this widget as loading records. | [
"Marks",
"this",
"widget",
"as",
"loading",
"records",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L573-L604 | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | XOrbRecordBox.markLoadingFinished | def markLoadingFinished(self):
"""
Marks this widget as finished loading records.
"""
XLoaderWidget.stop(self, force=True)
hint, tree_hint = self._baseHints
self.setHint(hint)
# set the tree widget
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setHint(tree_hint)
tree.unsetCursor()
tree.setUpdatesEnabled(True)
tree.blockSignals(False)
self.unsetCursor()
self.blockSignals(False)
self.setUpdatesEnabled(True)
self.loadingFinished.emit() | python | def markLoadingFinished(self):
"""
Marks this widget as finished loading records.
"""
XLoaderWidget.stop(self, force=True)
hint, tree_hint = self._baseHints
self.setHint(hint)
# set the tree widget
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setHint(tree_hint)
tree.unsetCursor()
tree.setUpdatesEnabled(True)
tree.blockSignals(False)
self.unsetCursor()
self.blockSignals(False)
self.setUpdatesEnabled(True)
self.loadingFinished.emit() | [
"def",
"markLoadingFinished",
"(",
"self",
")",
":",
"XLoaderWidget",
".",
"stop",
"(",
"self",
",",
"force",
"=",
"True",
")",
"hint",
",",
"tree_hint",
"=",
"self",
".",
"_baseHints",
"self",
".",
"setHint",
"(",
"hint",
")",
"# set the tree widget\r",
"if",
"self",
".",
"showTreePopup",
"(",
")",
":",
"tree",
"=",
"self",
".",
"treePopupWidget",
"(",
")",
"tree",
".",
"setHint",
"(",
"tree_hint",
")",
"tree",
".",
"unsetCursor",
"(",
")",
"tree",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"tree",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"unsetCursor",
"(",
")",
"self",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"self",
".",
"loadingFinished",
".",
"emit",
"(",
")"
] | Marks this widget as finished loading records. | [
"Marks",
"this",
"widget",
"as",
"finished",
"loading",
"records",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L606-L626 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | XTreeWidgetItem.destroy | def destroy(self):
"""
Destroyes this item by disconnecting any signals that may exist. This
is called when the tree clears itself or is deleted. If you are
manually removing an item, you should call the destroy method yourself.
This is required since Python allows for non-QObject connections, and
since QTreeWidgetItem's are not QObjects', they do not properly handle
being destroyed with connections on them.
"""
try:
tree = self.treeWidget()
tree.destroyed.disconnect(self.destroy)
except StandardError:
pass
for movie in set(self._movies.values()):
try:
movie.frameChanged.disconnect(self._updateFrame)
except StandardError:
pass | python | def destroy(self):
"""
Destroyes this item by disconnecting any signals that may exist. This
is called when the tree clears itself or is deleted. If you are
manually removing an item, you should call the destroy method yourself.
This is required since Python allows for non-QObject connections, and
since QTreeWidgetItem's are not QObjects', they do not properly handle
being destroyed with connections on them.
"""
try:
tree = self.treeWidget()
tree.destroyed.disconnect(self.destroy)
except StandardError:
pass
for movie in set(self._movies.values()):
try:
movie.frameChanged.disconnect(self._updateFrame)
except StandardError:
pass | [
"def",
"destroy",
"(",
"self",
")",
":",
"try",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"tree",
".",
"destroyed",
".",
"disconnect",
"(",
"self",
".",
"destroy",
")",
"except",
"StandardError",
":",
"pass",
"for",
"movie",
"in",
"set",
"(",
"self",
".",
"_movies",
".",
"values",
"(",
")",
")",
":",
"try",
":",
"movie",
".",
"frameChanged",
".",
"disconnect",
"(",
"self",
".",
"_updateFrame",
")",
"except",
"StandardError",
":",
"pass"
] | Destroyes this item by disconnecting any signals that may exist. This
is called when the tree clears itself or is deleted. If you are
manually removing an item, you should call the destroy method yourself.
This is required since Python allows for non-QObject connections, and
since QTreeWidgetItem's are not QObjects', they do not properly handle
being destroyed with connections on them. | [
"Destroyes",
"this",
"item",
"by",
"disconnecting",
"any",
"signals",
"that",
"may",
"exist",
".",
"This",
"is",
"called",
"when",
"the",
"tree",
"clears",
"itself",
"or",
"is",
"deleted",
".",
"If",
"you",
"are",
"manually",
"removing",
"an",
"item",
"you",
"should",
"call",
"the",
"destroy",
"method",
"yourself",
".",
"This",
"is",
"required",
"since",
"Python",
"allows",
"for",
"non",
"-",
"QObject",
"connections",
"and",
"since",
"QTreeWidgetItem",
"s",
"are",
"not",
"QObjects",
"they",
"do",
"not",
"properly",
"handle",
"being",
"destroyed",
"with",
"connections",
"on",
"them",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L125-L144 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | XTreeWidgetItem.ensureVisible | def ensureVisible(self):
"""
Expands all the parents of this item to ensure that it is visible
to the user.
"""
parent = self.parent()
while parent:
parent.setExpanded(True)
parent = parent.parent() | python | def ensureVisible(self):
"""
Expands all the parents of this item to ensure that it is visible
to the user.
"""
parent = self.parent()
while parent:
parent.setExpanded(True)
parent = parent.parent() | [
"def",
"ensureVisible",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"while",
"parent",
":",
"parent",
".",
"setExpanded",
"(",
"True",
")",
"parent",
"=",
"parent",
".",
"parent",
"(",
")"
] | Expands all the parents of this item to ensure that it is visible
to the user. | [
"Expands",
"all",
"the",
"parents",
"of",
"this",
"item",
"to",
"ensure",
"that",
"it",
"is",
"visible",
"to",
"the",
"user",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L173-L181 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | XTreeWidgetItem.initGroupStyle | def initGroupStyle(self, useIcons=True, columnCount=None):
"""
Initialzes this item with a grouping style option.
"""
flags = self.flags()
if flags & QtCore.Qt.ItemIsSelectable:
flags ^= QtCore.Qt.ItemIsSelectable
self.setFlags(flags)
if useIcons:
ico = QtGui.QIcon(resources.find('img/treeview/triangle_right.png'))
expand_ico = QtGui.QIcon(resources.find('img/treeview/triangle_down.png'))
self.setIcon(0, ico)
self.setExpandedIcon(0, expand_ico)
palette = QtGui.QApplication.palette()
line_clr = palette.color(palette.Mid)
base_clr = palette.color(palette.Button)
text_clr = palette.color(palette.ButtonText)
gradient = QtGui.QLinearGradient()
gradient.setColorAt(0.00, line_clr)
gradient.setColorAt(0.03, line_clr)
gradient.setColorAt(0.04, base_clr.lighter(105))
gradient.setColorAt(0.25, base_clr)
gradient.setColorAt(0.96, base_clr.darker(105))
gradient.setColorAt(0.97, line_clr)
gradient.setColorAt(1.00, line_clr)
h = self._fixedHeight
if not h:
h = self.sizeHint(0).height()
if not h:
h = 18
gradient.setStart(0.0, 0.0)
gradient.setFinalStop(0.0, h)
brush = QtGui.QBrush(gradient)
tree = self.treeWidget()
columnCount = columnCount or (tree.columnCount() if tree else self.columnCount())
for i in range(columnCount):
self.setForeground(i, text_clr)
self.setBackground(i, brush) | python | def initGroupStyle(self, useIcons=True, columnCount=None):
"""
Initialzes this item with a grouping style option.
"""
flags = self.flags()
if flags & QtCore.Qt.ItemIsSelectable:
flags ^= QtCore.Qt.ItemIsSelectable
self.setFlags(flags)
if useIcons:
ico = QtGui.QIcon(resources.find('img/treeview/triangle_right.png'))
expand_ico = QtGui.QIcon(resources.find('img/treeview/triangle_down.png'))
self.setIcon(0, ico)
self.setExpandedIcon(0, expand_ico)
palette = QtGui.QApplication.palette()
line_clr = palette.color(palette.Mid)
base_clr = palette.color(palette.Button)
text_clr = palette.color(palette.ButtonText)
gradient = QtGui.QLinearGradient()
gradient.setColorAt(0.00, line_clr)
gradient.setColorAt(0.03, line_clr)
gradient.setColorAt(0.04, base_clr.lighter(105))
gradient.setColorAt(0.25, base_clr)
gradient.setColorAt(0.96, base_clr.darker(105))
gradient.setColorAt(0.97, line_clr)
gradient.setColorAt(1.00, line_clr)
h = self._fixedHeight
if not h:
h = self.sizeHint(0).height()
if not h:
h = 18
gradient.setStart(0.0, 0.0)
gradient.setFinalStop(0.0, h)
brush = QtGui.QBrush(gradient)
tree = self.treeWidget()
columnCount = columnCount or (tree.columnCount() if tree else self.columnCount())
for i in range(columnCount):
self.setForeground(i, text_clr)
self.setBackground(i, brush) | [
"def",
"initGroupStyle",
"(",
"self",
",",
"useIcons",
"=",
"True",
",",
"columnCount",
"=",
"None",
")",
":",
"flags",
"=",
"self",
".",
"flags",
"(",
")",
"if",
"flags",
"&",
"QtCore",
".",
"Qt",
".",
"ItemIsSelectable",
":",
"flags",
"^=",
"QtCore",
".",
"Qt",
".",
"ItemIsSelectable",
"self",
".",
"setFlags",
"(",
"flags",
")",
"if",
"useIcons",
":",
"ico",
"=",
"QtGui",
".",
"QIcon",
"(",
"resources",
".",
"find",
"(",
"'img/treeview/triangle_right.png'",
")",
")",
"expand_ico",
"=",
"QtGui",
".",
"QIcon",
"(",
"resources",
".",
"find",
"(",
"'img/treeview/triangle_down.png'",
")",
")",
"self",
".",
"setIcon",
"(",
"0",
",",
"ico",
")",
"self",
".",
"setExpandedIcon",
"(",
"0",
",",
"expand_ico",
")",
"palette",
"=",
"QtGui",
".",
"QApplication",
".",
"palette",
"(",
")",
"line_clr",
"=",
"palette",
".",
"color",
"(",
"palette",
".",
"Mid",
")",
"base_clr",
"=",
"palette",
".",
"color",
"(",
"palette",
".",
"Button",
")",
"text_clr",
"=",
"palette",
".",
"color",
"(",
"palette",
".",
"ButtonText",
")",
"gradient",
"=",
"QtGui",
".",
"QLinearGradient",
"(",
")",
"gradient",
".",
"setColorAt",
"(",
"0.00",
",",
"line_clr",
")",
"gradient",
".",
"setColorAt",
"(",
"0.03",
",",
"line_clr",
")",
"gradient",
".",
"setColorAt",
"(",
"0.04",
",",
"base_clr",
".",
"lighter",
"(",
"105",
")",
")",
"gradient",
".",
"setColorAt",
"(",
"0.25",
",",
"base_clr",
")",
"gradient",
".",
"setColorAt",
"(",
"0.96",
",",
"base_clr",
".",
"darker",
"(",
"105",
")",
")",
"gradient",
".",
"setColorAt",
"(",
"0.97",
",",
"line_clr",
")",
"gradient",
".",
"setColorAt",
"(",
"1.00",
",",
"line_clr",
")",
"h",
"=",
"self",
".",
"_fixedHeight",
"if",
"not",
"h",
":",
"h",
"=",
"self",
".",
"sizeHint",
"(",
"0",
")",
".",
"height",
"(",
")",
"if",
"not",
"h",
":",
"h",
"=",
"18",
"gradient",
".",
"setStart",
"(",
"0.0",
",",
"0.0",
")",
"gradient",
".",
"setFinalStop",
"(",
"0.0",
",",
"h",
")",
"brush",
"=",
"QtGui",
".",
"QBrush",
"(",
"gradient",
")",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"columnCount",
"=",
"columnCount",
"or",
"(",
"tree",
".",
"columnCount",
"(",
")",
"if",
"tree",
"else",
"self",
".",
"columnCount",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"columnCount",
")",
":",
"self",
".",
"setForeground",
"(",
"i",
",",
"text_clr",
")",
"self",
".",
"setBackground",
"(",
"i",
",",
"brush",
")"
] | Initialzes this item with a grouping style option. | [
"Initialzes",
"this",
"item",
"with",
"a",
"grouping",
"style",
"option",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L242-L290 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | XTreeWidgetItem.takeFromTree | def takeFromTree(self):
"""
Takes this item from the tree.
"""
tree = self.treeWidget()
parent = self.parent()
if parent:
parent.takeChild(parent.indexOfChild(self))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(self)) | python | def takeFromTree(self):
"""
Takes this item from the tree.
"""
tree = self.treeWidget()
parent = self.parent()
if parent:
parent.takeChild(parent.indexOfChild(self))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(self)) | [
"def",
"takeFromTree",
"(",
"self",
")",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"if",
"parent",
":",
"parent",
".",
"takeChild",
"(",
"parent",
".",
"indexOfChild",
"(",
"self",
")",
")",
"else",
":",
"tree",
".",
"takeTopLevelItem",
"(",
"tree",
".",
"indexOfTopLevelItem",
"(",
"self",
")",
")"
] | Takes this item from the tree. | [
"Takes",
"this",
"item",
"from",
"the",
"tree",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L548-L558 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.find | def find(self, *args, **kwargs):
"""
Run the pymongo find command against the default database and collection
and paginate the output to the screen.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
self.print_cursor(self.collection.find(*args, **kwargs)) | python | def find(self, *args, **kwargs):
"""
Run the pymongo find command against the default database and collection
and paginate the output to the screen.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
self.print_cursor(self.collection.find(*args, **kwargs)) | [
"def",
"find",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# print(f\"database.collection: '{self.database.name}.{self.collection.name}'\")",
"self",
".",
"print_cursor",
"(",
"self",
".",
"collection",
".",
"find",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Run the pymongo find command against the default database and collection
and paginate the output to the screen. | [
"Run",
"the",
"pymongo",
"find",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"paginate",
"the",
"output",
"to",
"the",
"screen",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L247-L253 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.find_one | def find_one(self, *args, **kwargs):
"""
Run the pymongo find_one command against the default database and collection
and paginate the output to the screen.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
self.print_doc(self.collection.find_one(*args, **kwargs)) | python | def find_one(self, *args, **kwargs):
"""
Run the pymongo find_one command against the default database and collection
and paginate the output to the screen.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
self.print_doc(self.collection.find_one(*args, **kwargs)) | [
"def",
"find_one",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# print(f\"database.collection: '{self.database.name}.{self.collection.name}'\")",
"self",
".",
"print_doc",
"(",
"self",
".",
"collection",
".",
"find_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Run the pymongo find_one command against the default database and collection
and paginate the output to the screen. | [
"Run",
"the",
"pymongo",
"find_one",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"paginate",
"the",
"output",
"to",
"the",
"screen",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L255-L261 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.insert_one | def insert_one(self, *args, **kwargs):
"""
Run the pymongo insert_one command against the default database and collection
and returne the inserted ID.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
result = self.collection.insert_one(*args, **kwargs)
return result.inserted_id | python | def insert_one(self, *args, **kwargs):
"""
Run the pymongo insert_one command against the default database and collection
and returne the inserted ID.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
result = self.collection.insert_one(*args, **kwargs)
return result.inserted_id | [
"def",
"insert_one",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# print(f\"database.collection: '{self.database.name}.{self.collection.name}'\")",
"result",
"=",
"self",
".",
"collection",
".",
"insert_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
".",
"inserted_id"
] | Run the pymongo insert_one command against the default database and collection
and returne the inserted ID. | [
"Run",
"the",
"pymongo",
"insert_one",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"returne",
"the",
"inserted",
"ID",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L263-L270 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.insert_many | def insert_many(self, *args, **kwargs):
"""
Run the pymongo insert_many command against the default database and collection
and return the list of inserted IDs.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
result = self.collection.insert_many(*args, **kwargs)
return result.inserted_ids | python | def insert_many(self, *args, **kwargs):
"""
Run the pymongo insert_many command against the default database and collection
and return the list of inserted IDs.
"""
# print(f"database.collection: '{self.database.name}.{self.collection.name}'")
result = self.collection.insert_many(*args, **kwargs)
return result.inserted_ids | [
"def",
"insert_many",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# print(f\"database.collection: '{self.database.name}.{self.collection.name}'\")",
"result",
"=",
"self",
".",
"collection",
".",
"insert_many",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
".",
"inserted_ids"
] | Run the pymongo insert_many command against the default database and collection
and return the list of inserted IDs. | [
"Run",
"the",
"pymongo",
"insert_many",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"return",
"the",
"list",
"of",
"inserted",
"IDs",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L272-L279 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.delete_one | def delete_one(self, *args, **kwargs):
"""
Run the pymongo delete_one command against the default database and collection
and return the deleted IDs.
"""
result = self.collection.delete_one(*args, **kwargs)
return result.raw_result | python | def delete_one(self, *args, **kwargs):
"""
Run the pymongo delete_one command against the default database and collection
and return the deleted IDs.
"""
result = self.collection.delete_one(*args, **kwargs)
return result.raw_result | [
"def",
"delete_one",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"collection",
".",
"delete_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
".",
"raw_result"
] | Run the pymongo delete_one command against the default database and collection
and return the deleted IDs. | [
"Run",
"the",
"pymongo",
"delete_one",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"return",
"the",
"deleted",
"IDs",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L281-L287 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.delete_many | def delete_many(self, *args, **kwargs):
"""
Run the pymongo delete_many command against the default database and collection
and return the deleted IDs.
"""
result = self.collection.delete_many(*args, **kwargs)
return result.raw_result | python | def delete_many(self, *args, **kwargs):
"""
Run the pymongo delete_many command against the default database and collection
and return the deleted IDs.
"""
result = self.collection.delete_many(*args, **kwargs)
return result.raw_result | [
"def",
"delete_many",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"collection",
".",
"delete_many",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
".",
"raw_result"
] | Run the pymongo delete_many command against the default database and collection
and return the deleted IDs. | [
"Run",
"the",
"pymongo",
"delete_many",
"command",
"against",
"the",
"default",
"database",
"and",
"collection",
"and",
"return",
"the",
"deleted",
"IDs",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L289-L295 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.count_documents | def count_documents(self, filter={}, *args, **kwargs):
"""
Count all the documents in a collection accurately
"""
result = self.collection.count_documents(filter, *args, **kwargs)
return result | python | def count_documents(self, filter={}, *args, **kwargs):
"""
Count all the documents in a collection accurately
"""
result = self.collection.count_documents(filter, *args, **kwargs)
return result | [
"def",
"count_documents",
"(",
"self",
",",
"filter",
"=",
"{",
"}",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"collection",
".",
"count_documents",
"(",
"filter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result"
] | Count all the documents in a collection accurately | [
"Count",
"all",
"the",
"documents",
"in",
"a",
"collection",
"accurately"
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L297-L302 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB._get_collections | def _get_collections(self, db_names=None):
"""
Internal function to return all the collections for every database.
include a list of db_names to filter the list of collections.
"""
if db_names:
db_list = db_names
else:
db_list = self.client.list_database_names()
for db_name in db_list:
db = self.client.get_database(db_name)
for col_name in db.list_collection_names():
size = db[col_name].g
yield f"{db_name}.{col_name}" | python | def _get_collections(self, db_names=None):
"""
Internal function to return all the collections for every database.
include a list of db_names to filter the list of collections.
"""
if db_names:
db_list = db_names
else:
db_list = self.client.list_database_names()
for db_name in db_list:
db = self.client.get_database(db_name)
for col_name in db.list_collection_names():
size = db[col_name].g
yield f"{db_name}.{col_name}" | [
"def",
"_get_collections",
"(",
"self",
",",
"db_names",
"=",
"None",
")",
":",
"if",
"db_names",
":",
"db_list",
"=",
"db_names",
"else",
":",
"db_list",
"=",
"self",
".",
"client",
".",
"list_database_names",
"(",
")",
"for",
"db_name",
"in",
"db_list",
":",
"db",
"=",
"self",
".",
"client",
".",
"get_database",
"(",
"db_name",
")",
"for",
"col_name",
"in",
"db",
".",
"list_collection_names",
"(",
")",
":",
"size",
"=",
"db",
"[",
"col_name",
"]",
".",
"g",
"yield",
"f\"{db_name}.{col_name}\""
] | Internal function to return all the collections for every database.
include a list of db_names to filter the list of collections. | [
"Internal",
"function",
"to",
"return",
"all",
"the",
"collections",
"for",
"every",
"database",
".",
"include",
"a",
"list",
"of",
"db_names",
"to",
"filter",
"the",
"list",
"of",
"collections",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L337-L351 | train |
jdrumgoole/mongodbshell | mongodbshell/__init__.py | MongoDB.pager | def pager(self, lines):
"""
Outputs lines to a terminal. It uses
`shutil.get_terminal_size` to determine the height of the terminal.
It expects an iterator that returns a line at a time and those lines
should be terminated by a valid newline sequence.
Behaviour is controlled by a number of external class properties.
`paginate` : Is on by default and triggers pagination. Without `paginate`
all output is written straight to the screen.
`output_file` : By assigning a name to this property we can ensure that
all output is sent to the corresponding file. Prompts are not output.
`pretty_print` : If this is set (default is on) then all output is
pretty printed with `pprint`. If it is off then the output is just
written to the screen.
`overlap` : The number of lines to overlap between one page and the
next.
:param lines:
:return: paginated output
"""
try:
line_count = 0
if self._output_filename:
print(f"Output is also going to '{self.output_file}'")
self._output_file = open(self._output_filename, "a+")
terminal_columns, terminal_lines = shutil.get_terminal_size(fallback=(80, 24))
lines_left = terminal_lines
for i, l in enumerate(lines, 1):
line_residue = 0
if self.line_numbers:
output_line = f"{i:<4} {l}"
else:
output_line = l
line_overflow = int(len(output_line) / terminal_columns)
if line_overflow:
line_residue = len(output_line) % terminal_columns
if line_overflow >= 1:
lines_left = lines_left - line_overflow
else:
lines_left = lines_left - 1
if line_residue > 1:
lines_left = lines_left - 1
# line_count = line_count + 1
print(output_line)
if self._output_file:
self._output_file.write(f"{l}\n")
self._output_file.flush()
#print(lines_left)
if (lines_left - self.overlap - 1) <= 0: # -1 to leave room for prompt
if self.paginate:
print("Hit Return to continue (q or quit to exit)", end="")
user_input = input()
if user_input.lower().strip() in ["q", "quit", "exit"]:
break
terminal_columns, terminal_lines = shutil.get_terminal_size(fallback=(80, 24))
lines_left = terminal_lines
# end for
if self._output_file:
self._output_file.close()
except KeyboardInterrupt:
print("ctrl-C...")
if self._output_file:
self._output_file.close() | python | def pager(self, lines):
"""
Outputs lines to a terminal. It uses
`shutil.get_terminal_size` to determine the height of the terminal.
It expects an iterator that returns a line at a time and those lines
should be terminated by a valid newline sequence.
Behaviour is controlled by a number of external class properties.
`paginate` : Is on by default and triggers pagination. Without `paginate`
all output is written straight to the screen.
`output_file` : By assigning a name to this property we can ensure that
all output is sent to the corresponding file. Prompts are not output.
`pretty_print` : If this is set (default is on) then all output is
pretty printed with `pprint`. If it is off then the output is just
written to the screen.
`overlap` : The number of lines to overlap between one page and the
next.
:param lines:
:return: paginated output
"""
try:
line_count = 0
if self._output_filename:
print(f"Output is also going to '{self.output_file}'")
self._output_file = open(self._output_filename, "a+")
terminal_columns, terminal_lines = shutil.get_terminal_size(fallback=(80, 24))
lines_left = terminal_lines
for i, l in enumerate(lines, 1):
line_residue = 0
if self.line_numbers:
output_line = f"{i:<4} {l}"
else:
output_line = l
line_overflow = int(len(output_line) / terminal_columns)
if line_overflow:
line_residue = len(output_line) % terminal_columns
if line_overflow >= 1:
lines_left = lines_left - line_overflow
else:
lines_left = lines_left - 1
if line_residue > 1:
lines_left = lines_left - 1
# line_count = line_count + 1
print(output_line)
if self._output_file:
self._output_file.write(f"{l}\n")
self._output_file.flush()
#print(lines_left)
if (lines_left - self.overlap - 1) <= 0: # -1 to leave room for prompt
if self.paginate:
print("Hit Return to continue (q or quit to exit)", end="")
user_input = input()
if user_input.lower().strip() in ["q", "quit", "exit"]:
break
terminal_columns, terminal_lines = shutil.get_terminal_size(fallback=(80, 24))
lines_left = terminal_lines
# end for
if self._output_file:
self._output_file.close()
except KeyboardInterrupt:
print("ctrl-C...")
if self._output_file:
self._output_file.close() | [
"def",
"pager",
"(",
"self",
",",
"lines",
")",
":",
"try",
":",
"line_count",
"=",
"0",
"if",
"self",
".",
"_output_filename",
":",
"print",
"(",
"f\"Output is also going to '{self.output_file}'\"",
")",
"self",
".",
"_output_file",
"=",
"open",
"(",
"self",
".",
"_output_filename",
",",
"\"a+\"",
")",
"terminal_columns",
",",
"terminal_lines",
"=",
"shutil",
".",
"get_terminal_size",
"(",
"fallback",
"=",
"(",
"80",
",",
"24",
")",
")",
"lines_left",
"=",
"terminal_lines",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"lines",
",",
"1",
")",
":",
"line_residue",
"=",
"0",
"if",
"self",
".",
"line_numbers",
":",
"output_line",
"=",
"f\"{i:<4} {l}\"",
"else",
":",
"output_line",
"=",
"l",
"line_overflow",
"=",
"int",
"(",
"len",
"(",
"output_line",
")",
"/",
"terminal_columns",
")",
"if",
"line_overflow",
":",
"line_residue",
"=",
"len",
"(",
"output_line",
")",
"%",
"terminal_columns",
"if",
"line_overflow",
">=",
"1",
":",
"lines_left",
"=",
"lines_left",
"-",
"line_overflow",
"else",
":",
"lines_left",
"=",
"lines_left",
"-",
"1",
"if",
"line_residue",
">",
"1",
":",
"lines_left",
"=",
"lines_left",
"-",
"1",
"# line_count = line_count + 1",
"print",
"(",
"output_line",
")",
"if",
"self",
".",
"_output_file",
":",
"self",
".",
"_output_file",
".",
"write",
"(",
"f\"{l}\\n\"",
")",
"self",
".",
"_output_file",
".",
"flush",
"(",
")",
"#print(lines_left)",
"if",
"(",
"lines_left",
"-",
"self",
".",
"overlap",
"-",
"1",
")",
"<=",
"0",
":",
"# -1 to leave room for prompt",
"if",
"self",
".",
"paginate",
":",
"print",
"(",
"\"Hit Return to continue (q or quit to exit)\"",
",",
"end",
"=",
"\"\"",
")",
"user_input",
"=",
"input",
"(",
")",
"if",
"user_input",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"in",
"[",
"\"q\"",
",",
"\"quit\"",
",",
"\"exit\"",
"]",
":",
"break",
"terminal_columns",
",",
"terminal_lines",
"=",
"shutil",
".",
"get_terminal_size",
"(",
"fallback",
"=",
"(",
"80",
",",
"24",
")",
")",
"lines_left",
"=",
"terminal_lines",
"# end for",
"if",
"self",
".",
"_output_file",
":",
"self",
".",
"_output_file",
".",
"close",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"\"ctrl-C...\"",
")",
"if",
"self",
".",
"_output_file",
":",
"self",
".",
"_output_file",
".",
"close",
"(",
")"
] | Outputs lines to a terminal. It uses
`shutil.get_terminal_size` to determine the height of the terminal.
It expects an iterator that returns a line at a time and those lines
should be terminated by a valid newline sequence.
Behaviour is controlled by a number of external class properties.
`paginate` : Is on by default and triggers pagination. Without `paginate`
all output is written straight to the screen.
`output_file` : By assigning a name to this property we can ensure that
all output is sent to the corresponding file. Prompts are not output.
`pretty_print` : If this is set (default is on) then all output is
pretty printed with `pprint`. If it is off then the output is just
written to the screen.
`overlap` : The number of lines to overlap between one page and the
next.
:param lines:
:return: paginated output | [
"Outputs",
"lines",
"to",
"a",
"terminal",
".",
"It",
"uses",
"shutil",
".",
"get_terminal_size",
"to",
"determine",
"the",
"height",
"of",
"the",
"terminal",
".",
"It",
"expects",
"an",
"iterator",
"that",
"returns",
"a",
"line",
"at",
"a",
"time",
"and",
"those",
"lines",
"should",
"be",
"terminated",
"by",
"a",
"valid",
"newline",
"sequence",
"."
] | 7e194247ea2adc1f124532935507cdffafa2c1f6 | https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L454-L536 | train |
bitesofcode/projexui | projexui/widgets/xorbbrowserwidget/xorbquerywidget.py | XOrbQueryWidget.groupQuery | def groupQuery( self ):
"""
Groups the selected items together into a sub query
"""
items = self.uiQueryTREE.selectedItems()
if ( not len(items) > 2 ):
return
if ( isinstance(items[-1], XJoinItem) ):
items = items[:-1]
tree = self.uiQueryTREE
parent = items[0].parent()
if ( not parent ):
parent = tree
preceeding = items[-1]
tree.blockSignals(True)
tree.setUpdatesEnabled(False)
grp_item = XQueryItem(parent, Q(), preceeding = preceeding)
for item in items:
parent = item.parent()
if ( not parent ):
tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
else:
parent.takeChild(parent.indexOfChild(item))
grp_item.addChild(item)
grp_item.update()
tree.blockSignals(False)
tree.setUpdatesEnabled(True) | python | def groupQuery( self ):
"""
Groups the selected items together into a sub query
"""
items = self.uiQueryTREE.selectedItems()
if ( not len(items) > 2 ):
return
if ( isinstance(items[-1], XJoinItem) ):
items = items[:-1]
tree = self.uiQueryTREE
parent = items[0].parent()
if ( not parent ):
parent = tree
preceeding = items[-1]
tree.blockSignals(True)
tree.setUpdatesEnabled(False)
grp_item = XQueryItem(parent, Q(), preceeding = preceeding)
for item in items:
parent = item.parent()
if ( not parent ):
tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
else:
parent.takeChild(parent.indexOfChild(item))
grp_item.addChild(item)
grp_item.update()
tree.blockSignals(False)
tree.setUpdatesEnabled(True) | [
"def",
"groupQuery",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"uiQueryTREE",
".",
"selectedItems",
"(",
")",
"if",
"(",
"not",
"len",
"(",
"items",
")",
">",
"2",
")",
":",
"return",
"if",
"(",
"isinstance",
"(",
"items",
"[",
"-",
"1",
"]",
",",
"XJoinItem",
")",
")",
":",
"items",
"=",
"items",
"[",
":",
"-",
"1",
"]",
"tree",
"=",
"self",
".",
"uiQueryTREE",
"parent",
"=",
"items",
"[",
"0",
"]",
".",
"parent",
"(",
")",
"if",
"(",
"not",
"parent",
")",
":",
"parent",
"=",
"tree",
"preceeding",
"=",
"items",
"[",
"-",
"1",
"]",
"tree",
".",
"blockSignals",
"(",
"True",
")",
"tree",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"grp_item",
"=",
"XQueryItem",
"(",
"parent",
",",
"Q",
"(",
")",
",",
"preceeding",
"=",
"preceeding",
")",
"for",
"item",
"in",
"items",
":",
"parent",
"=",
"item",
".",
"parent",
"(",
")",
"if",
"(",
"not",
"parent",
")",
":",
"tree",
".",
"takeTopLevelItem",
"(",
"tree",
".",
"indexOfTopLevelItem",
"(",
"item",
")",
")",
"else",
":",
"parent",
".",
"takeChild",
"(",
"parent",
".",
"indexOfChild",
"(",
"item",
")",
")",
"grp_item",
".",
"addChild",
"(",
"item",
")",
"grp_item",
".",
"update",
"(",
")",
"tree",
".",
"blockSignals",
"(",
"False",
")",
"tree",
".",
"setUpdatesEnabled",
"(",
"True",
")"
] | Groups the selected items together into a sub query | [
"Groups",
"the",
"selected",
"items",
"together",
"into",
"a",
"sub",
"query"
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbquerywidget.py#L575-L607 | train |
bitesofcode/projexui | projexui/widgets/xorbbrowserwidget/xorbquerywidget.py | XOrbQueryWidget.removeQuery | def removeQuery( self ):
"""
Removes the currently selected query.
"""
items = self.uiQueryTREE.selectedItems()
tree = self.uiQueryTREE
for item in items:
parent = item.parent()
if ( parent ):
parent.takeChild(parent.indexOfChild(item))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
self.setQuery(self.query()) | python | def removeQuery( self ):
"""
Removes the currently selected query.
"""
items = self.uiQueryTREE.selectedItems()
tree = self.uiQueryTREE
for item in items:
parent = item.parent()
if ( parent ):
parent.takeChild(parent.indexOfChild(item))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
self.setQuery(self.query()) | [
"def",
"removeQuery",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"uiQueryTREE",
".",
"selectedItems",
"(",
")",
"tree",
"=",
"self",
".",
"uiQueryTREE",
"for",
"item",
"in",
"items",
":",
"parent",
"=",
"item",
".",
"parent",
"(",
")",
"if",
"(",
"parent",
")",
":",
"parent",
".",
"takeChild",
"(",
"parent",
".",
"indexOfChild",
"(",
"item",
")",
")",
"else",
":",
"tree",
".",
"takeTopLevelItem",
"(",
"tree",
".",
"indexOfTopLevelItem",
"(",
"item",
")",
")",
"self",
".",
"setQuery",
"(",
"self",
".",
"query",
"(",
")",
")"
] | Removes the currently selected query. | [
"Removes",
"the",
"currently",
"selected",
"query",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbquerywidget.py#L631-L644 | train |
bitesofcode/projexui | projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py | XWizardBrowserDialog.runWizard | def runWizard( self ):
"""
Runs the current wizard.
"""
plugin = self.currentPlugin()
if ( plugin and plugin.runWizard(self) ):
self.accept() | python | def runWizard( self ):
"""
Runs the current wizard.
"""
plugin = self.currentPlugin()
if ( plugin and plugin.runWizard(self) ):
self.accept() | [
"def",
"runWizard",
"(",
"self",
")",
":",
"plugin",
"=",
"self",
".",
"currentPlugin",
"(",
")",
"if",
"(",
"plugin",
"and",
"plugin",
".",
"runWizard",
"(",
"self",
")",
")",
":",
"self",
".",
"accept",
"(",
")"
] | Runs the current wizard. | [
"Runs",
"the",
"current",
"wizard",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py#L133-L139 | train |
bitesofcode/projexui | projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py | XWizardBrowserDialog.showDescription | def showDescription( self ):
"""
Shows the description for the current plugin in the interface.
"""
plugin = self.currentPlugin()
if ( not plugin ):
self.uiDescriptionTXT.setText('')
else:
self.uiDescriptionTXT.setText(plugin.description()) | python | def showDescription( self ):
"""
Shows the description for the current plugin in the interface.
"""
plugin = self.currentPlugin()
if ( not plugin ):
self.uiDescriptionTXT.setText('')
else:
self.uiDescriptionTXT.setText(plugin.description()) | [
"def",
"showDescription",
"(",
"self",
")",
":",
"plugin",
"=",
"self",
".",
"currentPlugin",
"(",
")",
"if",
"(",
"not",
"plugin",
")",
":",
"self",
".",
"uiDescriptionTXT",
".",
"setText",
"(",
"''",
")",
"else",
":",
"self",
".",
"uiDescriptionTXT",
".",
"setText",
"(",
"plugin",
".",
"description",
"(",
")",
")"
] | Shows the description for the current plugin in the interface. | [
"Shows",
"the",
"description",
"for",
"the",
"current",
"plugin",
"in",
"the",
"interface",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py#L208-L216 | train |
bitesofcode/projexui | projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py | XWizardBrowserDialog.showWizards | def showWizards( self ):
"""
Show the wizards widget for the currently selected plugin.
"""
self.uiWizardTABLE.clear()
item = self.uiPluginTREE.currentItem()
if ( not (item and item.parent()) ):
plugins = []
else:
wlang = nativestring(item.parent().text(0))
wgrp = nativestring(item.text(0))
plugins = self.plugins(wlang, wgrp)
if ( not plugins ):
self.uiWizardTABLE.setEnabled(False)
self.uiDescriptionTXT.setEnabled(False)
return
self.uiWizardTABLE.setEnabled(True)
self.uiDescriptionTXT.setEnabled(True)
# determine the number of columns
colcount = len(plugins) / 2
if ( len(plugins) % 2 ):
colcount += 1
self.uiWizardTABLE.setRowCount(2)
self.uiWizardTABLE.setColumnCount( colcount )
header = self.uiWizardTABLE.verticalHeader()
header.setResizeMode(0, header.Stretch)
header.setResizeMode(1, header.Stretch)
header.setMinimumSectionSize(64)
header.hide()
header = self.uiWizardTABLE.horizontalHeader()
header.setMinimumSectionSize(64)
header.hide()
col = -1
row = 1
for plugin in plugins:
if ( row ):
col += 1
row = int(not row)
widget = PluginWidget(self, plugin)
self.uiWizardTABLE.setItem(row, col, QTableWidgetItem())
self.uiWizardTABLE.setCellWidget(row, col, widget) | python | def showWizards( self ):
"""
Show the wizards widget for the currently selected plugin.
"""
self.uiWizardTABLE.clear()
item = self.uiPluginTREE.currentItem()
if ( not (item and item.parent()) ):
plugins = []
else:
wlang = nativestring(item.parent().text(0))
wgrp = nativestring(item.text(0))
plugins = self.plugins(wlang, wgrp)
if ( not plugins ):
self.uiWizardTABLE.setEnabled(False)
self.uiDescriptionTXT.setEnabled(False)
return
self.uiWizardTABLE.setEnabled(True)
self.uiDescriptionTXT.setEnabled(True)
# determine the number of columns
colcount = len(plugins) / 2
if ( len(plugins) % 2 ):
colcount += 1
self.uiWizardTABLE.setRowCount(2)
self.uiWizardTABLE.setColumnCount( colcount )
header = self.uiWizardTABLE.verticalHeader()
header.setResizeMode(0, header.Stretch)
header.setResizeMode(1, header.Stretch)
header.setMinimumSectionSize(64)
header.hide()
header = self.uiWizardTABLE.horizontalHeader()
header.setMinimumSectionSize(64)
header.hide()
col = -1
row = 1
for plugin in plugins:
if ( row ):
col += 1
row = int(not row)
widget = PluginWidget(self, plugin)
self.uiWizardTABLE.setItem(row, col, QTableWidgetItem())
self.uiWizardTABLE.setCellWidget(row, col, widget) | [
"def",
"showWizards",
"(",
"self",
")",
":",
"self",
".",
"uiWizardTABLE",
".",
"clear",
"(",
")",
"item",
"=",
"self",
".",
"uiPluginTREE",
".",
"currentItem",
"(",
")",
"if",
"(",
"not",
"(",
"item",
"and",
"item",
".",
"parent",
"(",
")",
")",
")",
":",
"plugins",
"=",
"[",
"]",
"else",
":",
"wlang",
"=",
"nativestring",
"(",
"item",
".",
"parent",
"(",
")",
".",
"text",
"(",
"0",
")",
")",
"wgrp",
"=",
"nativestring",
"(",
"item",
".",
"text",
"(",
"0",
")",
")",
"plugins",
"=",
"self",
".",
"plugins",
"(",
"wlang",
",",
"wgrp",
")",
"if",
"(",
"not",
"plugins",
")",
":",
"self",
".",
"uiWizardTABLE",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"uiDescriptionTXT",
".",
"setEnabled",
"(",
"False",
")",
"return",
"self",
".",
"uiWizardTABLE",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"uiDescriptionTXT",
".",
"setEnabled",
"(",
"True",
")",
"# determine the number of columns\r",
"colcount",
"=",
"len",
"(",
"plugins",
")",
"/",
"2",
"if",
"(",
"len",
"(",
"plugins",
")",
"%",
"2",
")",
":",
"colcount",
"+=",
"1",
"self",
".",
"uiWizardTABLE",
".",
"setRowCount",
"(",
"2",
")",
"self",
".",
"uiWizardTABLE",
".",
"setColumnCount",
"(",
"colcount",
")",
"header",
"=",
"self",
".",
"uiWizardTABLE",
".",
"verticalHeader",
"(",
")",
"header",
".",
"setResizeMode",
"(",
"0",
",",
"header",
".",
"Stretch",
")",
"header",
".",
"setResizeMode",
"(",
"1",
",",
"header",
".",
"Stretch",
")",
"header",
".",
"setMinimumSectionSize",
"(",
"64",
")",
"header",
".",
"hide",
"(",
")",
"header",
"=",
"self",
".",
"uiWizardTABLE",
".",
"horizontalHeader",
"(",
")",
"header",
".",
"setMinimumSectionSize",
"(",
"64",
")",
"header",
".",
"hide",
"(",
")",
"col",
"=",
"-",
"1",
"row",
"=",
"1",
"for",
"plugin",
"in",
"plugins",
":",
"if",
"(",
"row",
")",
":",
"col",
"+=",
"1",
"row",
"=",
"int",
"(",
"not",
"row",
")",
"widget",
"=",
"PluginWidget",
"(",
"self",
",",
"plugin",
")",
"self",
".",
"uiWizardTABLE",
".",
"setItem",
"(",
"row",
",",
"col",
",",
"QTableWidgetItem",
"(",
")",
")",
"self",
".",
"uiWizardTABLE",
".",
"setCellWidget",
"(",
"row",
",",
"col",
",",
"widget",
")"
] | Show the wizards widget for the currently selected plugin. | [
"Show",
"the",
"wizards",
"widget",
"for",
"the",
"currently",
"selected",
"plugin",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xwizardbrowserdialog/xwizardbrowserdialog.py#L218-L268 | train |
bitesofcode/projexui | projexui/xcolorset.py | XColorSet.registerToDataTypes | def registerToDataTypes( cls ):
"""
Registers this class as a valid datatype for saving and loading via
the datatype system.
"""
from projexui.xdatatype import registerDataType
registerDataType(cls.__name__,
lambda pyvalue: pyvalue.toString(),
lambda qvariant: cls.fromString(unwrapVariant(qvariant))) | python | def registerToDataTypes( cls ):
"""
Registers this class as a valid datatype for saving and loading via
the datatype system.
"""
from projexui.xdatatype import registerDataType
registerDataType(cls.__name__,
lambda pyvalue: pyvalue.toString(),
lambda qvariant: cls.fromString(unwrapVariant(qvariant))) | [
"def",
"registerToDataTypes",
"(",
"cls",
")",
":",
"from",
"projexui",
".",
"xdatatype",
"import",
"registerDataType",
"registerDataType",
"(",
"cls",
".",
"__name__",
",",
"lambda",
"pyvalue",
":",
"pyvalue",
".",
"toString",
"(",
")",
",",
"lambda",
"qvariant",
":",
"cls",
".",
"fromString",
"(",
"unwrapVariant",
"(",
"qvariant",
")",
")",
")"
] | Registers this class as a valid datatype for saving and loading via
the datatype system. | [
"Registers",
"this",
"class",
"as",
"a",
"valid",
"datatype",
"for",
"saving",
"and",
"loading",
"via",
"the",
"datatype",
"system",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xcolorset.py#L184-L192 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelItem.enterEvent | def enterEvent(self, event):
"""
Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent>
"""
super(XViewPanelItem, self).enterEvent(event)
# store the hover state and mark for a repaint
self._hovered = True
self.update() | python | def enterEvent(self, event):
"""
Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent>
"""
super(XViewPanelItem, self).enterEvent(event)
# store the hover state and mark for a repaint
self._hovered = True
self.update() | [
"def",
"enterEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XViewPanelItem",
",",
"self",
")",
".",
"enterEvent",
"(",
"event",
")",
"# store the hover state and mark for a repaint",
"self",
".",
"_hovered",
"=",
"True",
"self",
".",
"update",
"(",
")"
] | Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent> | [
"Mark",
"the",
"hovered",
"state",
"as",
"being",
"true",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L134-L144 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelItem.leaveEvent | def leaveEvent(self, event):
"""
Mark the hovered state as being false.
:param event | <QtCore.QLeaveEvent>
"""
super(XViewPanelItem, self).leaveEvent(event)
# store the hover state and mark for a repaint
self._hovered = False
self.update() | python | def leaveEvent(self, event):
"""
Mark the hovered state as being false.
:param event | <QtCore.QLeaveEvent>
"""
super(XViewPanelItem, self).leaveEvent(event)
# store the hover state and mark for a repaint
self._hovered = False
self.update() | [
"def",
"leaveEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XViewPanelItem",
",",
"self",
")",
".",
"leaveEvent",
"(",
"event",
")",
"# store the hover state and mark for a repaint",
"self",
".",
"_hovered",
"=",
"False",
"self",
".",
"update",
"(",
")"
] | Mark the hovered state as being false.
:param event | <QtCore.QLeaveEvent> | [
"Mark",
"the",
"hovered",
"state",
"as",
"being",
"false",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L146-L156 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelItem.mousePressEvent | def mousePressEvent(self, event):
"""
Creates the mouse event for dragging or activating this tab.
:param event | <QtCore.QMousePressEvent>
"""
self._moveItemStarted = False
rect = QtCore.QRect(0, 0, 12, self.height())
# drag the tab off
if not self._locked and rect.contains(event.pos()):
tabbar = self.parent()
panel = tabbar.parent()
index = tabbar.indexOf(self)
view = panel.widget(index)
pixmap = QtGui.QPixmap.grabWidget(view)
drag = QtGui.QDrag(panel)
data = QtCore.QMimeData()
data.setData('x-application/xview/tabbed_view', QtCore.QByteArray(str(index)))
drag.setMimeData(data)
drag.setPixmap(pixmap)
if not drag.exec_():
cursor = QtGui.QCursor.pos()
geom = self.window().geometry()
if not geom.contains(cursor):
view.popout()
# allow moving indexes around
elif not self._locked and self.isActive():
self._moveItemStarted = self.parent().count() > 1
else:
self.activate()
super(XViewPanelItem, self).mousePressEvent(event) | python | def mousePressEvent(self, event):
"""
Creates the mouse event for dragging or activating this tab.
:param event | <QtCore.QMousePressEvent>
"""
self._moveItemStarted = False
rect = QtCore.QRect(0, 0, 12, self.height())
# drag the tab off
if not self._locked and rect.contains(event.pos()):
tabbar = self.parent()
panel = tabbar.parent()
index = tabbar.indexOf(self)
view = panel.widget(index)
pixmap = QtGui.QPixmap.grabWidget(view)
drag = QtGui.QDrag(panel)
data = QtCore.QMimeData()
data.setData('x-application/xview/tabbed_view', QtCore.QByteArray(str(index)))
drag.setMimeData(data)
drag.setPixmap(pixmap)
if not drag.exec_():
cursor = QtGui.QCursor.pos()
geom = self.window().geometry()
if not geom.contains(cursor):
view.popout()
# allow moving indexes around
elif not self._locked and self.isActive():
self._moveItemStarted = self.parent().count() > 1
else:
self.activate()
super(XViewPanelItem, self).mousePressEvent(event) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_moveItemStarted",
"=",
"False",
"rect",
"=",
"QtCore",
".",
"QRect",
"(",
"0",
",",
"0",
",",
"12",
",",
"self",
".",
"height",
"(",
")",
")",
"# drag the tab off",
"if",
"not",
"self",
".",
"_locked",
"and",
"rect",
".",
"contains",
"(",
"event",
".",
"pos",
"(",
")",
")",
":",
"tabbar",
"=",
"self",
".",
"parent",
"(",
")",
"panel",
"=",
"tabbar",
".",
"parent",
"(",
")",
"index",
"=",
"tabbar",
".",
"indexOf",
"(",
"self",
")",
"view",
"=",
"panel",
".",
"widget",
"(",
"index",
")",
"pixmap",
"=",
"QtGui",
".",
"QPixmap",
".",
"grabWidget",
"(",
"view",
")",
"drag",
"=",
"QtGui",
".",
"QDrag",
"(",
"panel",
")",
"data",
"=",
"QtCore",
".",
"QMimeData",
"(",
")",
"data",
".",
"setData",
"(",
"'x-application/xview/tabbed_view'",
",",
"QtCore",
".",
"QByteArray",
"(",
"str",
"(",
"index",
")",
")",
")",
"drag",
".",
"setMimeData",
"(",
"data",
")",
"drag",
".",
"setPixmap",
"(",
"pixmap",
")",
"if",
"not",
"drag",
".",
"exec_",
"(",
")",
":",
"cursor",
"=",
"QtGui",
".",
"QCursor",
".",
"pos",
"(",
")",
"geom",
"=",
"self",
".",
"window",
"(",
")",
".",
"geometry",
"(",
")",
"if",
"not",
"geom",
".",
"contains",
"(",
"cursor",
")",
":",
"view",
".",
"popout",
"(",
")",
"# allow moving indexes around",
"elif",
"not",
"self",
".",
"_locked",
"and",
"self",
".",
"isActive",
"(",
")",
":",
"self",
".",
"_moveItemStarted",
"=",
"self",
".",
"parent",
"(",
")",
".",
"count",
"(",
")",
">",
"1",
"else",
":",
"self",
".",
"activate",
"(",
")",
"super",
"(",
"XViewPanelItem",
",",
"self",
")",
".",
"mousePressEvent",
"(",
"event",
")"
] | Creates the mouse event for dragging or activating this tab.
:param event | <QtCore.QMousePressEvent> | [
"Creates",
"the",
"mouse",
"event",
"for",
"dragging",
"or",
"activating",
"this",
"tab",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L214-L251 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelItem.setFixedHeight | def setFixedHeight(self, height):
"""
Sets the fixed height for this item to the inputed height amount.
:param height | <int>
"""
super(XViewPanelItem, self).setFixedHeight(height)
self._dragLabel.setFixedHeight(height)
self._titleLabel.setFixedHeight(height)
self._searchButton.setFixedHeight(height)
self._closeButton.setFixedHeight(height) | python | def setFixedHeight(self, height):
"""
Sets the fixed height for this item to the inputed height amount.
:param height | <int>
"""
super(XViewPanelItem, self).setFixedHeight(height)
self._dragLabel.setFixedHeight(height)
self._titleLabel.setFixedHeight(height)
self._searchButton.setFixedHeight(height)
self._closeButton.setFixedHeight(height) | [
"def",
"setFixedHeight",
"(",
"self",
",",
"height",
")",
":",
"super",
"(",
"XViewPanelItem",
",",
"self",
")",
".",
"setFixedHeight",
"(",
"height",
")",
"self",
".",
"_dragLabel",
".",
"setFixedHeight",
"(",
"height",
")",
"self",
".",
"_titleLabel",
".",
"setFixedHeight",
"(",
"height",
")",
"self",
".",
"_searchButton",
".",
"setFixedHeight",
"(",
"height",
")",
"self",
".",
"_closeButton",
".",
"setFixedHeight",
"(",
"height",
")"
] | Sets the fixed height for this item to the inputed height amount.
:param height | <int> | [
"Sets",
"the",
"fixed",
"height",
"for",
"this",
"item",
"to",
"the",
"inputed",
"height",
"amount",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L274-L285 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.clear | def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self._currentIndex) | python | def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self._currentIndex) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"items",
"=",
"list",
"(",
"self",
".",
"items",
"(",
")",
")",
"for",
"item",
"in",
"items",
":",
"item",
".",
"close",
"(",
")",
"self",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"_currentIndex",
"=",
"-",
"1",
"self",
".",
"currentIndexChanged",
".",
"emit",
"(",
"self",
".",
"_currentIndex",
")"
] | Clears out all the items from this tab bar. | [
"Clears",
"out",
"all",
"the",
"items",
"from",
"this",
"tab",
"bar",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L407-L418 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.closeTab | def closeTab(self, item):
"""
Requests a close for the inputed tab item.
:param item | <XViewPanelItem>
"""
index = self.indexOf(item)
if index != -1:
self.tabCloseRequested.emit(index) | python | def closeTab(self, item):
"""
Requests a close for the inputed tab item.
:param item | <XViewPanelItem>
"""
index = self.indexOf(item)
if index != -1:
self.tabCloseRequested.emit(index) | [
"def",
"closeTab",
"(",
"self",
",",
"item",
")",
":",
"index",
"=",
"self",
".",
"indexOf",
"(",
"item",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"self",
".",
"tabCloseRequested",
".",
"emit",
"(",
"index",
")"
] | Requests a close for the inputed tab item.
:param item | <XViewPanelItem> | [
"Requests",
"a",
"close",
"for",
"the",
"inputed",
"tab",
"item",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L420-L428 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.items | def items(self):
"""
Returns a list of all the items associated with this panel.
:return [<XViewPanelItem>, ..]
"""
output = []
for i in xrange(self.layout().count()):
item = self.layout().itemAt(i)
try:
widget = item.widget()
except AttributeError:
break
if isinstance(widget, XViewPanelItem):
output.append(widget)
else:
break
return output | python | def items(self):
"""
Returns a list of all the items associated with this panel.
:return [<XViewPanelItem>, ..]
"""
output = []
for i in xrange(self.layout().count()):
item = self.layout().itemAt(i)
try:
widget = item.widget()
except AttributeError:
break
if isinstance(widget, XViewPanelItem):
output.append(widget)
else:
break
return output | [
"def",
"items",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"layout",
"(",
")",
".",
"count",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"layout",
"(",
")",
".",
"itemAt",
"(",
"i",
")",
"try",
":",
"widget",
"=",
"item",
".",
"widget",
"(",
")",
"except",
"AttributeError",
":",
"break",
"if",
"isinstance",
"(",
"widget",
",",
"XViewPanelItem",
")",
":",
"output",
".",
"append",
"(",
"widget",
")",
"else",
":",
"break",
"return",
"output"
] | Returns a list of all the items associated with this panel.
:return [<XViewPanelItem>, ..] | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"items",
"associated",
"with",
"this",
"panel",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L488-L506 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.moveTab | def moveTab(self, fromIndex, toIndex):
"""
Moves the tab from the inputed index to the given index.
:param fromIndex | <int>
toIndex | <int>
"""
try:
item = self.layout().itemAt(fromIndex)
self.layout().insertItem(toIndex, item.widget())
except StandardError:
pass | python | def moveTab(self, fromIndex, toIndex):
"""
Moves the tab from the inputed index to the given index.
:param fromIndex | <int>
toIndex | <int>
"""
try:
item = self.layout().itemAt(fromIndex)
self.layout().insertItem(toIndex, item.widget())
except StandardError:
pass | [
"def",
"moveTab",
"(",
"self",
",",
"fromIndex",
",",
"toIndex",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"layout",
"(",
")",
".",
"itemAt",
"(",
"fromIndex",
")",
"self",
".",
"layout",
"(",
")",
".",
"insertItem",
"(",
"toIndex",
",",
"item",
".",
"widget",
"(",
")",
")",
"except",
"StandardError",
":",
"pass"
] | Moves the tab from the inputed index to the given index.
:param fromIndex | <int>
toIndex | <int> | [
"Moves",
"the",
"tab",
"from",
"the",
"inputed",
"index",
"to",
"the",
"given",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L508-L519 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.removeTab | def removeTab(self, index):
"""
Removes the tab at the inputed index.
:param index | <int>
"""
curr_index = self.currentIndex()
items = list(self.items())
item = items[index]
item.close()
if index <= curr_index:
self._currentIndex -= 1 | python | def removeTab(self, index):
"""
Removes the tab at the inputed index.
:param index | <int>
"""
curr_index = self.currentIndex()
items = list(self.items())
item = items[index]
item.close()
if index <= curr_index:
self._currentIndex -= 1 | [
"def",
"removeTab",
"(",
"self",
",",
"index",
")",
":",
"curr_index",
"=",
"self",
".",
"currentIndex",
"(",
")",
"items",
"=",
"list",
"(",
"self",
".",
"items",
"(",
")",
")",
"item",
"=",
"items",
"[",
"index",
"]",
"item",
".",
"close",
"(",
")",
"if",
"index",
"<=",
"curr_index",
":",
"self",
".",
"_currentIndex",
"-=",
"1"
] | Removes the tab at the inputed index.
:param index | <int> | [
"Removes",
"the",
"tab",
"at",
"the",
"inputed",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L546-L558 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.requestAddMenu | def requestAddMenu(self):
"""
Emits the add requested signal.
"""
point = QtCore.QPoint(self._addButton.width(), 0)
point = self._addButton.mapToGlobal(point)
self.addRequested.emit(point) | python | def requestAddMenu(self):
"""
Emits the add requested signal.
"""
point = QtCore.QPoint(self._addButton.width(), 0)
point = self._addButton.mapToGlobal(point)
self.addRequested.emit(point) | [
"def",
"requestAddMenu",
"(",
"self",
")",
":",
"point",
"=",
"QtCore",
".",
"QPoint",
"(",
"self",
".",
"_addButton",
".",
"width",
"(",
")",
",",
"0",
")",
"point",
"=",
"self",
".",
"_addButton",
".",
"mapToGlobal",
"(",
"point",
")",
"self",
".",
"addRequested",
".",
"emit",
"(",
"point",
")"
] | Emits the add requested signal. | [
"Emits",
"the",
"add",
"requested",
"signal",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L560-L566 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.requestOptionsMenu | def requestOptionsMenu(self):
"""
Emits the options request signal.
"""
point = QtCore.QPoint(0, self._optionsButton.height())
point = self._optionsButton.mapToGlobal(point)
self.optionsRequested.emit(point) | python | def requestOptionsMenu(self):
"""
Emits the options request signal.
"""
point = QtCore.QPoint(0, self._optionsButton.height())
point = self._optionsButton.mapToGlobal(point)
self.optionsRequested.emit(point) | [
"def",
"requestOptionsMenu",
"(",
"self",
")",
":",
"point",
"=",
"QtCore",
".",
"QPoint",
"(",
"0",
",",
"self",
".",
"_optionsButton",
".",
"height",
"(",
")",
")",
"point",
"=",
"self",
".",
"_optionsButton",
".",
"mapToGlobal",
"(",
"point",
")",
"self",
".",
"optionsRequested",
".",
"emit",
"(",
"point",
")"
] | Emits the options request signal. | [
"Emits",
"the",
"options",
"request",
"signal",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L568-L574 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.setCurrentIndex | def setCurrentIndex(self, index):
"""
Sets the current item to the item at the inputed index.
:param index | <int>
"""
if self._currentIndex == index:
return
self._currentIndex = index
self.currentIndexChanged.emit(index)
for i, item in enumerate(self.items()):
item.setMenuEnabled(i == index)
self.repaint() | python | def setCurrentIndex(self, index):
"""
Sets the current item to the item at the inputed index.
:param index | <int>
"""
if self._currentIndex == index:
return
self._currentIndex = index
self.currentIndexChanged.emit(index)
for i, item in enumerate(self.items()):
item.setMenuEnabled(i == index)
self.repaint() | [
"def",
"setCurrentIndex",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"_currentIndex",
"==",
"index",
":",
"return",
"self",
".",
"_currentIndex",
"=",
"index",
"self",
".",
"currentIndexChanged",
".",
"emit",
"(",
"index",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"items",
"(",
")",
")",
":",
"item",
".",
"setMenuEnabled",
"(",
"i",
"==",
"index",
")",
"self",
".",
"repaint",
"(",
")"
] | Sets the current item to the item at the inputed index.
:param index | <int> | [
"Sets",
"the",
"current",
"item",
"to",
"the",
"item",
"at",
"the",
"inputed",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L576-L590 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.setFixedHeight | def setFixedHeight(self, height):
"""
Sets the fixed height for this bar to the inputed height.
:param height | <int>
"""
super(XViewPanelBar, self).setFixedHeight(height)
# update the layout
if self.layout():
for i in xrange(self.layout().count()):
try:
self.layout().itemAt(i).widget().setFixedHeight(height)
except StandardError:
continue | python | def setFixedHeight(self, height):
"""
Sets the fixed height for this bar to the inputed height.
:param height | <int>
"""
super(XViewPanelBar, self).setFixedHeight(height)
# update the layout
if self.layout():
for i in xrange(self.layout().count()):
try:
self.layout().itemAt(i).widget().setFixedHeight(height)
except StandardError:
continue | [
"def",
"setFixedHeight",
"(",
"self",
",",
"height",
")",
":",
"super",
"(",
"XViewPanelBar",
",",
"self",
")",
".",
"setFixedHeight",
"(",
"height",
")",
"# update the layout",
"if",
"self",
".",
"layout",
"(",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"layout",
"(",
")",
".",
"count",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"layout",
"(",
")",
".",
"itemAt",
"(",
"i",
")",
".",
"widget",
"(",
")",
".",
"setFixedHeight",
"(",
"height",
")",
"except",
"StandardError",
":",
"continue"
] | Sets the fixed height for this bar to the inputed height.
:param height | <int> | [
"Sets",
"the",
"fixed",
"height",
"for",
"this",
"bar",
"to",
"the",
"inputed",
"height",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L610-L624 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanelBar.setTabText | def setTabText(self, index, text):
"""
Returns the text for the tab at the inputed index.
:param index | <int>
:return <str>
"""
try:
self.items()[index].setText(text)
except IndexError:
pass | python | def setTabText(self, index, text):
"""
Returns the text for the tab at the inputed index.
:param index | <int>
:return <str>
"""
try:
self.items()[index].setText(text)
except IndexError:
pass | [
"def",
"setTabText",
"(",
"self",
",",
"index",
",",
"text",
")",
":",
"try",
":",
"self",
".",
"items",
"(",
")",
"[",
"index",
"]",
".",
"setText",
"(",
"text",
")",
"except",
"IndexError",
":",
"pass"
] | Returns the text for the tab at the inputed index.
:param index | <int>
:return <str> | [
"Returns",
"the",
"text",
"for",
"the",
"tab",
"at",
"the",
"inputed",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L626-L637 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.closePanel | def closePanel(self):
"""
Closes a full view panel.
"""
# make sure we can close all the widgets in the view first
for i in range(self.count()):
if not self.widget(i).canClose():
return False
container = self.parentWidget()
viewWidget = self.viewWidget()
# close all the child views
for i in xrange(self.count() - 1, -1, -1):
self.widget(i).close()
self.tabBar().clear()
if isinstance(container, XSplitter):
parent_container = container.parentWidget()
if container.count() == 2:
if isinstance(parent_container, XSplitter):
sizes = parent_container.sizes()
widget = container.widget(int(not container.indexOf(self)))
index = parent_container.indexOf(container)
parent_container.insertWidget(index, widget)
container.setParent(None)
container.close()
container.deleteLater()
parent_container.setSizes(sizes)
elif parent_container.parentWidget() == viewWidget:
widget = container.widget(int(not container.indexOf(self)))
widget.setParent(viewWidget)
if projexui.QT_WRAPPER == 'PySide':
_ = viewWidget.takeWidget()
else:
old_widget = viewWidget.widget()
old_widget.setParent(None)
old_widget.close()
old_widget.deleteLater()
QtGui.QApplication.instance().processEvents()
viewWidget.setWidget(widget)
else:
container.setParent(None)
container.close()
container.deleteLater()
else:
self.setFocus()
self._hintLabel.setText(self.hint())
self._hintLabel.show()
return True | python | def closePanel(self):
"""
Closes a full view panel.
"""
# make sure we can close all the widgets in the view first
for i in range(self.count()):
if not self.widget(i).canClose():
return False
container = self.parentWidget()
viewWidget = self.viewWidget()
# close all the child views
for i in xrange(self.count() - 1, -1, -1):
self.widget(i).close()
self.tabBar().clear()
if isinstance(container, XSplitter):
parent_container = container.parentWidget()
if container.count() == 2:
if isinstance(parent_container, XSplitter):
sizes = parent_container.sizes()
widget = container.widget(int(not container.indexOf(self)))
index = parent_container.indexOf(container)
parent_container.insertWidget(index, widget)
container.setParent(None)
container.close()
container.deleteLater()
parent_container.setSizes(sizes)
elif parent_container.parentWidget() == viewWidget:
widget = container.widget(int(not container.indexOf(self)))
widget.setParent(viewWidget)
if projexui.QT_WRAPPER == 'PySide':
_ = viewWidget.takeWidget()
else:
old_widget = viewWidget.widget()
old_widget.setParent(None)
old_widget.close()
old_widget.deleteLater()
QtGui.QApplication.instance().processEvents()
viewWidget.setWidget(widget)
else:
container.setParent(None)
container.close()
container.deleteLater()
else:
self.setFocus()
self._hintLabel.setText(self.hint())
self._hintLabel.show()
return True | [
"def",
"closePanel",
"(",
"self",
")",
":",
"# make sure we can close all the widgets in the view first",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"widget",
"(",
"i",
")",
".",
"canClose",
"(",
")",
":",
"return",
"False",
"container",
"=",
"self",
".",
"parentWidget",
"(",
")",
"viewWidget",
"=",
"self",
".",
"viewWidget",
"(",
")",
"# close all the child views",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"count",
"(",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"self",
".",
"widget",
"(",
"i",
")",
".",
"close",
"(",
")",
"self",
".",
"tabBar",
"(",
")",
".",
"clear",
"(",
")",
"if",
"isinstance",
"(",
"container",
",",
"XSplitter",
")",
":",
"parent_container",
"=",
"container",
".",
"parentWidget",
"(",
")",
"if",
"container",
".",
"count",
"(",
")",
"==",
"2",
":",
"if",
"isinstance",
"(",
"parent_container",
",",
"XSplitter",
")",
":",
"sizes",
"=",
"parent_container",
".",
"sizes",
"(",
")",
"widget",
"=",
"container",
".",
"widget",
"(",
"int",
"(",
"not",
"container",
".",
"indexOf",
"(",
"self",
")",
")",
")",
"index",
"=",
"parent_container",
".",
"indexOf",
"(",
"container",
")",
"parent_container",
".",
"insertWidget",
"(",
"index",
",",
"widget",
")",
"container",
".",
"setParent",
"(",
"None",
")",
"container",
".",
"close",
"(",
")",
"container",
".",
"deleteLater",
"(",
")",
"parent_container",
".",
"setSizes",
"(",
"sizes",
")",
"elif",
"parent_container",
".",
"parentWidget",
"(",
")",
"==",
"viewWidget",
":",
"widget",
"=",
"container",
".",
"widget",
"(",
"int",
"(",
"not",
"container",
".",
"indexOf",
"(",
"self",
")",
")",
")",
"widget",
".",
"setParent",
"(",
"viewWidget",
")",
"if",
"projexui",
".",
"QT_WRAPPER",
"==",
"'PySide'",
":",
"_",
"=",
"viewWidget",
".",
"takeWidget",
"(",
")",
"else",
":",
"old_widget",
"=",
"viewWidget",
".",
"widget",
"(",
")",
"old_widget",
".",
"setParent",
"(",
"None",
")",
"old_widget",
".",
"close",
"(",
")",
"old_widget",
".",
"deleteLater",
"(",
")",
"QtGui",
".",
"QApplication",
".",
"instance",
"(",
")",
".",
"processEvents",
"(",
")",
"viewWidget",
".",
"setWidget",
"(",
"widget",
")",
"else",
":",
"container",
".",
"setParent",
"(",
"None",
")",
"container",
".",
"close",
"(",
")",
"container",
".",
"deleteLater",
"(",
")",
"else",
":",
"self",
".",
"setFocus",
"(",
")",
"self",
".",
"_hintLabel",
".",
"setText",
"(",
"self",
".",
"hint",
"(",
")",
")",
"self",
".",
"_hintLabel",
".",
"show",
"(",
")",
"return",
"True"
] | Closes a full view panel. | [
"Closes",
"a",
"full",
"view",
"panel",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L935-L993 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.ensureVisible | def ensureVisible(self, viewType):
"""
Find and switch to the first tab of the specified view type. If the
type does not exist, add it.
:param viewType | <subclass of XView>
:return <XView> || None
"""
# make sure we're not trying to switch to the same type
view = self.currentView()
if type(view) == viewType:
return view
self.blockSignals(True)
self.setUpdatesEnabled(False)
for i in xrange(self.count()):
widget = self.widget(i)
if type(widget) == viewType:
self.setCurrentIndex(i)
view = widget
break
else:
view = self.addView(viewType)
self.blockSignals(False)
self.setUpdatesEnabled(True)
return view | python | def ensureVisible(self, viewType):
"""
Find and switch to the first tab of the specified view type. If the
type does not exist, add it.
:param viewType | <subclass of XView>
:return <XView> || None
"""
# make sure we're not trying to switch to the same type
view = self.currentView()
if type(view) == viewType:
return view
self.blockSignals(True)
self.setUpdatesEnabled(False)
for i in xrange(self.count()):
widget = self.widget(i)
if type(widget) == viewType:
self.setCurrentIndex(i)
view = widget
break
else:
view = self.addView(viewType)
self.blockSignals(False)
self.setUpdatesEnabled(True)
return view | [
"def",
"ensureVisible",
"(",
"self",
",",
"viewType",
")",
":",
"# make sure we're not trying to switch to the same type",
"view",
"=",
"self",
".",
"currentView",
"(",
")",
"if",
"type",
"(",
"view",
")",
"==",
"viewType",
":",
"return",
"view",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"widget",
"=",
"self",
".",
"widget",
"(",
"i",
")",
"if",
"type",
"(",
"widget",
")",
"==",
"viewType",
":",
"self",
".",
"setCurrentIndex",
"(",
"i",
")",
"view",
"=",
"widget",
"break",
"else",
":",
"view",
"=",
"self",
".",
"addView",
"(",
"viewType",
")",
"self",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"return",
"view"
] | Find and switch to the first tab of the specified view type. If the
type does not exist, add it.
:param viewType | <subclass of XView>
:return <XView> || None | [
"Find",
"and",
"switch",
"to",
"the",
"first",
"tab",
"of",
"the",
"specified",
"view",
"type",
".",
"If",
"the",
"type",
"does",
"not",
"exist",
"add",
"it",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1121-L1150 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.insertTab | def insertTab(self, index, widget, title):
"""
Inserts a new tab for this widget.
:param index | <int>
widget | <QtGui.QWidget>
title | <str>
"""
self.insertWidget(index, widget)
tab = self.tabBar().insertTab(index, title)
tab.titleChanged.connect(widget.setWindowTitle) | python | def insertTab(self, index, widget, title):
"""
Inserts a new tab for this widget.
:param index | <int>
widget | <QtGui.QWidget>
title | <str>
"""
self.insertWidget(index, widget)
tab = self.tabBar().insertTab(index, title)
tab.titleChanged.connect(widget.setWindowTitle) | [
"def",
"insertTab",
"(",
"self",
",",
"index",
",",
"widget",
",",
"title",
")",
":",
"self",
".",
"insertWidget",
"(",
"index",
",",
"widget",
")",
"tab",
"=",
"self",
".",
"tabBar",
"(",
")",
".",
"insertTab",
"(",
"index",
",",
"title",
")",
"tab",
".",
"titleChanged",
".",
"connect",
"(",
"widget",
".",
"setWindowTitle",
")"
] | Inserts a new tab for this widget.
:param index | <int>
widget | <QtGui.QWidget>
title | <str> | [
"Inserts",
"a",
"new",
"tab",
"for",
"this",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1225-L1235 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.markCurrentChanged | def markCurrentChanged(self):
"""
Marks that the current widget has changed.
"""
view = self.currentView()
if view:
view.setCurrent()
self.setFocus()
view.setFocus()
self._hintLabel.hide()
else:
self._hintLabel.show()
self._hintLabel.setText(self.hint())
if not self.count():
self.tabBar().clear()
self.adjustSizeConstraint() | python | def markCurrentChanged(self):
"""
Marks that the current widget has changed.
"""
view = self.currentView()
if view:
view.setCurrent()
self.setFocus()
view.setFocus()
self._hintLabel.hide()
else:
self._hintLabel.show()
self._hintLabel.setText(self.hint())
if not self.count():
self.tabBar().clear()
self.adjustSizeConstraint() | [
"def",
"markCurrentChanged",
"(",
"self",
")",
":",
"view",
"=",
"self",
".",
"currentView",
"(",
")",
"if",
"view",
":",
"view",
".",
"setCurrent",
"(",
")",
"self",
".",
"setFocus",
"(",
")",
"view",
".",
"setFocus",
"(",
")",
"self",
".",
"_hintLabel",
".",
"hide",
"(",
")",
"else",
":",
"self",
".",
"_hintLabel",
".",
"show",
"(",
")",
"self",
".",
"_hintLabel",
".",
"setText",
"(",
"self",
".",
"hint",
"(",
")",
")",
"if",
"not",
"self",
".",
"count",
"(",
")",
":",
"self",
".",
"tabBar",
"(",
")",
".",
"clear",
"(",
")",
"self",
".",
"adjustSizeConstraint",
"(",
")"
] | Marks that the current widget has changed. | [
"Marks",
"that",
"the",
"current",
"widget",
"has",
"changed",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1254-L1271 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.refreshTitles | def refreshTitles(self):
"""
Refreshes the titles for each view within this tab panel.
"""
for index in range(self.count()):
widget = self.widget(index)
self.setTabText(index, widget.windowTitle()) | python | def refreshTitles(self):
"""
Refreshes the titles for each view within this tab panel.
"""
for index in range(self.count()):
widget = self.widget(index)
self.setTabText(index, widget.windowTitle()) | [
"def",
"refreshTitles",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"widget",
"=",
"self",
".",
"widget",
"(",
"index",
")",
"self",
".",
"setTabText",
"(",
"index",
",",
"widget",
".",
"windowTitle",
"(",
")",
")"
] | Refreshes the titles for each view within this tab panel. | [
"Refreshes",
"the",
"titles",
"for",
"each",
"view",
"within",
"this",
"tab",
"panel",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1301-L1307 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.setCurrentIndex | def setCurrentIndex(self, index):
"""
Sets the current index on self and on the tab bar to keep the two insync.
:param index | <int>
"""
super(XViewPanel, self).setCurrentIndex(index)
self.tabBar().setCurrentIndex(index) | python | def setCurrentIndex(self, index):
"""
Sets the current index on self and on the tab bar to keep the two insync.
:param index | <int>
"""
super(XViewPanel, self).setCurrentIndex(index)
self.tabBar().setCurrentIndex(index) | [
"def",
"setCurrentIndex",
"(",
"self",
",",
"index",
")",
":",
"super",
"(",
"XViewPanel",
",",
"self",
")",
".",
"setCurrentIndex",
"(",
"index",
")",
"self",
".",
"tabBar",
"(",
")",
".",
"setCurrentIndex",
"(",
"index",
")"
] | Sets the current index on self and on the tab bar to keep the two insync.
:param index | <int> | [
"Sets",
"the",
"current",
"index",
"on",
"self",
"and",
"on",
"the",
"tab",
"bar",
"to",
"keep",
"the",
"two",
"insync",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1452-L1459 | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | XViewPanel.switchCurrentView | def switchCurrentView(self, viewType):
"""
Swaps the current tab view for the inputed action's type.
:param action | <QAction>
:return <XView> || None
"""
if not self.count():
return self.addView(viewType)
# make sure we're not trying to switch to the same type
view = self.currentView()
if type(view) == viewType:
return view
# create a new view and close the old one
self.blockSignals(True)
self.setUpdatesEnabled(False)
# create the new view
index = self.indexOf(view)
if not view.close():
return None
#else:
# self.tabBar().removeTab(index)
index = self.currentIndex()
new_view = viewType.createInstance(self.viewWidget(), self.viewWidget())
# add the new view
self.insertTab(index, new_view, new_view.windowTitle())
self.blockSignals(False)
self.setUpdatesEnabled(True)
self.setCurrentIndex(index)
return new_view | python | def switchCurrentView(self, viewType):
"""
Swaps the current tab view for the inputed action's type.
:param action | <QAction>
:return <XView> || None
"""
if not self.count():
return self.addView(viewType)
# make sure we're not trying to switch to the same type
view = self.currentView()
if type(view) == viewType:
return view
# create a new view and close the old one
self.blockSignals(True)
self.setUpdatesEnabled(False)
# create the new view
index = self.indexOf(view)
if not view.close():
return None
#else:
# self.tabBar().removeTab(index)
index = self.currentIndex()
new_view = viewType.createInstance(self.viewWidget(), self.viewWidget())
# add the new view
self.insertTab(index, new_view, new_view.windowTitle())
self.blockSignals(False)
self.setUpdatesEnabled(True)
self.setCurrentIndex(index)
return new_view | [
"def",
"switchCurrentView",
"(",
"self",
",",
"viewType",
")",
":",
"if",
"not",
"self",
".",
"count",
"(",
")",
":",
"return",
"self",
".",
"addView",
"(",
"viewType",
")",
"# make sure we're not trying to switch to the same type",
"view",
"=",
"self",
".",
"currentView",
"(",
")",
"if",
"type",
"(",
"view",
")",
"==",
"viewType",
":",
"return",
"view",
"# create a new view and close the old one",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"# create the new view",
"index",
"=",
"self",
".",
"indexOf",
"(",
"view",
")",
"if",
"not",
"view",
".",
"close",
"(",
")",
":",
"return",
"None",
"#else:",
"# self.tabBar().removeTab(index)",
"index",
"=",
"self",
".",
"currentIndex",
"(",
")",
"new_view",
"=",
"viewType",
".",
"createInstance",
"(",
"self",
".",
"viewWidget",
"(",
")",
",",
"self",
".",
"viewWidget",
"(",
")",
")",
"# add the new view",
"self",
".",
"insertTab",
"(",
"index",
",",
"new_view",
",",
"new_view",
".",
"windowTitle",
"(",
")",
")",
"self",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"self",
".",
"setCurrentIndex",
"(",
"index",
")",
"return",
"new_view"
] | Swaps the current tab view for the inputed action's type.
:param action | <QAction>
:return <XView> || None | [
"Swaps",
"the",
"current",
"tab",
"view",
"for",
"the",
"inputed",
"action",
"s",
"type",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1503-L1540 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | ReadMixin.keys | async def keys(self, prefix, *,
dc=None, separator=None, watch=None, consistency=None):
"""Returns a list of the keys under the given prefix
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is list of keys
For example, listing ``/web/`` with a ``/`` separator may return::
[
"/web/bar",
"/web/foo",
"/web/subdir/"
]
"""
response = await self._read(prefix,
dc=dc,
separator=separator,
keys=True,
watch=watch,
consistency=consistency)
return consul(response) | python | async def keys(self, prefix, *,
dc=None, separator=None, watch=None, consistency=None):
"""Returns a list of the keys under the given prefix
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is list of keys
For example, listing ``/web/`` with a ``/`` separator may return::
[
"/web/bar",
"/web/foo",
"/web/subdir/"
]
"""
response = await self._read(prefix,
dc=dc,
separator=separator,
keys=True,
watch=watch,
consistency=consistency)
return consul(response) | [
"async",
"def",
"keys",
"(",
"self",
",",
"prefix",
",",
"*",
",",
"dc",
"=",
"None",
",",
"separator",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"response",
"=",
"await",
"self",
".",
"_read",
"(",
"prefix",
",",
"dc",
"=",
"dc",
",",
"separator",
"=",
"separator",
",",
"keys",
"=",
"True",
",",
"watch",
"=",
"watch",
",",
"consistency",
"=",
"consistency",
")",
"return",
"consul",
"(",
"response",
")"
] | Returns a list of the keys under the given prefix
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is list of keys
For example, listing ``/web/`` with a ``/`` separator may return::
[
"/web/bar",
"/web/foo",
"/web/subdir/"
] | [
"Returns",
"a",
"list",
"of",
"the",
"keys",
"under",
"the",
"given",
"prefix"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L39-L68 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | ReadMixin.get_tree | async def get_tree(self, prefix, *,
dc=None, separator=None, watch=None, consistency=None):
"""Gets all keys with a prefix of Key during the transaction.
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list of values
This does not fail the transaction if the Key doesn't exist. Not
all keys may be present in the results if ACLs do not permit them
to be read.
"""
response = await self._read(prefix,
dc=dc,
recurse=True,
separator=separator,
watch=watch,
consistency=consistency)
result = response.body
for data in result:
data["Value"] = decode_value(data["Value"], data["Flags"])
return consul(result, meta=extract_meta(response.headers)) | python | async def get_tree(self, prefix, *,
dc=None, separator=None, watch=None, consistency=None):
"""Gets all keys with a prefix of Key during the transaction.
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list of values
This does not fail the transaction if the Key doesn't exist. Not
all keys may be present in the results if ACLs do not permit them
to be read.
"""
response = await self._read(prefix,
dc=dc,
recurse=True,
separator=separator,
watch=watch,
consistency=consistency)
result = response.body
for data in result:
data["Value"] = decode_value(data["Value"], data["Flags"])
return consul(result, meta=extract_meta(response.headers)) | [
"async",
"def",
"get_tree",
"(",
"self",
",",
"prefix",
",",
"*",
",",
"dc",
"=",
"None",
",",
"separator",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"response",
"=",
"await",
"self",
".",
"_read",
"(",
"prefix",
",",
"dc",
"=",
"dc",
",",
"recurse",
"=",
"True",
",",
"separator",
"=",
"separator",
",",
"watch",
"=",
"watch",
",",
"consistency",
"=",
"consistency",
")",
"result",
"=",
"response",
".",
"body",
"for",
"data",
"in",
"result",
":",
"data",
"[",
"\"Value\"",
"]",
"=",
"decode_value",
"(",
"data",
"[",
"\"Value\"",
"]",
",",
"data",
"[",
"\"Flags\"",
"]",
")",
"return",
"consul",
"(",
"result",
",",
"meta",
"=",
"extract_meta",
"(",
"response",
".",
"headers",
")",
")"
] | Gets all keys with a prefix of Key during the transaction.
Parameters:
prefix (str): Prefix to fetch
separator (str): List only up to a given separator
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list of values
This does not fail the transaction if the Key doesn't exist. Not
all keys may be present in the results if ACLs do not permit them
to be read. | [
"Gets",
"all",
"keys",
"with",
"a",
"prefix",
"of",
"Key",
"during",
"the",
"transaction",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L141-L168 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | WriteMixin.cas | async def cas(self, key, value, *, flags=None, index):
"""Sets the key to the given value with check-and-set semantics.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
index (ObjectIndex): Index ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only be set if its current modify index matches
the supplied Index
If the index is 0, Consul will only put the key if it does not already
exist. If the index is non-zero, the key is only set if the index
matches the ModifyIndex of that key.
"""
value = encode_value(value, flags)
index = extract_attr(index, keys=["ModifyIndex", "Index"])
response = await self._write(key, value, flags=flags, cas=index)
return response.body is True | python | async def cas(self, key, value, *, flags=None, index):
"""Sets the key to the given value with check-and-set semantics.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
index (ObjectIndex): Index ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only be set if its current modify index matches
the supplied Index
If the index is 0, Consul will only put the key if it does not already
exist. If the index is non-zero, the key is only set if the index
matches the ModifyIndex of that key.
"""
value = encode_value(value, flags)
index = extract_attr(index, keys=["ModifyIndex", "Index"])
response = await self._write(key, value, flags=flags, cas=index)
return response.body is True | [
"async",
"def",
"cas",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
",",
"flags",
"=",
"None",
",",
"index",
")",
":",
"value",
"=",
"encode_value",
"(",
"value",
",",
"flags",
")",
"index",
"=",
"extract_attr",
"(",
"index",
",",
"keys",
"=",
"[",
"\"ModifyIndex\"",
",",
"\"Index\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_write",
"(",
"key",
",",
"value",
",",
"flags",
"=",
"flags",
",",
"cas",
"=",
"index",
")",
"return",
"response",
".",
"body",
"is",
"True"
] | Sets the key to the given value with check-and-set semantics.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
index (ObjectIndex): Index ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only be set if its current modify index matches
the supplied Index
If the index is 0, Consul will only put the key if it does not already
exist. If the index is non-zero, the key is only set if the index
matches the ModifyIndex of that key. | [
"Sets",
"the",
"key",
"to",
"the",
"given",
"value",
"with",
"check",
"-",
"and",
"-",
"set",
"semantics",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L187-L208 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | WriteMixin.lock | async def lock(self, key, value, *, flags=None, session):
"""Locks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only obtain the lock if the Session is valid, and no
other session has it locked
"""
value = encode_value(value, flags)
session_id = extract_attr(session, keys=["ID"])
response = await self._write(key, value,
flags=flags,
acquire=session_id)
return response.body is True | python | async def lock(self, key, value, *, flags=None, session):
"""Locks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only obtain the lock if the Session is valid, and no
other session has it locked
"""
value = encode_value(value, flags)
session_id = extract_attr(session, keys=["ID"])
response = await self._write(key, value,
flags=flags,
acquire=session_id)
return response.body is True | [
"async",
"def",
"lock",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
",",
"flags",
"=",
"None",
",",
"session",
")",
":",
"value",
"=",
"encode_value",
"(",
"value",
",",
"flags",
")",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_write",
"(",
"key",
",",
"value",
",",
"flags",
"=",
"flags",
",",
"acquire",
"=",
"session_id",
")",
"return",
"response",
".",
"body",
"is",
"True"
] | Locks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only obtain the lock if the Session is valid, and no
other session has it locked | [
"Locks",
"the",
"Key",
"with",
"the",
"given",
"Session",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L210-L229 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | WriteMixin.unlock | async def unlock(self, key, value, *, flags=None, session):
"""Unlocks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only release the lock if the Session is valid and
currently has it locked.
"""
value = encode_value(value, flags)
session_id = extract_attr(session, keys=["ID"])
response = await self._write(key, value,
flags=flags,
release=session_id)
return response.body is True | python | async def unlock(self, key, value, *, flags=None, session):
"""Unlocks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only release the lock if the Session is valid and
currently has it locked.
"""
value = encode_value(value, flags)
session_id = extract_attr(session, keys=["ID"])
response = await self._write(key, value,
flags=flags,
release=session_id)
return response.body is True | [
"async",
"def",
"unlock",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
",",
"flags",
"=",
"None",
",",
"session",
")",
":",
"value",
"=",
"encode_value",
"(",
"value",
",",
"flags",
")",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_write",
"(",
"key",
",",
"value",
",",
"flags",
"=",
"flags",
",",
"release",
"=",
"session_id",
")",
"return",
"response",
".",
"body",
"is",
"True"
] | Unlocks the Key with the given Session.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
session (ObjectID): Session ID
flags (int): Flags to set with value
Response:
bool: ``True`` on success
The Key will only release the lock if the Session is valid and
currently has it locked. | [
"Unlocks",
"the",
"Key",
"with",
"the",
"given",
"Session",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L231-L250 | train |
johnnoone/aioconsul | aioconsul/client/kv_endpoint.py | DeleteMixin.delete_tree | async def delete_tree(self, prefix, *, separator=None):
"""Deletes all keys with a prefix of Key.
Parameters:
key (str): Key to delete
separator (str): Delete only up to a given separator
Response:
bool: ``True`` on success
"""
response = await self._discard(prefix,
recurse=True,
separator=separator)
return response.body is True | python | async def delete_tree(self, prefix, *, separator=None):
"""Deletes all keys with a prefix of Key.
Parameters:
key (str): Key to delete
separator (str): Delete only up to a given separator
Response:
bool: ``True`` on success
"""
response = await self._discard(prefix,
recurse=True,
separator=separator)
return response.body is True | [
"async",
"def",
"delete_tree",
"(",
"self",
",",
"prefix",
",",
"*",
",",
"separator",
"=",
"None",
")",
":",
"response",
"=",
"await",
"self",
".",
"_discard",
"(",
"prefix",
",",
"recurse",
"=",
"True",
",",
"separator",
"=",
"separator",
")",
"return",
"response",
".",
"body",
"is",
"True"
] | Deletes all keys with a prefix of Key.
Parameters:
key (str): Key to delete
separator (str): Delete only up to a given separator
Response:
bool: ``True`` on success | [
"Deletes",
"all",
"keys",
"with",
"a",
"prefix",
"of",
"Key",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/kv_endpoint.py#L288-L300 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.