repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ttinoco/OPTALG | optalg/opt_solver/opt_solver.py | OptSolver.reset | def reset(self):
"""
Resets solver data.
"""
self.k = 0.
self.x = np.zeros(0)
self.lam = np.zeros(0)
self.nu = np.zeros(0)
self.mu = np.zeros(0)
self.pi = np.zeros(0)
self.status = self.STATUS_UNKNOWN
self.error_msg = ''
self.obj_sca = 1. | python | def reset(self):
"""
Resets solver data.
"""
self.k = 0.
self.x = np.zeros(0)
self.lam = np.zeros(0)
self.nu = np.zeros(0)
self.mu = np.zeros(0)
self.pi = np.zeros(0)
self.status = self.STATUS_UNKNOWN
self.error_msg = ''
self.obj_sca = 1. | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"k",
"=",
"0.",
"self",
".",
"x",
"=",
"np",
".",
"zeros",
"(",
"0",
")",
"self",
".",
"lam",
"=",
"np",
".",
"zeros",
"(",
"0",
")",
"self",
".",
"nu",
"=",
"np",
".",
"zeros",
"(",
"0"... | Resets solver data. | [
"Resets",
"solver",
"data",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/opt_solver.py#L238-L251 | train | 40,100 |
ttinoco/OPTALG | optalg/opt_solver/opt_solver.py | OptSolver.set_parameters | def set_parameters(self,parameters):
"""
Sets solver parameters.
Parameters
----------
parameters : dict
"""
for key,value in list(parameters.items()):
if key in self.parameters:
self.parameters[key] = value | python | def set_parameters(self,parameters):
"""
Sets solver parameters.
Parameters
----------
parameters : dict
"""
for key,value in list(parameters.items()):
if key in self.parameters:
self.parameters[key] = value | [
"def",
"set_parameters",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"parameters",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"parameters",
":",
"self",
".",
"parameters",
"[",
"key"... | Sets solver parameters.
Parameters
----------
parameters : dict | [
"Sets",
"solver",
"parameters",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/opt_solver/opt_solver.py#L275-L286 | train | 40,101 |
ttinoco/OPTALG | optalg/lin_solver/lin_solver.py | LinSolver.factorize_and_solve | def factorize_and_solve(self, A, b):
"""
Factorizes A and solves Ax=b.
Returns
-------
x : vector
"""
self.factorize(A)
return self.solve(b) | python | def factorize_and_solve(self, A, b):
"""
Factorizes A and solves Ax=b.
Returns
-------
x : vector
"""
self.factorize(A)
return self.solve(b) | [
"def",
"factorize_and_solve",
"(",
"self",
",",
"A",
",",
"b",
")",
":",
"self",
".",
"factorize",
"(",
"A",
")",
"return",
"self",
".",
"solve",
"(",
"b",
")"
] | Factorizes A and solves Ax=b.
Returns
-------
x : vector | [
"Factorizes",
"A",
"and",
"solves",
"Ax",
"=",
"b",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/lin_solver.py#L85-L96 | train | 40,102 |
pre-commit/pre-commit-mirror-maker | pre_commit_mirror_maker/make_repo.py | format_files | def format_files(src: str, dest: str, **fmt_vars: str) -> None:
"""Copies all files inside src into dest while formatting the contents
of the files into the output.
For example, a file with the following contents:
{foo} bar {baz}
and the vars {'foo': 'herp', 'baz': 'derp'}
will end up in the output as
herp bar derp
:param text src: Source directory.
:param text dest: Destination directory.
:param dict fmt_vars: Vars to format into the files.
"""
assert os.path.exists(src)
assert os.path.exists(dest)
# Only at the root. Could be made more complicated and recursive later
for filename in os.listdir(src):
if filename.endswith(EXCLUDED_EXTENSIONS):
continue
# Flat directory structure
elif not os.path.isfile(os.path.join(src, filename)):
continue
with open(os.path.join(src, filename)) as f:
output_contents = f.read().format(**fmt_vars)
with open(os.path.join(dest, filename), 'w') as file_obj:
file_obj.write(output_contents) | python | def format_files(src: str, dest: str, **fmt_vars: str) -> None:
"""Copies all files inside src into dest while formatting the contents
of the files into the output.
For example, a file with the following contents:
{foo} bar {baz}
and the vars {'foo': 'herp', 'baz': 'derp'}
will end up in the output as
herp bar derp
:param text src: Source directory.
:param text dest: Destination directory.
:param dict fmt_vars: Vars to format into the files.
"""
assert os.path.exists(src)
assert os.path.exists(dest)
# Only at the root. Could be made more complicated and recursive later
for filename in os.listdir(src):
if filename.endswith(EXCLUDED_EXTENSIONS):
continue
# Flat directory structure
elif not os.path.isfile(os.path.join(src, filename)):
continue
with open(os.path.join(src, filename)) as f:
output_contents = f.read().format(**fmt_vars)
with open(os.path.join(dest, filename), 'w') as file_obj:
file_obj.write(output_contents) | [
"def",
"format_files",
"(",
"src",
":",
"str",
",",
"dest",
":",
"str",
",",
"*",
"*",
"fmt_vars",
":",
"str",
")",
"->",
"None",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"src",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
... | Copies all files inside src into dest while formatting the contents
of the files into the output.
For example, a file with the following contents:
{foo} bar {baz}
and the vars {'foo': 'herp', 'baz': 'derp'}
will end up in the output as
herp bar derp
:param text src: Source directory.
:param text dest: Destination directory.
:param dict fmt_vars: Vars to format into the files. | [
"Copies",
"all",
"files",
"inside",
"src",
"into",
"dest",
"while",
"formatting",
"the",
"contents",
"of",
"the",
"files",
"into",
"the",
"output",
"."
] | 8bafa3b87e67d291d5a747f0137b921a170a1723 | https://github.com/pre-commit/pre-commit-mirror-maker/blob/8bafa3b87e67d291d5a747f0137b921a170a1723/pre_commit_mirror_maker/make_repo.py#L14-L43 | train | 40,103 |
ttinoco/OPTALG | optalg/lin_solver/mumps.py | LinSolverMUMPS.analyze | def analyze(self,A):
"""
Analyzes structure of A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part.
"""
A = coo_matrix(A)
self.mumps.set_shape(A.shape[0])
self.mumps.set_centralized_assembled_rows_cols(A.row+1,A.col+1)
self.mumps.run(job=1)
self.analyzed = True | python | def analyze(self,A):
"""
Analyzes structure of A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part.
"""
A = coo_matrix(A)
self.mumps.set_shape(A.shape[0])
self.mumps.set_centralized_assembled_rows_cols(A.row+1,A.col+1)
self.mumps.run(job=1)
self.analyzed = True | [
"def",
"analyze",
"(",
"self",
",",
"A",
")",
":",
"A",
"=",
"coo_matrix",
"(",
"A",
")",
"self",
".",
"mumps",
".",
"set_shape",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
")",
"self",
".",
"mumps",
".",
"set_centralized_assembled_rows_cols",
"(",
"A",
... | Analyzes structure of A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part. | [
"Analyzes",
"structure",
"of",
"A",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/mumps.py#L43-L60 | train | 40,104 |
ttinoco/OPTALG | optalg/lin_solver/mumps.py | LinSolverMUMPS.factorize_and_solve | def factorize_and_solve(self,A,b):
"""
Factorizes A and sovles Ax=b.
Parameters
----------
A : matrix
b : ndarray
Returns
-------
x : ndarray
"""
A = coo_matrix(A)
x = b.copy()
self.mumps.set_centralized_assembled_values(A.data)
self.mumps.set_rhs(x)
self.mumps.run(job=5)
return x | python | def factorize_and_solve(self,A,b):
"""
Factorizes A and sovles Ax=b.
Parameters
----------
A : matrix
b : ndarray
Returns
-------
x : ndarray
"""
A = coo_matrix(A)
x = b.copy()
self.mumps.set_centralized_assembled_values(A.data)
self.mumps.set_rhs(x)
self.mumps.run(job=5)
return x | [
"def",
"factorize_and_solve",
"(",
"self",
",",
"A",
",",
"b",
")",
":",
"A",
"=",
"coo_matrix",
"(",
"A",
")",
"x",
"=",
"b",
".",
"copy",
"(",
")",
"self",
".",
"mumps",
".",
"set_centralized_assembled_values",
"(",
"A",
".",
"data",
")",
"self",
... | Factorizes A and sovles Ax=b.
Parameters
----------
A : matrix
b : ndarray
Returns
-------
x : ndarray | [
"Factorizes",
"A",
"and",
"sovles",
"Ax",
"=",
"b",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/mumps.py#L96-L117 | train | 40,105 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | spsolve | def spsolve(A, b, comm=None):
"""Sparse solve A\b."""
assert A.dtype == 'd' and b.dtype == 'd', "Only double precision supported."
with DMumpsContext(par=1, sym=0, comm=comm) as ctx:
if ctx.myid == 0:
# Set the sparse matrix -- only necessary on
ctx.set_centralized_sparse(A.tocoo())
x = b.copy()
ctx.set_rhs(x)
# Silence most messages
ctx.set_silent()
# Analysis + Factorization + Solve
ctx.run(job=6)
if ctx.myid == 0:
return x | python | def spsolve(A, b, comm=None):
"""Sparse solve A\b."""
assert A.dtype == 'd' and b.dtype == 'd', "Only double precision supported."
with DMumpsContext(par=1, sym=0, comm=comm) as ctx:
if ctx.myid == 0:
# Set the sparse matrix -- only necessary on
ctx.set_centralized_sparse(A.tocoo())
x = b.copy()
ctx.set_rhs(x)
# Silence most messages
ctx.set_silent()
# Analysis + Factorization + Solve
ctx.run(job=6)
if ctx.myid == 0:
return x | [
"def",
"spsolve",
"(",
"A",
",",
"b",
",",
"comm",
"=",
"None",
")",
":",
"assert",
"A",
".",
"dtype",
"==",
"'d'",
"and",
"b",
".",
"dtype",
"==",
"'d'",
",",
"\"Only double precision supported.\"",
"with",
"DMumpsContext",
"(",
"par",
"=",
"1",
",",
... | Sparse solve A\b. | [
"Sparse",
"solve",
"A",
"\\",
"b",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L250-L268 | train | 40,106 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_centralized_assembled_rows_cols | def set_centralized_assembled_rows_cols(self, irn, jcn):
"""Set assembled matrix indices on processor 0.
The row and column indices (irn & jcn) should be one based.
"""
if self.myid != 0:
return
assert irn.size == jcn.size
self._refs.update(irn=irn, jcn=jcn)
self.id.nz = irn.size
self.id.irn = self.cast_array(irn)
self.id.jcn = self.cast_array(jcn) | python | def set_centralized_assembled_rows_cols(self, irn, jcn):
"""Set assembled matrix indices on processor 0.
The row and column indices (irn & jcn) should be one based.
"""
if self.myid != 0:
return
assert irn.size == jcn.size
self._refs.update(irn=irn, jcn=jcn)
self.id.nz = irn.size
self.id.irn = self.cast_array(irn)
self.id.jcn = self.cast_array(jcn) | [
"def",
"set_centralized_assembled_rows_cols",
"(",
"self",
",",
"irn",
",",
"jcn",
")",
":",
"if",
"self",
".",
"myid",
"!=",
"0",
":",
"return",
"assert",
"irn",
".",
"size",
"==",
"jcn",
".",
"size",
"self",
".",
"_refs",
".",
"update",
"(",
"irn",
... | Set assembled matrix indices on processor 0.
The row and column indices (irn & jcn) should be one based. | [
"Set",
"assembled",
"matrix",
"indices",
"on",
"processor",
"0",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L110-L121 | train | 40,107 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_centralized_assembled_values | def set_centralized_assembled_values(self, a):
"""Set assembled matrix values on processor 0."""
if self.myid != 0:
return
assert a.size == self.id.nz
self._refs.update(a=a)
self.id.a = self.cast_array(a) | python | def set_centralized_assembled_values(self, a):
"""Set assembled matrix values on processor 0."""
if self.myid != 0:
return
assert a.size == self.id.nz
self._refs.update(a=a)
self.id.a = self.cast_array(a) | [
"def",
"set_centralized_assembled_values",
"(",
"self",
",",
"a",
")",
":",
"if",
"self",
".",
"myid",
"!=",
"0",
":",
"return",
"assert",
"a",
".",
"size",
"==",
"self",
".",
"id",
".",
"nz",
"self",
".",
"_refs",
".",
"update",
"(",
"a",
"=",
"a"... | Set assembled matrix values on processor 0. | [
"Set",
"assembled",
"matrix",
"values",
"on",
"processor",
"0",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L123-L129 | train | 40,108 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_distributed_assembled | def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc):
"""Set the distributed assembled matrix.
Distributed assembled matrices require setting icntl(18) != 0.
"""
self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc)
self.set_distributed_assembled_values(a_loc) | python | def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc):
"""Set the distributed assembled matrix.
Distributed assembled matrices require setting icntl(18) != 0.
"""
self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc)
self.set_distributed_assembled_values(a_loc) | [
"def",
"set_distributed_assembled",
"(",
"self",
",",
"irn_loc",
",",
"jcn_loc",
",",
"a_loc",
")",
":",
"self",
".",
"set_distributed_assembled_rows_cols",
"(",
"irn_loc",
",",
"jcn_loc",
")",
"self",
".",
"set_distributed_assembled_values",
"(",
"a_loc",
")"
] | Set the distributed assembled matrix.
Distributed assembled matrices require setting icntl(18) != 0. | [
"Set",
"the",
"distributed",
"assembled",
"matrix",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L136-L142 | train | 40,109 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_distributed_assembled_rows_cols | def set_distributed_assembled_rows_cols(self, irn_loc, jcn_loc):
"""Set the distributed assembled matrix row & column numbers.
Distributed assembled matrices require setting icntl(18) != 0.
"""
assert irn_loc.size == jcn_loc.size
self._refs.update(irn_loc=irn_loc, jcn_loc=jcn_loc)
self.id.nz_loc = irn_loc.size
self.id.irn_loc = self.cast_array(irn_loc)
self.id.jcn_loc = self.cast_array(jcn_loc) | python | def set_distributed_assembled_rows_cols(self, irn_loc, jcn_loc):
"""Set the distributed assembled matrix row & column numbers.
Distributed assembled matrices require setting icntl(18) != 0.
"""
assert irn_loc.size == jcn_loc.size
self._refs.update(irn_loc=irn_loc, jcn_loc=jcn_loc)
self.id.nz_loc = irn_loc.size
self.id.irn_loc = self.cast_array(irn_loc)
self.id.jcn_loc = self.cast_array(jcn_loc) | [
"def",
"set_distributed_assembled_rows_cols",
"(",
"self",
",",
"irn_loc",
",",
"jcn_loc",
")",
":",
"assert",
"irn_loc",
".",
"size",
"==",
"jcn_loc",
".",
"size",
"self",
".",
"_refs",
".",
"update",
"(",
"irn_loc",
"=",
"irn_loc",
",",
"jcn_loc",
"=",
"... | Set the distributed assembled matrix row & column numbers.
Distributed assembled matrices require setting icntl(18) != 0. | [
"Set",
"the",
"distributed",
"assembled",
"matrix",
"row",
"&",
"column",
"numbers",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L144-L154 | train | 40,110 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_distributed_assembled_values | def set_distributed_assembled_values(self, a_loc):
"""Set the distributed assembled matrix values.
Distributed assembled matrices require setting icntl(18) != 0.
"""
assert a_loc.size == self._refs['irn_loc'].size
self._refs.update(a_loc=a_loc)
self.id.a_loc = self.cast_array(a_loc) | python | def set_distributed_assembled_values(self, a_loc):
"""Set the distributed assembled matrix values.
Distributed assembled matrices require setting icntl(18) != 0.
"""
assert a_loc.size == self._refs['irn_loc'].size
self._refs.update(a_loc=a_loc)
self.id.a_loc = self.cast_array(a_loc) | [
"def",
"set_distributed_assembled_values",
"(",
"self",
",",
"a_loc",
")",
":",
"assert",
"a_loc",
".",
"size",
"==",
"self",
".",
"_refs",
"[",
"'irn_loc'",
"]",
".",
"size",
"self",
".",
"_refs",
".",
"update",
"(",
"a_loc",
"=",
"a_loc",
")",
"self",
... | Set the distributed assembled matrix values.
Distributed assembled matrices require setting icntl(18) != 0. | [
"Set",
"the",
"distributed",
"assembled",
"matrix",
"values",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L156-L163 | train | 40,111 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_rhs | def set_rhs(self, rhs):
"""Set the right hand side. This matrix will be modified in place."""
assert rhs.size == self.id.n
self._refs.update(rhs=rhs)
self.id.rhs = self.cast_array(rhs) | python | def set_rhs(self, rhs):
"""Set the right hand side. This matrix will be modified in place."""
assert rhs.size == self.id.n
self._refs.update(rhs=rhs)
self.id.rhs = self.cast_array(rhs) | [
"def",
"set_rhs",
"(",
"self",
",",
"rhs",
")",
":",
"assert",
"rhs",
".",
"size",
"==",
"self",
".",
"id",
".",
"n",
"self",
".",
"_refs",
".",
"update",
"(",
"rhs",
"=",
"rhs",
")",
"self",
".",
"id",
".",
"rhs",
"=",
"self",
".",
"cast_array... | Set the right hand side. This matrix will be modified in place. | [
"Set",
"the",
"right",
"hand",
"side",
".",
"This",
"matrix",
"will",
"be",
"modified",
"in",
"place",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L170-L174 | train | 40,112 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.set_silent | def set_silent(self):
"""Silence most messages."""
self.set_icntl(1, -1) # output stream for error msgs
self.set_icntl(2, -1) # otuput stream for diagnostic msgs
self.set_icntl(3, -1) # output stream for global info
self.set_icntl(4, 0) | python | def set_silent(self):
"""Silence most messages."""
self.set_icntl(1, -1) # output stream for error msgs
self.set_icntl(2, -1) # otuput stream for diagnostic msgs
self.set_icntl(3, -1) # output stream for global info
self.set_icntl(4, 0) | [
"def",
"set_silent",
"(",
"self",
")",
":",
"self",
".",
"set_icntl",
"(",
"1",
",",
"-",
"1",
")",
"# output stream for error msgs",
"self",
".",
"set_icntl",
"(",
"2",
",",
"-",
"1",
")",
"# otuput stream for diagnostic msgs",
"self",
".",
"set_icntl",
"("... | Silence most messages. | [
"Silence",
"most",
"messages",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L187-L192 | train | 40,113 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.destroy | def destroy(self):
"""Delete the MUMPS context and release all array references."""
if self.id is not None and self._mumps_c is not None:
self.id.job = -2 # JOB_END
self._mumps_c(self.id)
self.id = None
self._refs = None | python | def destroy(self):
"""Delete the MUMPS context and release all array references."""
if self.id is not None and self._mumps_c is not None:
self.id.job = -2 # JOB_END
self._mumps_c(self.id)
self.id = None
self._refs = None | [
"def",
"destroy",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
"is",
"not",
"None",
"and",
"self",
".",
"_mumps_c",
"is",
"not",
"None",
":",
"self",
".",
"id",
".",
"job",
"=",
"-",
"2",
"# JOB_END",
"self",
".",
"_mumps_c",
"(",
"self",
".",... | Delete the MUMPS context and release all array references. | [
"Delete",
"the",
"MUMPS",
"context",
"and",
"release",
"all",
"array",
"references",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L198-L204 | train | 40,114 |
ttinoco/OPTALG | optalg/lin_solver/_mumps/__init__.py | _MumpsBaseContext.mumps | def mumps(self):
"""Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS.
"""
self._mumps_c(self.id)
if self.id.infog[0] < 0:
raise RuntimeError("MUMPS error: %d" % self.id.infog[0]) | python | def mumps(self):
"""Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS.
"""
self._mumps_c(self.id)
if self.id.infog[0] < 0:
raise RuntimeError("MUMPS error: %d" % self.id.infog[0]) | [
"def",
"mumps",
"(",
"self",
")",
":",
"self",
".",
"_mumps_c",
"(",
"self",
".",
"id",
")",
"if",
"self",
".",
"id",
".",
"infog",
"[",
"0",
"]",
"<",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"MUMPS error: %d\"",
"%",
"self",
".",
"id",
".",
"i... | Call MUMPS, checking for errors in the return code.
The desired job should have already been set using `ctx.set_job(...)`.
As a convenience, you may wish to call `ctx.run(job=...)` which sets
the job and calls MUMPS. | [
"Call",
"MUMPS",
"checking",
"for",
"errors",
"in",
"the",
"return",
"code",
"."
] | d4f141292f281eea4faa71473258139e7f433001 | https://github.com/ttinoco/OPTALG/blob/d4f141292f281eea4faa71473258139e7f433001/optalg/lin_solver/_mumps/__init__.py#L213-L222 | train | 40,115 |
DLR-RM/RAFCON | source/rafcon/core/state_elements/data_flow.py | DataFlow.modify_origin | def modify_origin(self, from_state, from_key):
"""Set both from_state and from_key at the same time to modify data flow origin
:param str from_state: State id of the origin state
:param int from_key: Data port id of the origin port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid
"""
if not isinstance(from_state, string_types):
raise ValueError("Invalid data flow origin port: from_state must be a string")
if not isinstance(from_key, int):
raise ValueError("Invalid data flow origin port: from_key must be of type int")
old_from_state = self.from_state
old_from_key = self.from_key
self._from_state = from_state
self._from_key = from_key
valid, message = self._check_validity()
if not valid:
self._from_state = old_from_state
self._from_key = old_from_key
raise ValueError("The data flow origin could not be changed: {0}".format(message)) | python | def modify_origin(self, from_state, from_key):
"""Set both from_state and from_key at the same time to modify data flow origin
:param str from_state: State id of the origin state
:param int from_key: Data port id of the origin port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid
"""
if not isinstance(from_state, string_types):
raise ValueError("Invalid data flow origin port: from_state must be a string")
if not isinstance(from_key, int):
raise ValueError("Invalid data flow origin port: from_key must be of type int")
old_from_state = self.from_state
old_from_key = self.from_key
self._from_state = from_state
self._from_key = from_key
valid, message = self._check_validity()
if not valid:
self._from_state = old_from_state
self._from_key = old_from_key
raise ValueError("The data flow origin could not be changed: {0}".format(message)) | [
"def",
"modify_origin",
"(",
"self",
",",
"from_state",
",",
"from_key",
")",
":",
"if",
"not",
"isinstance",
"(",
"from_state",
",",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid data flow origin port: from_state must be a string\"",
")",
"if",
"... | Set both from_state and from_key at the same time to modify data flow origin
:param str from_state: State id of the origin state
:param int from_key: Data port id of the origin port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid | [
"Set",
"both",
"from_state",
"and",
"from_key",
"at",
"the",
"same",
"time",
"to",
"modify",
"data",
"flow",
"origin"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_elements/data_flow.py#L128-L149 | train | 40,116 |
DLR-RM/RAFCON | source/rafcon/core/state_elements/data_flow.py | DataFlow.modify_target | def modify_target(self, to_state, to_key):
"""Set both to_state and to_key at the same time to modify data flow target
:param str to_state: State id of the target state
:param int to_key: Data port id of the target port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid
"""
if not isinstance(to_state, string_types):
raise ValueError("Invalid data flow target port: from_state must be a string")
if not isinstance(to_key, int):
raise ValueError("Invalid data flow target port: from_outcome must be of type int")
old_to_state = self.to_state
old_to_key = self.to_key
self._to_state = to_state
self._to_key = to_key
valid, message = self._check_validity()
if not valid:
self._to_state = old_to_state
self._to_key = old_to_key
raise ValueError("The data flow target could not be changed: {0}".format(message)) | python | def modify_target(self, to_state, to_key):
"""Set both to_state and to_key at the same time to modify data flow target
:param str to_state: State id of the target state
:param int to_key: Data port id of the target port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid
"""
if not isinstance(to_state, string_types):
raise ValueError("Invalid data flow target port: from_state must be a string")
if not isinstance(to_key, int):
raise ValueError("Invalid data flow target port: from_outcome must be of type int")
old_to_state = self.to_state
old_to_key = self.to_key
self._to_state = to_state
self._to_key = to_key
valid, message = self._check_validity()
if not valid:
self._to_state = old_to_state
self._to_key = old_to_key
raise ValueError("The data flow target could not be changed: {0}".format(message)) | [
"def",
"modify_target",
"(",
"self",
",",
"to_state",
",",
"to_key",
")",
":",
"if",
"not",
"isinstance",
"(",
"to_state",
",",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid data flow target port: from_state must be a string\"",
")",
"if",
"not",
... | Set both to_state and to_key at the same time to modify data flow target
:param str to_state: State id of the target state
:param int to_key: Data port id of the target port
:raises exceptions.ValueError: If parameters have wrong types or the new data flow is not valid | [
"Set",
"both",
"to_state",
"and",
"to_key",
"at",
"the",
"same",
"time",
"to",
"modify",
"data",
"flow",
"target"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_elements/data_flow.py#L183-L204 | train | 40,117 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/utils/editor.py | EditorController.code_changed | def code_changed(self, source):
""" Apply checks and adjustments of the TextBuffer and TextView after every change in buffer.
The method re-apply the tag (style) for the buffer. It avoids changes while editable-property set to False
which are caused by a bug in the GtkSourceView2. GtkSourceView2 is the default used TextView widget here.
The text buffer is reset after every change to last stored source-text by a respective work around which
suspends any generation of undo items and avoids a recursive call of the method set_enabled by observing
its while_in_set_enabled flag.
:param TextBuffer source:
:return:
"""
# work around to avoid changes at all (e.g. by enter-key) if text view property editable is False
# TODO if SourceView3 is used in future check if this can be skipped
if not self.view.textview.get_editable() and not self.view.while_in_set_enabled:
if hasattr(self.view.get_buffer(), 'begin_not_undoable_action'):
self.view.get_buffer().begin_not_undoable_action()
self.view.set_enabled(False, self.source_text)
if hasattr(self.view.get_buffer(), 'end_not_undoable_action'):
self.view.get_buffer().end_not_undoable_action()
if self.view:
self.view.apply_tag('default') | python | def code_changed(self, source):
""" Apply checks and adjustments of the TextBuffer and TextView after every change in buffer.
The method re-apply the tag (style) for the buffer. It avoids changes while editable-property set to False
which are caused by a bug in the GtkSourceView2. GtkSourceView2 is the default used TextView widget here.
The text buffer is reset after every change to last stored source-text by a respective work around which
suspends any generation of undo items and avoids a recursive call of the method set_enabled by observing
its while_in_set_enabled flag.
:param TextBuffer source:
:return:
"""
# work around to avoid changes at all (e.g. by enter-key) if text view property editable is False
# TODO if SourceView3 is used in future check if this can be skipped
if not self.view.textview.get_editable() and not self.view.while_in_set_enabled:
if hasattr(self.view.get_buffer(), 'begin_not_undoable_action'):
self.view.get_buffer().begin_not_undoable_action()
self.view.set_enabled(False, self.source_text)
if hasattr(self.view.get_buffer(), 'end_not_undoable_action'):
self.view.get_buffer().end_not_undoable_action()
if self.view:
self.view.apply_tag('default') | [
"def",
"code_changed",
"(",
"self",
",",
"source",
")",
":",
"# work around to avoid changes at all (e.g. by enter-key) if text view property editable is False",
"# TODO if SourceView3 is used in future check if this can be skipped",
"if",
"not",
"self",
".",
"view",
".",
"textview",... | Apply checks and adjustments of the TextBuffer and TextView after every change in buffer.
The method re-apply the tag (style) for the buffer. It avoids changes while editable-property set to False
which are caused by a bug in the GtkSourceView2. GtkSourceView2 is the default used TextView widget here.
The text buffer is reset after every change to last stored source-text by a respective work around which
suspends any generation of undo items and avoids a recursive call of the method set_enabled by observing
its while_in_set_enabled flag.
:param TextBuffer source:
:return: | [
"Apply",
"checks",
"and",
"adjustments",
"of",
"the",
"TextBuffer",
"and",
"TextView",
"after",
"every",
"change",
"in",
"buffer",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/editor.py#L119-L142 | train | 40,118 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/utils/editor.py | EditorController.apply_clicked | def apply_clicked(self, button):
"""Triggered when the Apply-Shortcut in the editor is triggered.
"""
if isinstance(self.model.state, LibraryState):
return
self.set_script_text(self.view.get_text()) | python | def apply_clicked(self, button):
"""Triggered when the Apply-Shortcut in the editor is triggered.
"""
if isinstance(self.model.state, LibraryState):
return
self.set_script_text(self.view.get_text()) | [
"def",
"apply_clicked",
"(",
"self",
",",
"button",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
".",
"state",
",",
"LibraryState",
")",
":",
"return",
"self",
".",
"set_script_text",
"(",
"self",
".",
"view",
".",
"get_text",
"(",
")",
")"... | Triggered when the Apply-Shortcut in the editor is triggered. | [
"Triggered",
"when",
"the",
"Apply",
"-",
"Shortcut",
"in",
"the",
"editor",
"is",
"triggered",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/editor.py#L144-L151 | train | 40,119 |
DLR-RM/RAFCON | source/rafcon/gui/views/utils/editor.py | EditorView.set_text | def set_text(self, text):
""" The method insert text into the text buffer of the text view and preserves the cursor location.
:param str text: which is insert into the text buffer.
:return:
"""
line_number, line_offset = self.get_cursor_position()
self.get_buffer().set_text(text)
self.set_cursor_position(line_number, line_offset) | python | def set_text(self, text):
""" The method insert text into the text buffer of the text view and preserves the cursor location.
:param str text: which is insert into the text buffer.
:return:
"""
line_number, line_offset = self.get_cursor_position()
self.get_buffer().set_text(text)
self.set_cursor_position(line_number, line_offset) | [
"def",
"set_text",
"(",
"self",
",",
"text",
")",
":",
"line_number",
",",
"line_offset",
"=",
"self",
".",
"get_cursor_position",
"(",
")",
"self",
".",
"get_buffer",
"(",
")",
".",
"set_text",
"(",
"text",
")",
"self",
".",
"set_cursor_position",
"(",
... | The method insert text into the text buffer of the text view and preserves the cursor location.
:param str text: which is insert into the text buffer.
:return: | [
"The",
"method",
"insert",
"text",
"into",
"the",
"text",
"buffer",
"of",
"the",
"text",
"view",
"and",
"preserves",
"the",
"cursor",
"location",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/utils/editor.py#L144-L152 | train | 40,120 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | reduce_to_parent_states | def reduce_to_parent_states(models):
"""Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list
only contains the hierarchy state.
:param set models: The set of selected models
:return: The reduced set of selected models
:rtype: set
"""
models = set(models) # Ensure that models is a set and that we do not operate on the parameter itself
models_to_remove = set()
# check all models
for model in models:
parent_m = model.parent
# check if any (grand-)parent is already in the selection, if so, remove the child
while parent_m is not None:
if parent_m in models:
models_to_remove.add(model)
break
parent_m = parent_m.parent
for model in models_to_remove:
models.remove(model)
if models_to_remove:
logger.debug("The selection has been reduced, as it may not contain elements whose children are also selected")
return models | python | def reduce_to_parent_states(models):
"""Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list
only contains the hierarchy state.
:param set models: The set of selected models
:return: The reduced set of selected models
:rtype: set
"""
models = set(models) # Ensure that models is a set and that we do not operate on the parameter itself
models_to_remove = set()
# check all models
for model in models:
parent_m = model.parent
# check if any (grand-)parent is already in the selection, if so, remove the child
while parent_m is not None:
if parent_m in models:
models_to_remove.add(model)
break
parent_m = parent_m.parent
for model in models_to_remove:
models.remove(model)
if models_to_remove:
logger.debug("The selection has been reduced, as it may not contain elements whose children are also selected")
return models | [
"def",
"reduce_to_parent_states",
"(",
"models",
")",
":",
"models",
"=",
"set",
"(",
"models",
")",
"# Ensure that models is a set and that we do not operate on the parameter itself",
"models_to_remove",
"=",
"set",
"(",
")",
"# check all models",
"for",
"model",
"in",
"... | Remove all models of states that have a state model with parent relation in the list
The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list
only contains the hierarchy state.
:param set models: The set of selected models
:return: The reduced set of selected models
:rtype: set | [
"Remove",
"all",
"models",
"of",
"states",
"that",
"have",
"a",
"state",
"model",
"with",
"parent",
"relation",
"in",
"the",
"list"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L37-L63 | train | 40,121 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | updates_selection | def updates_selection(update_selection):
""" Decorator indicating that the decorated method could change the selection"""
def handle_update(selection, *args, **kwargs):
"""Check for changes in the selection
If the selection is changed by the decorated method, the internal core element lists are updated and a signal is
emitted with the old and new selection as well as the name of the method that caused the change..
"""
old_selection = selection.get_all()
update_selection(selection, *args, **kwargs)
new_selection = selection.get_all()
affected_models = old_selection ^ new_selection
if len(affected_models) != 0: # The selection was updated
deselected_models = old_selection - new_selection
selected_models = new_selection - old_selection
map(selection.relieve_model, deselected_models)
map(selection.observe_model, selected_models)
# Maintain internal lists for fast access
selection.update_core_element_lists()
# Clear focus if no longer in selection
if selection.focus and selection.focus not in new_selection:
del selection.focus
# Send notifications about changes
affected_classes = set(model.core_element.__class__ for model in affected_models)
msg_namedtuple = SelectionChangedSignalMsg(update_selection.__name__, new_selection, old_selection,
affected_classes)
selection.selection_changed_signal.emit(msg_namedtuple)
if selection.parent_signal is not None:
selection.parent_signal.emit(msg_namedtuple)
return handle_update | python | def updates_selection(update_selection):
""" Decorator indicating that the decorated method could change the selection"""
def handle_update(selection, *args, **kwargs):
"""Check for changes in the selection
If the selection is changed by the decorated method, the internal core element lists are updated and a signal is
emitted with the old and new selection as well as the name of the method that caused the change..
"""
old_selection = selection.get_all()
update_selection(selection, *args, **kwargs)
new_selection = selection.get_all()
affected_models = old_selection ^ new_selection
if len(affected_models) != 0: # The selection was updated
deselected_models = old_selection - new_selection
selected_models = new_selection - old_selection
map(selection.relieve_model, deselected_models)
map(selection.observe_model, selected_models)
# Maintain internal lists for fast access
selection.update_core_element_lists()
# Clear focus if no longer in selection
if selection.focus and selection.focus not in new_selection:
del selection.focus
# Send notifications about changes
affected_classes = set(model.core_element.__class__ for model in affected_models)
msg_namedtuple = SelectionChangedSignalMsg(update_selection.__name__, new_selection, old_selection,
affected_classes)
selection.selection_changed_signal.emit(msg_namedtuple)
if selection.parent_signal is not None:
selection.parent_signal.emit(msg_namedtuple)
return handle_update | [
"def",
"updates_selection",
"(",
"update_selection",
")",
":",
"def",
"handle_update",
"(",
"selection",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Check for changes in the selection\n\n If the selection is changed by the decorated method, the internal c... | Decorator indicating that the decorated method could change the selection | [
"Decorator",
"indicating",
"that",
"the",
"decorated",
"method",
"could",
"change",
"the",
"selection"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L66-L99 | train | 40,122 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | extend_selection | def extend_selection():
"""Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True
"""
from rafcon.gui.singleton import main_window_controller
currently_pressed_keys = main_window_controller.currently_pressed_keys if main_window_controller else set()
if any(key in currently_pressed_keys for key in [constants.EXTEND_SELECTION_KEY,
constants.EXTEND_SELECTION_KEY_ALT]):
return True
return False | python | def extend_selection():
"""Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True
"""
from rafcon.gui.singleton import main_window_controller
currently_pressed_keys = main_window_controller.currently_pressed_keys if main_window_controller else set()
if any(key in currently_pressed_keys for key in [constants.EXTEND_SELECTION_KEY,
constants.EXTEND_SELECTION_KEY_ALT]):
return True
return False | [
"def",
"extend_selection",
"(",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"singleton",
"import",
"main_window_controller",
"currently_pressed_keys",
"=",
"main_window_controller",
".",
"currently_pressed_keys",
"if",
"main_window_controller",
"else",
"set",
"(",
")",... | Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True | [
"Checks",
"is",
"the",
"selection",
"is",
"to",
"be",
"extended"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L102-L115 | train | 40,123 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection._check_model_types | def _check_model_types(self, models):
""" Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class"""
if not hasattr(models, "__iter__"):
models = {models}
if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):
raise TypeError("The selection supports only models with base class AbstractStateModel or "
"StateElementModel, see handed elements {0}".format(models))
return models if isinstance(models, set) else set(models) | python | def _check_model_types(self, models):
""" Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class"""
if not hasattr(models, "__iter__"):
models = {models}
if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):
raise TypeError("The selection supports only models with base class AbstractStateModel or "
"StateElementModel, see handed elements {0}".format(models))
return models if isinstance(models, set) else set(models) | [
"def",
"_check_model_types",
"(",
"self",
",",
"models",
")",
":",
"if",
"not",
"hasattr",
"(",
"models",
",",
"\"__iter__\"",
")",
":",
"models",
"=",
"{",
"models",
"}",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"model",
",",
"(",
"AbstractSta... | Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class | [
"Check",
"types",
"of",
"passed",
"models",
"for",
"correctness",
"and",
"in",
"case",
"raise",
"exception"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L157-L167 | train | 40,124 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.handle_prepared_selection_of_core_class_elements | def handle_prepared_selection_of_core_class_elements(self, core_class, models):
"""Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is handled by that widget. This method is called to integrate the local selection with the overall
selection of the state machine.
If no modifier key (indicating to extend the selection) is pressed, the state machine selection is set to the
passed selection. If the selection is to be extended, the state machine collection will consist of the widget
selection plus all previously selected elements not having the core class `core_class`.
:param State | StateElement core_class: The core class of the elements the widget handles
:param models: The list of models that are currently being selected locally
"""
if extend_selection():
self._selected.difference_update(self.get_selected_elements_of_core_class(core_class))
else:
self._selected.clear()
models = self._check_model_types(models)
if len(models) > 1:
models = reduce_to_parent_states(models)
self._selected.update(models) | python | def handle_prepared_selection_of_core_class_elements(self, core_class, models):
"""Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is handled by that widget. This method is called to integrate the local selection with the overall
selection of the state machine.
If no modifier key (indicating to extend the selection) is pressed, the state machine selection is set to the
passed selection. If the selection is to be extended, the state machine collection will consist of the widget
selection plus all previously selected elements not having the core class `core_class`.
:param State | StateElement core_class: The core class of the elements the widget handles
:param models: The list of models that are currently being selected locally
"""
if extend_selection():
self._selected.difference_update(self.get_selected_elements_of_core_class(core_class))
else:
self._selected.clear()
models = self._check_model_types(models)
if len(models) > 1:
models = reduce_to_parent_states(models)
self._selected.update(models) | [
"def",
"handle_prepared_selection_of_core_class_elements",
"(",
"self",
",",
"core_class",
",",
"models",
")",
":",
"if",
"extend_selection",
"(",
")",
":",
"self",
".",
"_selected",
".",
"difference_update",
"(",
"self",
".",
"get_selected_elements_of_core_class",
"(... | Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is handled by that widget. This method is called to integrate the local selection with the overall
selection of the state machine.
If no modifier key (indicating to extend the selection) is pressed, the state machine selection is set to the
passed selection. If the selection is to be extended, the state machine collection will consist of the widget
selection plus all previously selected elements not having the core class `core_class`.
:param State | StateElement core_class: The core class of the elements the widget handles
:param models: The list of models that are currently being selected locally | [
"Handles",
"the",
"selection",
"for",
"TreeStore",
"widgets",
"maintaining",
"lists",
"of",
"a",
"specific",
"core_class",
"elements"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L206-L229 | train | 40,125 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.handle_new_selection | def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on
"""
models = self._check_model_types(models)
if extend_selection():
already_selected_elements = models & self._selected
newly_selected_elements = models - self._selected
self._selected.difference_update(already_selected_elements)
self._selected.update(newly_selected_elements)
else:
self._selected = models
self._selected = reduce_to_parent_states(self._selected) | python | def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on
"""
models = self._check_model_types(models)
if extend_selection():
already_selected_elements = models & self._selected
newly_selected_elements = models - self._selected
self._selected.difference_update(already_selected_elements)
self._selected.update(newly_selected_elements)
else:
self._selected = models
self._selected = reduce_to_parent_states(self._selected) | [
"def",
"handle_new_selection",
"(",
"self",
",",
"models",
")",
":",
"models",
"=",
"self",
".",
"_check_model_types",
"(",
"models",
")",
"if",
"extend_selection",
"(",
")",
":",
"already_selected_elements",
"=",
"models",
"&",
"self",
".",
"_selected",
"newl... | Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:
* If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
models
* If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
selection are selected, those that are in the previous selection are deselected
:param models: The list of models that are newly selected/clicked on | [
"Handles",
"the",
"selection",
"for",
"generic",
"widgets"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L232-L256 | train | 40,126 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.focus | def focus(self, model):
"""Sets the passed model as focused element
:param ModelMT model: The element to be focused
"""
if model is None:
del self.focus
return
self._check_model_types(model)
self.add(model)
focus_msg = FocusSignalMsg(model, self._focus)
self._focus = model
self._selected.add(model)
self._selected = reduce_to_parent_states(self._selected)
self.focus_signal.emit(focus_msg) | python | def focus(self, model):
"""Sets the passed model as focused element
:param ModelMT model: The element to be focused
"""
if model is None:
del self.focus
return
self._check_model_types(model)
self.add(model)
focus_msg = FocusSignalMsg(model, self._focus)
self._focus = model
self._selected.add(model)
self._selected = reduce_to_parent_states(self._selected)
self.focus_signal.emit(focus_msg) | [
"def",
"focus",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
"is",
"None",
":",
"del",
"self",
".",
"focus",
"return",
"self",
".",
"_check_model_types",
"(",
"model",
")",
"self",
".",
"add",
"(",
"model",
")",
"focus_msg",
"=",
"FocusSignalMsg... | Sets the passed model as focused element
:param ModelMT model: The element to be focused | [
"Sets",
"the",
"passed",
"model",
"as",
"focused",
"element"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L264-L279 | train | 40,127 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.focus | def focus(self):
""" Unsets the focused element """
focus_msg = FocusSignalMsg(None, self._focus)
self._focus = None
self.focus_signal.emit(focus_msg) | python | def focus(self):
""" Unsets the focused element """
focus_msg = FocusSignalMsg(None, self._focus)
self._focus = None
self.focus_signal.emit(focus_msg) | [
"def",
"focus",
"(",
"self",
")",
":",
"focus_msg",
"=",
"FocusSignalMsg",
"(",
"None",
",",
"self",
".",
"_focus",
")",
"self",
".",
"_focus",
"=",
"None",
"self",
".",
"focus_signal",
".",
"emit",
"(",
"focus_msg",
")"
] | Unsets the focused element | [
"Unsets",
"the",
"focused",
"element"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L282-L286 | train | 40,128 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.update_core_element_lists | def update_core_element_lists(self):
""" Maintains inner lists of selected elements with a specific core element class """
def get_selected_elements_of_core_class(core_class):
return set(element for element in self._selected if isinstance(element.core_element, core_class))
self._states = get_selected_elements_of_core_class(State)
self._transitions = get_selected_elements_of_core_class(Transition)
self._data_flows = get_selected_elements_of_core_class(DataFlow)
self._input_data_ports = get_selected_elements_of_core_class(InputDataPort)
self._output_data_ports = get_selected_elements_of_core_class(OutputDataPort)
self._scoped_variables = get_selected_elements_of_core_class(ScopedVariable)
self._outcomes = get_selected_elements_of_core_class(Outcome) | python | def update_core_element_lists(self):
""" Maintains inner lists of selected elements with a specific core element class """
def get_selected_elements_of_core_class(core_class):
return set(element for element in self._selected if isinstance(element.core_element, core_class))
self._states = get_selected_elements_of_core_class(State)
self._transitions = get_selected_elements_of_core_class(Transition)
self._data_flows = get_selected_elements_of_core_class(DataFlow)
self._input_data_ports = get_selected_elements_of_core_class(InputDataPort)
self._output_data_ports = get_selected_elements_of_core_class(OutputDataPort)
self._scoped_variables = get_selected_elements_of_core_class(ScopedVariable)
self._outcomes = get_selected_elements_of_core_class(Outcome) | [
"def",
"update_core_element_lists",
"(",
"self",
")",
":",
"def",
"get_selected_elements_of_core_class",
"(",
"core_class",
")",
":",
"return",
"set",
"(",
"element",
"for",
"element",
"in",
"self",
".",
"_selected",
"if",
"isinstance",
"(",
"element",
".",
"cor... | Maintains inner lists of selected elements with a specific core element class | [
"Maintains",
"inner",
"lists",
"of",
"selected",
"elements",
"with",
"a",
"specific",
"core",
"element",
"class"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L300-L310 | train | 40,129 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.get_selected_elements_of_core_class | def get_selected_elements_of_core_class(self, core_element_type):
"""Returns all selected elements having the specified `core_element_type` as state element class
:return: Subset of the selection, only containing elements having `core_element_type` as state element class
:rtype: set
"""
if core_element_type is Outcome:
return self.outcomes
elif core_element_type is InputDataPort:
return self.input_data_ports
elif core_element_type is OutputDataPort:
return self.output_data_ports
elif core_element_type is ScopedVariable:
return self.scoped_variables
elif core_element_type is Transition:
return self.transitions
elif core_element_type is DataFlow:
return self.data_flows
elif core_element_type is State:
return self.states
raise RuntimeError("Invalid core element type: " + core_element_type) | python | def get_selected_elements_of_core_class(self, core_element_type):
"""Returns all selected elements having the specified `core_element_type` as state element class
:return: Subset of the selection, only containing elements having `core_element_type` as state element class
:rtype: set
"""
if core_element_type is Outcome:
return self.outcomes
elif core_element_type is InputDataPort:
return self.input_data_ports
elif core_element_type is OutputDataPort:
return self.output_data_ports
elif core_element_type is ScopedVariable:
return self.scoped_variables
elif core_element_type is Transition:
return self.transitions
elif core_element_type is DataFlow:
return self.data_flows
elif core_element_type is State:
return self.states
raise RuntimeError("Invalid core element type: " + core_element_type) | [
"def",
"get_selected_elements_of_core_class",
"(",
"self",
",",
"core_element_type",
")",
":",
"if",
"core_element_type",
"is",
"Outcome",
":",
"return",
"self",
".",
"outcomes",
"elif",
"core_element_type",
"is",
"InputDataPort",
":",
"return",
"self",
".",
"input_... | Returns all selected elements having the specified `core_element_type` as state element class
:return: Subset of the selection, only containing elements having `core_element_type` as state element class
:rtype: set | [
"Returns",
"all",
"selected",
"elements",
"having",
"the",
"specified",
"core_element_type",
"as",
"state",
"element",
"class"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L375-L395 | train | 40,130 |
DLR-RM/RAFCON | source/rafcon/gui/models/selection.py | Selection.is_selected | def is_selected(self, model):
"""Checks whether the given model is selected
:param model:
:return: True if the model is within the selection, False else
:rtype: bool
"""
if model is None:
return len(self._selected) == 0
return model in self._selected | python | def is_selected(self, model):
"""Checks whether the given model is selected
:param model:
:return: True if the model is within the selection, False else
:rtype: bool
"""
if model is None:
return len(self._selected) == 0
return model in self._selected | [
"def",
"is_selected",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
"is",
"None",
":",
"return",
"len",
"(",
"self",
".",
"_selected",
")",
"==",
"0",
"return",
"model",
"in",
"self",
".",
"_selected"
] | Checks whether the given model is selected
:param model:
:return: True if the model is within the selection, False else
:rtype: bool | [
"Checks",
"whether",
"the",
"given",
"model",
"is",
"selected"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/selection.py#L397-L406 | train | 40,131 |
DLR-RM/RAFCON | source/rafcon/gui/utils/shell_execution.py | execute_command_with_path_in_process | def execute_command_with_path_in_process(command, path, shell=False, cwd=None, logger=None):
"""Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None
"""
if logger is None:
logger = _logger
logger.debug("Opening path with command: {0} {1}".format(command, path))
# This splits the command in a matter so that the command gets called in a separate shell and thus
# does not lock the window.
args = shlex.split('{0} "{1}"'.format(command, path))
try:
subprocess.Popen(args, shell=shell, cwd=cwd)
return True
except OSError as e:
logger.error('The operating system raised an error: {}'.format(e))
return False | python | def execute_command_with_path_in_process(command, path, shell=False, cwd=None, logger=None):
"""Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None
"""
if logger is None:
logger = _logger
logger.debug("Opening path with command: {0} {1}".format(command, path))
# This splits the command in a matter so that the command gets called in a separate shell and thus
# does not lock the window.
args = shlex.split('{0} "{1}"'.format(command, path))
try:
subprocess.Popen(args, shell=shell, cwd=cwd)
return True
except OSError as e:
logger.error('The operating system raised an error: {}'.format(e))
return False | [
"def",
"execute_command_with_path_in_process",
"(",
"command",
",",
"path",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"logger",
"is",
"None",
":",
"logger",
"=",
"_logger",
"logger",
".",
"debug",
"(... | Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None | [
"Executes",
"a",
"specific",
"command",
"in",
"a",
"separate",
"process",
"with",
"a",
"path",
"as",
"argument",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/utils/shell_execution.py#L8-L29 | train | 40,132 |
DLR-RM/RAFCON | source/rafcon/gui/utils/shell_execution.py | execute_command_in_process | def execute_command_in_process(command, shell=False, cwd=None, logger=None):
""" Executes a specific command in a separate process
:param command: the command to be executed
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None
"""
if logger is None:
logger = _logger
logger.debug("Run shell command: {0}".format(command))
try:
subprocess.Popen(command, shell=shell, cwd=cwd)
return True
except OSError as e:
logger.error('The operating system raised an error: {}'.format(e))
return False | python | def execute_command_in_process(command, shell=False, cwd=None, logger=None):
""" Executes a specific command in a separate process
:param command: the command to be executed
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None
"""
if logger is None:
logger = _logger
logger.debug("Run shell command: {0}".format(command))
try:
subprocess.Popen(command, shell=shell, cwd=cwd)
return True
except OSError as e:
logger.error('The operating system raised an error: {}'.format(e))
return False | [
"def",
"execute_command_in_process",
"(",
"command",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"logger",
"is",
"None",
":",
"logger",
"=",
"_logger",
"logger",
".",
"debug",
"(",
"\"Run shell command: ... | Executes a specific command in a separate process
:param command: the command to be executed
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional logger instance which can be handed from other module
:return: None | [
"Executes",
"a",
"specific",
"command",
"in",
"a",
"separate",
"process"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/utils/shell_execution.py#L32-L49 | train | 40,133 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel._load_child_state_models | def _load_child_state_models(self, load_meta_data):
"""Adds models for each child state of the state
:param bool load_meta_data: Whether to load the meta data of the child state
"""
self.states = {}
# Create model for each child class
child_states = self.state.states
for child_state in child_states.values():
# Create hierarchy
model_class = get_state_model_class_for_state(child_state)
if model_class is not None:
self._add_model(self.states, child_state, model_class, child_state.state_id, load_meta_data)
else:
logger.error("Unknown state type '{type:s}'. Cannot create model.".format(type=type(child_state))) | python | def _load_child_state_models(self, load_meta_data):
"""Adds models for each child state of the state
:param bool load_meta_data: Whether to load the meta data of the child state
"""
self.states = {}
# Create model for each child class
child_states = self.state.states
for child_state in child_states.values():
# Create hierarchy
model_class = get_state_model_class_for_state(child_state)
if model_class is not None:
self._add_model(self.states, child_state, model_class, child_state.state_id, load_meta_data)
else:
logger.error("Unknown state type '{type:s}'. Cannot create model.".format(type=type(child_state))) | [
"def",
"_load_child_state_models",
"(",
"self",
",",
"load_meta_data",
")",
":",
"self",
".",
"states",
"=",
"{",
"}",
"# Create model for each child class",
"child_states",
"=",
"self",
".",
"state",
".",
"states",
"for",
"child_state",
"in",
"child_states",
".",... | Adds models for each child state of the state
:param bool load_meta_data: Whether to load the meta data of the child state | [
"Adds",
"models",
"for",
"each",
"child",
"state",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L72-L86 | train | 40,134 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel._load_scoped_variable_models | def _load_scoped_variable_models(self):
""" Adds models for each scoped variable of the state """
self.scoped_variables = []
for scoped_variable in self.state.scoped_variables.values():
self._add_model(self.scoped_variables, scoped_variable, ScopedVariableModel) | python | def _load_scoped_variable_models(self):
""" Adds models for each scoped variable of the state """
self.scoped_variables = []
for scoped_variable in self.state.scoped_variables.values():
self._add_model(self.scoped_variables, scoped_variable, ScopedVariableModel) | [
"def",
"_load_scoped_variable_models",
"(",
"self",
")",
":",
"self",
".",
"scoped_variables",
"=",
"[",
"]",
"for",
"scoped_variable",
"in",
"self",
".",
"state",
".",
"scoped_variables",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"self",... | Adds models for each scoped variable of the state | [
"Adds",
"models",
"for",
"each",
"scoped",
"variable",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L88-L92 | train | 40,135 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel._load_data_flow_models | def _load_data_flow_models(self):
""" Adds models for each data flow of the state """
self.data_flows = []
for data_flow in self.state.data_flows.values():
self._add_model(self.data_flows, data_flow, DataFlowModel) | python | def _load_data_flow_models(self):
""" Adds models for each data flow of the state """
self.data_flows = []
for data_flow in self.state.data_flows.values():
self._add_model(self.data_flows, data_flow, DataFlowModel) | [
"def",
"_load_data_flow_models",
"(",
"self",
")",
":",
"self",
".",
"data_flows",
"=",
"[",
"]",
"for",
"data_flow",
"in",
"self",
".",
"state",
".",
"data_flows",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"self",
".",
"data_flows",
... | Adds models for each data flow of the state | [
"Adds",
"models",
"for",
"each",
"data",
"flow",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L94-L98 | train | 40,136 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel._load_transition_models | def _load_transition_models(self):
""" Adds models for each transition of the state """
self.transitions = []
for transition in self.state.transitions.values():
self._add_model(self.transitions, transition, TransitionModel) | python | def _load_transition_models(self):
""" Adds models for each transition of the state """
self.transitions = []
for transition in self.state.transitions.values():
self._add_model(self.transitions, transition, TransitionModel) | [
"def",
"_load_transition_models",
"(",
"self",
")",
":",
"self",
".",
"transitions",
"=",
"[",
"]",
"for",
"transition",
"in",
"self",
".",
"state",
".",
"transitions",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"self",
".",
"transitio... | Adds models for each transition of the state | [
"Adds",
"models",
"for",
"each",
"transition",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L100-L104 | train | 40,137 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel.update_child_models | def update_child_models(self, _, name, info):
""" This method is always triggered when the state model changes
It keeps the following models/model-lists consistent:
transition models
data-flow models
state models
scoped variable models
"""
# Update is_start flag in child states if the start state has changed (eventually)
if info.method_name in ['start_state_id', 'add_transition', 'remove_transition']:
self.update_child_is_start()
if info.method_name in ["add_transition", "remove_transition", "transitions"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("transition")
elif info.method_name in ["add_data_flow", "remove_data_flow", "data_flows"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("data_flow")
elif info.method_name in ["add_state", "remove_state", "states"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("state", info)
elif info.method_name in ["add_scoped_variable", "remove_scoped_variable", "scoped_variables"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("scoped_variable")
else:
return
if isinstance(info.result, Exception):
# Do nothing if the observed function raised an exception
pass
elif "add" in info.method_name:
self.add_missing_model(model_list, data_list, model_name, model_class, model_key)
elif "remove" in info.method_name:
destroy = info.kwargs.get('destroy', True)
recursive = info.kwargs.get('recursive', True)
self.remove_specific_model(model_list, info.result, model_key, recursive, destroy)
elif info.method_name in ["transitions", "data_flows", "states", "scoped_variables"]:
self.re_initiate_model_list(model_list, data_list, model_name, model_class, model_key) | python | def update_child_models(self, _, name, info):
""" This method is always triggered when the state model changes
It keeps the following models/model-lists consistent:
transition models
data-flow models
state models
scoped variable models
"""
# Update is_start flag in child states if the start state has changed (eventually)
if info.method_name in ['start_state_id', 'add_transition', 'remove_transition']:
self.update_child_is_start()
if info.method_name in ["add_transition", "remove_transition", "transitions"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("transition")
elif info.method_name in ["add_data_flow", "remove_data_flow", "data_flows"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("data_flow")
elif info.method_name in ["add_state", "remove_state", "states"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("state", info)
elif info.method_name in ["add_scoped_variable", "remove_scoped_variable", "scoped_variables"]:
(model_list, data_list, model_name, model_class, model_key) = self._get_model_info("scoped_variable")
else:
return
if isinstance(info.result, Exception):
# Do nothing if the observed function raised an exception
pass
elif "add" in info.method_name:
self.add_missing_model(model_list, data_list, model_name, model_class, model_key)
elif "remove" in info.method_name:
destroy = info.kwargs.get('destroy', True)
recursive = info.kwargs.get('recursive', True)
self.remove_specific_model(model_list, info.result, model_key, recursive, destroy)
elif info.method_name in ["transitions", "data_flows", "states", "scoped_variables"]:
self.re_initiate_model_list(model_list, data_list, model_name, model_class, model_key) | [
"def",
"update_child_models",
"(",
"self",
",",
"_",
",",
"name",
",",
"info",
")",
":",
"# Update is_start flag in child states if the start state has changed (eventually)",
"if",
"info",
".",
"method_name",
"in",
"[",
"'start_state_id'",
",",
"'add_transition'",
",",
... | This method is always triggered when the state model changes
It keeps the following models/model-lists consistent:
transition models
data-flow models
state models
scoped variable models | [
"This",
"method",
"is",
"always",
"triggered",
"when",
"the",
"state",
"model",
"changes"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L266-L301 | train | 40,138 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel.get_scoped_variable_m | def get_scoped_variable_m(self, data_port_id):
"""Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id
"""
for scoped_variable_m in self.scoped_variables:
if scoped_variable_m.scoped_variable.data_port_id == data_port_id:
return scoped_variable_m
return None | python | def get_scoped_variable_m(self, data_port_id):
"""Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id
"""
for scoped_variable_m in self.scoped_variables:
if scoped_variable_m.scoped_variable.data_port_id == data_port_id:
return scoped_variable_m
return None | [
"def",
"get_scoped_variable_m",
"(",
"self",
",",
"data_port_id",
")",
":",
"for",
"scoped_variable_m",
"in",
"self",
".",
"scoped_variables",
":",
"if",
"scoped_variable_m",
".",
"scoped_variable",
".",
"data_port_id",
"==",
"data_port_id",
":",
"return",
"scoped_v... | Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id | [
"Returns",
"the",
"scoped",
"variable",
"model",
"for",
"the",
"given",
"data",
"port",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L371-L380 | train | 40,139 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel.get_transition_m | def get_transition_m(self, transition_id):
"""Searches and return the transition model with the given in the given container state model
:param transition_id: The transition id to be searched
:return: The model of the transition or None if it is not found
"""
for transition_m in self.transitions:
if transition_m.transition.transition_id == transition_id:
return transition_m
return None | python | def get_transition_m(self, transition_id):
"""Searches and return the transition model with the given in the given container state model
:param transition_id: The transition id to be searched
:return: The model of the transition or None if it is not found
"""
for transition_m in self.transitions:
if transition_m.transition.transition_id == transition_id:
return transition_m
return None | [
"def",
"get_transition_m",
"(",
"self",
",",
"transition_id",
")",
":",
"for",
"transition_m",
"in",
"self",
".",
"transitions",
":",
"if",
"transition_m",
".",
"transition",
".",
"transition_id",
"==",
"transition_id",
":",
"return",
"transition_m",
"return",
"... | Searches and return the transition model with the given in the given container state model
:param transition_id: The transition id to be searched
:return: The model of the transition or None if it is not found | [
"Searches",
"and",
"return",
"the",
"transition",
"model",
"with",
"the",
"given",
"in",
"the",
"given",
"container",
"state",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L398-L407 | train | 40,140 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel.get_data_flow_m | def get_data_flow_m(self, data_flow_id):
"""Searches and return the data flow model with the given in the given container state model
:param data_flow_id: The data flow id to be searched
:return: The model of the data flow or None if it is not found
"""
for data_flow_m in self.data_flows:
if data_flow_m.data_flow.data_flow_id == data_flow_id:
return data_flow_m
return None | python | def get_data_flow_m(self, data_flow_id):
"""Searches and return the data flow model with the given in the given container state model
:param data_flow_id: The data flow id to be searched
:return: The model of the data flow or None if it is not found
"""
for data_flow_m in self.data_flows:
if data_flow_m.data_flow.data_flow_id == data_flow_id:
return data_flow_m
return None | [
"def",
"get_data_flow_m",
"(",
"self",
",",
"data_flow_id",
")",
":",
"for",
"data_flow_m",
"in",
"self",
".",
"data_flows",
":",
"if",
"data_flow_m",
".",
"data_flow",
".",
"data_flow_id",
"==",
"data_flow_id",
":",
"return",
"data_flow_m",
"return",
"None"
] | Searches and return the data flow model with the given in the given container state model
:param data_flow_id: The data flow id to be searched
:return: The model of the data flow or None if it is not found | [
"Searches",
"and",
"return",
"the",
"data",
"flow",
"model",
"with",
"the",
"given",
"in",
"the",
"given",
"container",
"state",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L409-L418 | train | 40,141 |
DLR-RM/RAFCON | source/rafcon/gui/models/container_state.py | ContainerStateModel.store_meta_data | def store_meta_data(self, copy_path=None):
"""Store meta data of container states to the filesystem
Recursively stores meta data of child states. For further insides read the description of also called respective
super class method.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
"""
super(ContainerStateModel, self).store_meta_data(copy_path)
for state_key, state in self.states.items():
state.store_meta_data(copy_path) | python | def store_meta_data(self, copy_path=None):
"""Store meta data of container states to the filesystem
Recursively stores meta data of child states. For further insides read the description of also called respective
super class method.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
"""
super(ContainerStateModel, self).store_meta_data(copy_path)
for state_key, state in self.states.items():
state.store_meta_data(copy_path) | [
"def",
"store_meta_data",
"(",
"self",
",",
"copy_path",
"=",
"None",
")",
":",
"super",
"(",
"ContainerStateModel",
",",
"self",
")",
".",
"store_meta_data",
"(",
"copy_path",
")",
"for",
"state_key",
",",
"state",
"in",
"self",
".",
"states",
".",
"items... | Store meta data of container states to the filesystem
Recursively stores meta data of child states. For further insides read the description of also called respective
super class method.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine | [
"Store",
"meta",
"data",
"of",
"container",
"states",
"to",
"the",
"filesystem"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/container_state.py#L422-L432 | train | 40,142 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | add_state_machine | def add_state_machine(widget, event=None):
"""Create a new state-machine when the user clicks on the '+' next to the tabs"""
logger.debug("Creating new state-machine...")
root_state = HierarchyState("new root state")
state_machine = StateMachine(root_state)
rafcon.core.singleton.state_machine_manager.add_state_machine(state_machine) | python | def add_state_machine(widget, event=None):
"""Create a new state-machine when the user clicks on the '+' next to the tabs"""
logger.debug("Creating new state-machine...")
root_state = HierarchyState("new root state")
state_machine = StateMachine(root_state)
rafcon.core.singleton.state_machine_manager.add_state_machine(state_machine) | [
"def",
"add_state_machine",
"(",
"widget",
",",
"event",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Creating new state-machine...\"",
")",
"root_state",
"=",
"HierarchyState",
"(",
"\"new root state\"",
")",
"state_machine",
"=",
"StateMachine",
"(",
"... | Create a new state-machine when the user clicks on the '+' next to the tabs | [
"Create",
"a",
"new",
"state",
"-",
"machine",
"when",
"the",
"user",
"clicks",
"on",
"the",
"+",
"next",
"to",
"the",
"tabs"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L106-L111 | train | 40,143 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.register_actions | def register_actions(self, shortcut_manager):
"""Register callback methods fot triggered actions.
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for_action('close', self.on_close_shortcut)
# Call register_action of parent in order to register actions for child controllers
super(StateMachinesEditorController, self).register_actions(shortcut_manager) | python | def register_actions(self, shortcut_manager):
"""Register callback methods fot triggered actions.
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for_action('close', self.on_close_shortcut)
# Call register_action of parent in order to register actions for child controllers
super(StateMachinesEditorController, self).register_actions(shortcut_manager) | [
"def",
"register_actions",
"(",
"self",
",",
"shortcut_manager",
")",
":",
"shortcut_manager",
".",
"add_callback_for_action",
"(",
"'close'",
",",
"self",
".",
"on_close_shortcut",
")",
"# Call register_action of parent in order to register actions for child controllers",
"sup... | Register callback methods fot triggered actions.
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. | [
"Register",
"callback",
"methods",
"fot",
"triggered",
"actions",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L143-L152 | train | 40,144 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.close_state_machine | def close_state_machine(self, widget, page_number, event=None):
"""Triggered when the close button in the tab is clicked
"""
page = widget.get_nth_page(page_number)
for tab_info in self.tabs.values():
if tab_info['page'] is page:
state_machine_m = tab_info['state_machine_m']
self.on_close_clicked(event, state_machine_m, None, force=False)
return | python | def close_state_machine(self, widget, page_number, event=None):
"""Triggered when the close button in the tab is clicked
"""
page = widget.get_nth_page(page_number)
for tab_info in self.tabs.values():
if tab_info['page'] is page:
state_machine_m = tab_info['state_machine_m']
self.on_close_clicked(event, state_machine_m, None, force=False)
return | [
"def",
"close_state_machine",
"(",
"self",
",",
"widget",
",",
"page_number",
",",
"event",
"=",
"None",
")",
":",
"page",
"=",
"widget",
".",
"get_nth_page",
"(",
"page_number",
")",
"for",
"tab_info",
"in",
"self",
".",
"tabs",
".",
"values",
"(",
")",... | Triggered when the close button in the tab is clicked | [
"Triggered",
"when",
"the",
"close",
"button",
"in",
"the",
"tab",
"is",
"clicked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L154-L162 | train | 40,145 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.add_graphical_state_machine_editor | def add_graphical_state_machine_editor(self, state_machine_m):
"""Add to for new state machine
If a new state machine was added, a new tab is created with a graphical editor for this state machine.
:param StateMachineModel state_machine_m: The new state machine model
"""
assert isinstance(state_machine_m, StateMachineModel)
sm_id = state_machine_m.state_machine.state_machine_id
logger.debug("Create new graphical editor for state machine with id %s" % str(sm_id))
graphical_editor_view = GraphicalEditorGaphasView(state_machine_m)
graphical_editor_ctrl = GraphicalEditorGaphasController(state_machine_m, graphical_editor_view)
self.add_controller(sm_id, graphical_editor_ctrl)
tab, tab_label = create_tab_header('', self.on_close_clicked, self.on_mouse_right_click,
state_machine_m, 'refused')
set_tab_label_texts(tab_label, state_machine_m, state_machine_m.state_machine.marked_dirty)
page = graphical_editor_view['main_frame']
self.view.notebook.append_page(page, tab)
self.view.notebook.set_tab_reorderable(page, True)
page.show_all()
self.tabs[sm_id] = {'page': page,
'state_machine_m': state_machine_m,
'file_system_path': state_machine_m.state_machine.file_system_path,
'marked_dirty': state_machine_m.state_machine.marked_dirty,
'root_state_name': state_machine_m.state_machine.root_state.name}
self.observe_model(state_machine_m)
graphical_editor_view.show()
self.view.notebook.show()
self.last_focused_state_machine_ids.append(sm_id) | python | def add_graphical_state_machine_editor(self, state_machine_m):
"""Add to for new state machine
If a new state machine was added, a new tab is created with a graphical editor for this state machine.
:param StateMachineModel state_machine_m: The new state machine model
"""
assert isinstance(state_machine_m, StateMachineModel)
sm_id = state_machine_m.state_machine.state_machine_id
logger.debug("Create new graphical editor for state machine with id %s" % str(sm_id))
graphical_editor_view = GraphicalEditorGaphasView(state_machine_m)
graphical_editor_ctrl = GraphicalEditorGaphasController(state_machine_m, graphical_editor_view)
self.add_controller(sm_id, graphical_editor_ctrl)
tab, tab_label = create_tab_header('', self.on_close_clicked, self.on_mouse_right_click,
state_machine_m, 'refused')
set_tab_label_texts(tab_label, state_machine_m, state_machine_m.state_machine.marked_dirty)
page = graphical_editor_view['main_frame']
self.view.notebook.append_page(page, tab)
self.view.notebook.set_tab_reorderable(page, True)
page.show_all()
self.tabs[sm_id] = {'page': page,
'state_machine_m': state_machine_m,
'file_system_path': state_machine_m.state_machine.file_system_path,
'marked_dirty': state_machine_m.state_machine.marked_dirty,
'root_state_name': state_machine_m.state_machine.root_state.name}
self.observe_model(state_machine_m)
graphical_editor_view.show()
self.view.notebook.show()
self.last_focused_state_machine_ids.append(sm_id) | [
"def",
"add_graphical_state_machine_editor",
"(",
"self",
",",
"state_machine_m",
")",
":",
"assert",
"isinstance",
"(",
"state_machine_m",
",",
"StateMachineModel",
")",
"sm_id",
"=",
"state_machine_m",
".",
"state_machine",
".",
"state_machine_id",
"logger",
".",
"d... | Add to for new state machine
If a new state machine was added, a new tab is created with a graphical editor for this state machine.
:param StateMachineModel state_machine_m: The new state machine model | [
"Add",
"to",
"for",
"new",
"state",
"machine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L211-L247 | train | 40,146 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.notification_selected_sm_changed | def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
page_id = self.get_page_num(selected_state_machine_id)
# to retrieve the current tab colors
number_of_pages = self.view["notebook"].get_n_pages()
old_label_colors = list(range(number_of_pages))
for p in range(number_of_pages):
page = self.view["notebook"].get_nth_page(p)
label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]
# old_label_colors[p] = label.get_style().fg[Gtk.StateType.NORMAL]
old_label_colors[p] = label.get_style_context().get_color(Gtk.StateType.NORMAL)
if not self.view.notebook.get_current_page() == page_id:
self.view.notebook.set_current_page(page_id)
# set the old colors
for p in range(number_of_pages):
page = self.view["notebook"].get_nth_page(p)
label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]
# Gtk TODO
style = label.get_style_context() | python | def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
page_id = self.get_page_num(selected_state_machine_id)
# to retrieve the current tab colors
number_of_pages = self.view["notebook"].get_n_pages()
old_label_colors = list(range(number_of_pages))
for p in range(number_of_pages):
page = self.view["notebook"].get_nth_page(p)
label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]
# old_label_colors[p] = label.get_style().fg[Gtk.StateType.NORMAL]
old_label_colors[p] = label.get_style_context().get_color(Gtk.StateType.NORMAL)
if not self.view.notebook.get_current_page() == page_id:
self.view.notebook.set_current_page(page_id)
# set the old colors
for p in range(number_of_pages):
page = self.view["notebook"].get_nth_page(p)
label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]
# Gtk TODO
style = label.get_style_context() | [
"def",
"notification_selected_sm_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"selected_state_machine_id",
"=",
"self",
".",
"model",
".",
"selected_state_machine_id",
"if",
"selected_state_machine_id",
"is",
"None",
":",
"return",
"... | If a new state machine is selected, make sure the tab is open | [
"If",
"a",
"new",
"state",
"machine",
"is",
"selected",
"make",
"sure",
"the",
"tab",
"is",
"open"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L250-L276 | train | 40,147 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.update_state_machine_tab_label | def update_state_machine_tab_label(self, state_machine_m):
""" Updates tab label if needed because system path, root state name or marked_dirty flag changed
:param StateMachineModel state_machine_m: State machine model that has changed
:return:
"""
sm_id = state_machine_m.state_machine.state_machine_id
if sm_id in self.tabs:
sm = state_machine_m.state_machine
# create new tab label if tab label properties are not up to date
if not self.tabs[sm_id]['marked_dirty'] == sm.marked_dirty or \
not self.tabs[sm_id]['file_system_path'] == sm.file_system_path or \
not self.tabs[sm_id]['root_state_name'] == sm.root_state.name:
label = self.view["notebook"].get_tab_label(self.tabs[sm_id]["page"]).get_child().get_children()[0]
set_tab_label_texts(label, state_machine_m, unsaved_changes=sm.marked_dirty)
self.tabs[sm_id]['file_system_path'] = sm.file_system_path
self.tabs[sm_id]['marked_dirty'] = sm.marked_dirty
self.tabs[sm_id]['root_state_name'] = sm.root_state.name
else:
logger.warning("State machine '{0}' tab label can not be updated there is no tab.".format(sm_id)) | python | def update_state_machine_tab_label(self, state_machine_m):
""" Updates tab label if needed because system path, root state name or marked_dirty flag changed
:param StateMachineModel state_machine_m: State machine model that has changed
:return:
"""
sm_id = state_machine_m.state_machine.state_machine_id
if sm_id in self.tabs:
sm = state_machine_m.state_machine
# create new tab label if tab label properties are not up to date
if not self.tabs[sm_id]['marked_dirty'] == sm.marked_dirty or \
not self.tabs[sm_id]['file_system_path'] == sm.file_system_path or \
not self.tabs[sm_id]['root_state_name'] == sm.root_state.name:
label = self.view["notebook"].get_tab_label(self.tabs[sm_id]["page"]).get_child().get_children()[0]
set_tab_label_texts(label, state_machine_m, unsaved_changes=sm.marked_dirty)
self.tabs[sm_id]['file_system_path'] = sm.file_system_path
self.tabs[sm_id]['marked_dirty'] = sm.marked_dirty
self.tabs[sm_id]['root_state_name'] = sm.root_state.name
else:
logger.warning("State machine '{0}' tab label can not be updated there is no tab.".format(sm_id)) | [
"def",
"update_state_machine_tab_label",
"(",
"self",
",",
"state_machine_m",
")",
":",
"sm_id",
"=",
"state_machine_m",
".",
"state_machine",
".",
"state_machine_id",
"if",
"sm_id",
"in",
"self",
".",
"tabs",
":",
"sm",
"=",
"state_machine_m",
".",
"state_machine... | Updates tab label if needed because system path, root state name or marked_dirty flag changed
:param StateMachineModel state_machine_m: State machine model that has changed
:return: | [
"Updates",
"tab",
"label",
"if",
"needed",
"because",
"system",
"path",
"root",
"state",
"name",
"or",
"marked_dirty",
"flag",
"changed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L306-L327 | train | 40,148 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.on_close_clicked | def on_close_clicked(self, event, state_machine_m, result, force=False):
"""Triggered when the close button of a state machine tab is clicked
Closes state machine if it is saved. Otherwise gives the user the option to 'Close without Saving' or to 'Cancel
the Close Operation'
:param state_machine_m: The selected state machine model.
"""
from rafcon.core.singleton import state_machine_execution_engine, state_machine_manager
force = True if event is not None and hasattr(event, 'state') \
and event.get_state() & Gdk.ModifierType.SHIFT_MASK \
and event.get_state() & Gdk.ModifierType.CONTROL_MASK else force
def remove_state_machine_m():
state_machine_id = state_machine_m.state_machine.state_machine_id
if state_machine_id in self.model.state_machine_manager.state_machines:
self.model.state_machine_manager.remove_state_machine(state_machine_id)
def push_sm_running_dialog():
message_string = "The state machine is still running. Are you sure you want to close?"
dialog = RAFCONButtonDialog(message_string, ["Stop and close", "Cancel"],
message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1:
logger.debug("State machine execution is being stopped")
state_machine_execution_engine.stop()
state_machine_execution_engine.join()
# wait for gui is needed; otherwise the signals related to the execution engine cannot
# be processed properly by the state machine under destruction
rafcon.gui.utils.wait_for_gui()
remove_state_machine_m()
return True
elif response_id == 2:
logger.debug("State machine execution will keep running")
return False
def push_sm_dirty_dialog():
sm_id = state_machine_m.state_machine.state_machine_id
root_state_name = state_machine_m.root_state.state.name
message_string = "There are unsaved changes in the state machine '{0}' with id {1}. Do you want to close " \
"the state machine anyway?".format(root_state_name, sm_id)
dialog = RAFCONButtonDialog(message_string, ["Close without saving", "Cancel"],
message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1: # Close without saving pressed
remove_state_machine_m()
return True
else:
logger.debug("Closing of state machine canceled")
return False
# sm running
if not state_machine_execution_engine.finished_or_stopped() and \
state_machine_manager.active_state_machine_id == state_machine_m.state_machine.state_machine_id:
return push_sm_running_dialog()
# close is forced -> sm not saved
elif force:
remove_state_machine_m()
return True
# sm dirty -> save sm request dialog
elif state_machine_m.state_machine.marked_dirty:
return push_sm_dirty_dialog()
else:
remove_state_machine_m()
return True | python | def on_close_clicked(self, event, state_machine_m, result, force=False):
"""Triggered when the close button of a state machine tab is clicked
Closes state machine if it is saved. Otherwise gives the user the option to 'Close without Saving' or to 'Cancel
the Close Operation'
:param state_machine_m: The selected state machine model.
"""
from rafcon.core.singleton import state_machine_execution_engine, state_machine_manager
force = True if event is not None and hasattr(event, 'state') \
and event.get_state() & Gdk.ModifierType.SHIFT_MASK \
and event.get_state() & Gdk.ModifierType.CONTROL_MASK else force
def remove_state_machine_m():
state_machine_id = state_machine_m.state_machine.state_machine_id
if state_machine_id in self.model.state_machine_manager.state_machines:
self.model.state_machine_manager.remove_state_machine(state_machine_id)
def push_sm_running_dialog():
message_string = "The state machine is still running. Are you sure you want to close?"
dialog = RAFCONButtonDialog(message_string, ["Stop and close", "Cancel"],
message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1:
logger.debug("State machine execution is being stopped")
state_machine_execution_engine.stop()
state_machine_execution_engine.join()
# wait for gui is needed; otherwise the signals related to the execution engine cannot
# be processed properly by the state machine under destruction
rafcon.gui.utils.wait_for_gui()
remove_state_machine_m()
return True
elif response_id == 2:
logger.debug("State machine execution will keep running")
return False
def push_sm_dirty_dialog():
sm_id = state_machine_m.state_machine.state_machine_id
root_state_name = state_machine_m.root_state.state.name
message_string = "There are unsaved changes in the state machine '{0}' with id {1}. Do you want to close " \
"the state machine anyway?".format(root_state_name, sm_id)
dialog = RAFCONButtonDialog(message_string, ["Close without saving", "Cancel"],
message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1: # Close without saving pressed
remove_state_machine_m()
return True
else:
logger.debug("Closing of state machine canceled")
return False
# sm running
if not state_machine_execution_engine.finished_or_stopped() and \
state_machine_manager.active_state_machine_id == state_machine_m.state_machine.state_machine_id:
return push_sm_running_dialog()
# close is forced -> sm not saved
elif force:
remove_state_machine_m()
return True
# sm dirty -> save sm request dialog
elif state_machine_m.state_machine.marked_dirty:
return push_sm_dirty_dialog()
else:
remove_state_machine_m()
return True | [
"def",
"on_close_clicked",
"(",
"self",
",",
"event",
",",
"state_machine_m",
",",
"result",
",",
"force",
"=",
"False",
")",
":",
"from",
"rafcon",
".",
"core",
".",
"singleton",
"import",
"state_machine_execution_engine",
",",
"state_machine_manager",
"force",
... | Triggered when the close button of a state machine tab is clicked
Closes state machine if it is saved. Otherwise gives the user the option to 'Close without Saving' or to 'Cancel
the Close Operation'
:param state_machine_m: The selected state machine model. | [
"Triggered",
"when",
"the",
"close",
"button",
"of",
"a",
"state",
"machine",
"tab",
"is",
"clicked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L354-L422 | train | 40,149 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.close_all_pages | def close_all_pages(self):
"""Closes all tabs of the state machines editor."""
state_machine_m_list = [tab['state_machine_m'] for tab in self.tabs.values()]
for state_machine_m in state_machine_m_list:
self.on_close_clicked(None, state_machine_m, None, force=True) | python | def close_all_pages(self):
"""Closes all tabs of the state machines editor."""
state_machine_m_list = [tab['state_machine_m'] for tab in self.tabs.values()]
for state_machine_m in state_machine_m_list:
self.on_close_clicked(None, state_machine_m, None, force=True) | [
"def",
"close_all_pages",
"(",
"self",
")",
":",
"state_machine_m_list",
"=",
"[",
"tab",
"[",
"'state_machine_m'",
"]",
"for",
"tab",
"in",
"self",
".",
"tabs",
".",
"values",
"(",
")",
"]",
"for",
"state_machine_m",
"in",
"state_machine_m_list",
":",
"self... | Closes all tabs of the state machines editor. | [
"Closes",
"all",
"tabs",
"of",
"the",
"state",
"machines",
"editor",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L458-L462 | train | 40,150 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.refresh_state_machines | def refresh_state_machines(self, state_machine_ids):
""" Refresh list af state machine tabs
:param list state_machine_ids: List of state machine ids to be refreshed
:return:
"""
# remember current selected state machine id
currently_selected_sm_id = None
if self.model.get_selected_state_machine_model():
currently_selected_sm_id = self.model.get_selected_state_machine_model().state_machine.state_machine_id
# create a dictionary from state machine id to state machine path and one for tab page number for recovery
state_machine_path_by_sm_id = {}
page_num_by_sm_id = {}
for sm_id, sm in self.model.state_machine_manager.state_machines.items():
# the sm.base_path is only None if the state machine has never been loaded or saved before
if sm_id in state_machine_ids and sm.file_system_path is not None:
state_machine_path_by_sm_id[sm_id] = sm.file_system_path
page_num_by_sm_id[sm_id] = self.get_page_num(sm_id)
# close all state machine in list and remember if one was not closed
for sm_id in state_machine_ids:
was_closed = self.on_close_clicked(None, self.model.state_machines[sm_id], None, force=True)
if not was_closed and sm_id in page_num_by_sm_id:
logger.info("State machine with id {0} will not be re-open because was not closed.".format(sm_id))
del state_machine_path_by_sm_id[sm_id]
del page_num_by_sm_id[sm_id]
# reload state machines from file system
try:
self.model.state_machine_manager.open_state_machines(state_machine_path_by_sm_id)
except AttributeError as e:
logger.warning("Not all state machines were re-open because {0}".format(e))
import rafcon.gui.utils
rafcon.gui.utils.wait_for_gui() # TODO check again this is needed to secure that all sm-models are generated
# recover tab arrangement
self.rearrange_state_machines(page_num_by_sm_id)
# recover initial selected state machine and case handling if now state machine is open anymore
if currently_selected_sm_id:
# case if only unsaved state machines are open
if currently_selected_sm_id in self.model.state_machine_manager.state_machines:
self.set_active_state_machine(currently_selected_sm_id) | python | def refresh_state_machines(self, state_machine_ids):
""" Refresh list af state machine tabs
:param list state_machine_ids: List of state machine ids to be refreshed
:return:
"""
# remember current selected state machine id
currently_selected_sm_id = None
if self.model.get_selected_state_machine_model():
currently_selected_sm_id = self.model.get_selected_state_machine_model().state_machine.state_machine_id
# create a dictionary from state machine id to state machine path and one for tab page number for recovery
state_machine_path_by_sm_id = {}
page_num_by_sm_id = {}
for sm_id, sm in self.model.state_machine_manager.state_machines.items():
# the sm.base_path is only None if the state machine has never been loaded or saved before
if sm_id in state_machine_ids and sm.file_system_path is not None:
state_machine_path_by_sm_id[sm_id] = sm.file_system_path
page_num_by_sm_id[sm_id] = self.get_page_num(sm_id)
# close all state machine in list and remember if one was not closed
for sm_id in state_machine_ids:
was_closed = self.on_close_clicked(None, self.model.state_machines[sm_id], None, force=True)
if not was_closed and sm_id in page_num_by_sm_id:
logger.info("State machine with id {0} will not be re-open because was not closed.".format(sm_id))
del state_machine_path_by_sm_id[sm_id]
del page_num_by_sm_id[sm_id]
# reload state machines from file system
try:
self.model.state_machine_manager.open_state_machines(state_machine_path_by_sm_id)
except AttributeError as e:
logger.warning("Not all state machines were re-open because {0}".format(e))
import rafcon.gui.utils
rafcon.gui.utils.wait_for_gui() # TODO check again this is needed to secure that all sm-models are generated
# recover tab arrangement
self.rearrange_state_machines(page_num_by_sm_id)
# recover initial selected state machine and case handling if now state machine is open anymore
if currently_selected_sm_id:
# case if only unsaved state machines are open
if currently_selected_sm_id in self.model.state_machine_manager.state_machines:
self.set_active_state_machine(currently_selected_sm_id) | [
"def",
"refresh_state_machines",
"(",
"self",
",",
"state_machine_ids",
")",
":",
"# remember current selected state machine id",
"currently_selected_sm_id",
"=",
"None",
"if",
"self",
".",
"model",
".",
"get_selected_state_machine_model",
"(",
")",
":",
"currently_selected... | Refresh list af state machine tabs
:param list state_machine_ids: List of state machine ids to be refreshed
:return: | [
"Refresh",
"list",
"af",
"state",
"machine",
"tabs"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L464-L507 | train | 40,151 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.refresh_all_state_machines | def refresh_all_state_machines(self):
""" Refreshes all state machine tabs
"""
self.refresh_state_machines(list(self.model.state_machine_manager.state_machines.keys())) | python | def refresh_all_state_machines(self):
""" Refreshes all state machine tabs
"""
self.refresh_state_machines(list(self.model.state_machine_manager.state_machines.keys())) | [
"def",
"refresh_all_state_machines",
"(",
"self",
")",
":",
"self",
".",
"refresh_state_machines",
"(",
"list",
"(",
"self",
".",
"model",
".",
"state_machine_manager",
".",
"state_machines",
".",
"keys",
"(",
")",
")",
")"
] | Refreshes all state machine tabs | [
"Refreshes",
"all",
"state",
"machine",
"tabs"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L516-L519 | train | 40,152 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machines_editor.py | StateMachinesEditorController.execution_engine_model_changed | def execution_engine_model_changed(self, model, prop_name, info):
"""High light active state machine. """
notebook = self.view['notebook']
active_state_machine_id = self.model.state_machine_manager.active_state_machine_id
if active_state_machine_id is None:
# un-mark all state machine that are marked with execution-running style class
for tab in self.tabs.values():
label = notebook.get_tab_label(tab['page']).get_child().get_children()[0]
if label.get_style_context().has_class(constants.execution_running_style_class):
label.get_style_context().remove_class(constants.execution_running_style_class)
else:
# mark active state machine with execution-running style class
page = self.get_page_for_state_machine_id(active_state_machine_id)
if page:
label = notebook.get_tab_label(page).get_child().get_children()[0]
label.get_style_context().add_class(constants.execution_running_style_class) | python | def execution_engine_model_changed(self, model, prop_name, info):
"""High light active state machine. """
notebook = self.view['notebook']
active_state_machine_id = self.model.state_machine_manager.active_state_machine_id
if active_state_machine_id is None:
# un-mark all state machine that are marked with execution-running style class
for tab in self.tabs.values():
label = notebook.get_tab_label(tab['page']).get_child().get_children()[0]
if label.get_style_context().has_class(constants.execution_running_style_class):
label.get_style_context().remove_class(constants.execution_running_style_class)
else:
# mark active state machine with execution-running style class
page = self.get_page_for_state_machine_id(active_state_machine_id)
if page:
label = notebook.get_tab_label(page).get_child().get_children()[0]
label.get_style_context().add_class(constants.execution_running_style_class) | [
"def",
"execution_engine_model_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"notebook",
"=",
"self",
".",
"view",
"[",
"'notebook'",
"]",
"active_state_machine_id",
"=",
"self",
".",
"model",
".",
"state_machine_manager",
".",
... | High light active state machine. | [
"High",
"light",
"active",
"state",
"machine",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machines_editor.py#L535-L552 | train | 40,153 |
DLR-RM/RAFCON | source/rafcon/gui/action.py | meta_dump_or_deepcopy | def meta_dump_or_deepcopy(meta):
"""Function to observe meta data vivi-dict copy process and to debug it at one point"""
if DEBUG_META_REFERENCES: # debug copy
from rafcon.gui.helpers.meta_data import meta_data_reference_check
meta_data_reference_check(meta)
return copy.deepcopy(meta) | python | def meta_dump_or_deepcopy(meta):
"""Function to observe meta data vivi-dict copy process and to debug it at one point"""
if DEBUG_META_REFERENCES: # debug copy
from rafcon.gui.helpers.meta_data import meta_data_reference_check
meta_data_reference_check(meta)
return copy.deepcopy(meta) | [
"def",
"meta_dump_or_deepcopy",
"(",
"meta",
")",
":",
"if",
"DEBUG_META_REFERENCES",
":",
"# debug copy",
"from",
"rafcon",
".",
"gui",
".",
"helpers",
".",
"meta_data",
"import",
"meta_data_reference_check",
"meta_data_reference_check",
"(",
"meta",
")",
"return",
... | Function to observe meta data vivi-dict copy process and to debug it at one point | [
"Function",
"to",
"observe",
"meta",
"data",
"vivi",
"-",
"dict",
"copy",
"process",
"and",
"to",
"debug",
"it",
"at",
"one",
"point"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/action.py#L176-L181 | train | 40,154 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/utils/cache/image_cache.py | ImageCache.get_cached_image | def get_cached_image(self, width, height, zoom, parameters=None, clear=False):
"""Get ImageSurface object, if possible, cached
The method checks whether the image was already rendered. This is done by comparing the passed size and
parameters with those of the last image. If they are equal, the cached image is returned. Otherwise,
a new ImageSurface with the specified dimensions is created and returned.
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:param clear: If True, the cache is emptied, thus the image won't be retrieved from cache
:returns: The flag is True when the image is retrieved from the cache, otherwise False; The cached image
surface or a blank one with the desired size; The zoom parameter when the image was stored
:rtype: bool, ImageSurface, float
"""
global MAX_ALLOWED_AREA
if not parameters:
parameters = {}
if self.__compare_parameters(width, height, zoom, parameters) and not clear:
return True, self.__image, self.__zoom
# Restrict image surface size to prevent excessive use of memory
while True:
try:
self.__limiting_multiplicator = 1
area = width * zoom * self.__zoom_multiplicator * height * zoom * self.__zoom_multiplicator
if area > MAX_ALLOWED_AREA:
self.__limiting_multiplicator = sqrt(MAX_ALLOWED_AREA / area)
image = ImageSurface(self.__format, int(ceil(width * zoom * self.multiplicator)),
int(ceil(height * zoom * self.multiplicator)))
break # If we reach this point, the area was successfully allocated and we can break the loop
except Error:
MAX_ALLOWED_AREA *= 0.8
self.__set_cached_image(image, width, height, zoom, parameters)
return False, self.__image, zoom | python | def get_cached_image(self, width, height, zoom, parameters=None, clear=False):
"""Get ImageSurface object, if possible, cached
The method checks whether the image was already rendered. This is done by comparing the passed size and
parameters with those of the last image. If they are equal, the cached image is returned. Otherwise,
a new ImageSurface with the specified dimensions is created and returned.
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:param clear: If True, the cache is emptied, thus the image won't be retrieved from cache
:returns: The flag is True when the image is retrieved from the cache, otherwise False; The cached image
surface or a blank one with the desired size; The zoom parameter when the image was stored
:rtype: bool, ImageSurface, float
"""
global MAX_ALLOWED_AREA
if not parameters:
parameters = {}
if self.__compare_parameters(width, height, zoom, parameters) and not clear:
return True, self.__image, self.__zoom
# Restrict image surface size to prevent excessive use of memory
while True:
try:
self.__limiting_multiplicator = 1
area = width * zoom * self.__zoom_multiplicator * height * zoom * self.__zoom_multiplicator
if area > MAX_ALLOWED_AREA:
self.__limiting_multiplicator = sqrt(MAX_ALLOWED_AREA / area)
image = ImageSurface(self.__format, int(ceil(width * zoom * self.multiplicator)),
int(ceil(height * zoom * self.multiplicator)))
break # If we reach this point, the area was successfully allocated and we can break the loop
except Error:
MAX_ALLOWED_AREA *= 0.8
self.__set_cached_image(image, width, height, zoom, parameters)
return False, self.__image, zoom | [
"def",
"get_cached_image",
"(",
"self",
",",
"width",
",",
"height",
",",
"zoom",
",",
"parameters",
"=",
"None",
",",
"clear",
"=",
"False",
")",
":",
"global",
"MAX_ALLOWED_AREA",
"if",
"not",
"parameters",
":",
"parameters",
"=",
"{",
"}",
"if",
"self... | Get ImageSurface object, if possible, cached
The method checks whether the image was already rendered. This is done by comparing the passed size and
parameters with those of the last image. If they are equal, the cached image is returned. Otherwise,
a new ImageSurface with the specified dimensions is created and returned.
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:param clear: If True, the cache is emptied, thus the image won't be retrieved from cache
:returns: The flag is True when the image is retrieved from the cache, otherwise False; The cached image
surface or a blank one with the desired size; The zoom parameter when the image was stored
:rtype: bool, ImageSurface, float | [
"Get",
"ImageSurface",
"object",
"if",
"possible",
"cached"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/image_cache.py#L48-L85 | train | 40,155 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/utils/cache/image_cache.py | ImageCache.copy_image_to_context | def copy_image_to_context(self, context, position, rotation=0, zoom=None):
"""Draw a cached image on the context
:param context: The Cairo context to draw on
:param position: The position od the image
"""
if not zoom:
zoom = self.__zoom
zoom_multiplicator = zoom * self.multiplicator
context.save()
context.scale(1. / zoom_multiplicator, 1. / zoom_multiplicator)
image_position = round(position[0] * zoom_multiplicator), round(position[1] * zoom_multiplicator)
context.translate(*image_position)
context.rotate(rotation)
context.set_source_surface(self.__image, 0, 0)
context.paint()
context.restore() | python | def copy_image_to_context(self, context, position, rotation=0, zoom=None):
"""Draw a cached image on the context
:param context: The Cairo context to draw on
:param position: The position od the image
"""
if not zoom:
zoom = self.__zoom
zoom_multiplicator = zoom * self.multiplicator
context.save()
context.scale(1. / zoom_multiplicator, 1. / zoom_multiplicator)
image_position = round(position[0] * zoom_multiplicator), round(position[1] * zoom_multiplicator)
context.translate(*image_position)
context.rotate(rotation)
context.set_source_surface(self.__image, 0, 0)
context.paint()
context.restore() | [
"def",
"copy_image_to_context",
"(",
"self",
",",
"context",
",",
"position",
",",
"rotation",
"=",
"0",
",",
"zoom",
"=",
"None",
")",
":",
"if",
"not",
"zoom",
":",
"zoom",
"=",
"self",
".",
"__zoom",
"zoom_multiplicator",
"=",
"zoom",
"*",
"self",
"... | Draw a cached image on the context
:param context: The Cairo context to draw on
:param position: The position od the image | [
"Draw",
"a",
"cached",
"image",
"on",
"the",
"context"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/image_cache.py#L87-L105 | train | 40,156 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/utils/cache/image_cache.py | ImageCache.get_context_for_image | def get_context_for_image(self, zoom):
"""Creates a temporary cairo context for the image surface
:param zoom: The current scaling factor
:return: Cairo context to draw on
"""
cairo_context = Context(self.__image)
cairo_context.scale(zoom * self.multiplicator, zoom * self.multiplicator)
return cairo_context | python | def get_context_for_image(self, zoom):
"""Creates a temporary cairo context for the image surface
:param zoom: The current scaling factor
:return: Cairo context to draw on
"""
cairo_context = Context(self.__image)
cairo_context.scale(zoom * self.multiplicator, zoom * self.multiplicator)
return cairo_context | [
"def",
"get_context_for_image",
"(",
"self",
",",
"zoom",
")",
":",
"cairo_context",
"=",
"Context",
"(",
"self",
".",
"__image",
")",
"cairo_context",
".",
"scale",
"(",
"zoom",
"*",
"self",
".",
"multiplicator",
",",
"zoom",
"*",
"self",
".",
"multiplica... | Creates a temporary cairo context for the image surface
:param zoom: The current scaling factor
:return: Cairo context to draw on | [
"Creates",
"a",
"temporary",
"cairo",
"context",
"for",
"the",
"image",
"surface"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/image_cache.py#L111-L119 | train | 40,157 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/utils/cache/image_cache.py | ImageCache.__compare_parameters | def __compare_parameters(self, width, height, zoom, parameters):
"""Compare parameters for equality
Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
so, True is returned, else False,
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:return: True if all parameters are equal, False else
"""
# Deactivated caching
if not global_gui_config.get_config_value('ENABLE_CACHING', True):
return False
# Empty cache
if not self.__image:
return False
# Changed image size
if self.__width != width or self.__height != height:
return False
# Current zoom greater then prepared zoom
if zoom > self.__zoom * self.__zoom_multiplicator:
return False
# Current zoom much smaller than prepared zoom, causes high memory usage and imperfect anti-aliasing
if zoom < self.__zoom / self.__zoom_multiplicator:
return False
# Changed drawing parameter
for key in parameters:
try:
if key not in self.__last_parameters or self.__last_parameters[key] != parameters[key]:
return False
except (AttributeError, ValueError):
# Some values cannot be compared and raise an exception on comparison (e.g. numpy.ndarray). In this
# case, just return False and do not cache.
try:
# Catch at least the ndarray-case, as this could occure relatively often
import numpy
if isinstance(self.__last_parameters[key], numpy.ndarray):
return numpy.array_equal(self.__last_parameters[key], parameters[key])
except ImportError:
return False
return False
return True | python | def __compare_parameters(self, width, height, zoom, parameters):
"""Compare parameters for equality
Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
so, True is returned, else False,
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:return: True if all parameters are equal, False else
"""
# Deactivated caching
if not global_gui_config.get_config_value('ENABLE_CACHING', True):
return False
# Empty cache
if not self.__image:
return False
# Changed image size
if self.__width != width or self.__height != height:
return False
# Current zoom greater then prepared zoom
if zoom > self.__zoom * self.__zoom_multiplicator:
return False
# Current zoom much smaller than prepared zoom, causes high memory usage and imperfect anti-aliasing
if zoom < self.__zoom / self.__zoom_multiplicator:
return False
# Changed drawing parameter
for key in parameters:
try:
if key not in self.__last_parameters or self.__last_parameters[key] != parameters[key]:
return False
except (AttributeError, ValueError):
# Some values cannot be compared and raise an exception on comparison (e.g. numpy.ndarray). In this
# case, just return False and do not cache.
try:
# Catch at least the ndarray-case, as this could occure relatively often
import numpy
if isinstance(self.__last_parameters[key], numpy.ndarray):
return numpy.array_equal(self.__last_parameters[key], parameters[key])
except ImportError:
return False
return False
return True | [
"def",
"__compare_parameters",
"(",
"self",
",",
"width",
",",
"height",
",",
"zoom",
",",
"parameters",
")",
":",
"# Deactivated caching",
"if",
"not",
"global_gui_config",
".",
"get_config_value",
"(",
"'ENABLE_CACHING'",
",",
"True",
")",
":",
"return",
"Fals... | Compare parameters for equality
Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
so, True is returned, else False,
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale/zoom factor
:param parameters: The parameters used for the image
:return: True if all parameters are equal, False else | [
"Compare",
"parameters",
"for",
"equality"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/image_cache.py#L128-L177 | train | 40,158 |
DLR-RM/RAFCON | source/rafcon/core/start.py | post_setup_plugins | def post_setup_plugins(parser_result):
"""Calls the post init hubs
:param dict parser_result: Dictionary with the parsed arguments
"""
if not isinstance(parser_result, dict):
parser_result = vars(parser_result)
plugins.run_post_inits(parser_result) | python | def post_setup_plugins(parser_result):
"""Calls the post init hubs
:param dict parser_result: Dictionary with the parsed arguments
"""
if not isinstance(parser_result, dict):
parser_result = vars(parser_result)
plugins.run_post_inits(parser_result) | [
"def",
"post_setup_plugins",
"(",
"parser_result",
")",
":",
"if",
"not",
"isinstance",
"(",
"parser_result",
",",
"dict",
")",
":",
"parser_result",
"=",
"vars",
"(",
"parser_result",
")",
"plugins",
".",
"run_post_inits",
"(",
"parser_result",
")"
] | Calls the post init hubs
:param dict parser_result: Dictionary with the parsed arguments | [
"Calls",
"the",
"post",
"init",
"hubs"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L59-L66 | train | 40,159 |
DLR-RM/RAFCON | source/rafcon/core/start.py | setup_environment | def setup_environment():
"""Ensures that the environmental variable RAFCON_LIB_PATH is existent
"""
try:
from gi.repository import GLib
user_data_folder = GLib.get_user_data_dir()
except ImportError:
user_data_folder = join(os.path.expanduser("~"), ".local", "share")
rafcon_root_path = dirname(realpath(rafcon.__file__))
user_library_folder = join(user_data_folder, "rafcon", "libraries")
# The RAFCON_LIB_PATH points to a path with common RAFCON libraries
# If the env variable is not set, we have to determine it. In the future, this should always be
# ~/.local/share/rafcon/libraries, but for backward compatibility, also a relative RAFCON path is supported
if not os.environ.get('RAFCON_LIB_PATH', None):
if exists(user_library_folder):
os.environ['RAFCON_LIB_PATH'] = user_library_folder
else:
os.environ['RAFCON_LIB_PATH'] = join(dirname(dirname(rafcon_root_path)), 'share', 'libraries')
# Install dummy _ builtin function in case i18.setup_l10n() is not called
if sys.version_info >= (3,):
import builtins as builtins23
else:
import __builtin__ as builtins23
if "_" not in builtins23.__dict__:
builtins23.__dict__["_"] = lambda s: s | python | def setup_environment():
"""Ensures that the environmental variable RAFCON_LIB_PATH is existent
"""
try:
from gi.repository import GLib
user_data_folder = GLib.get_user_data_dir()
except ImportError:
user_data_folder = join(os.path.expanduser("~"), ".local", "share")
rafcon_root_path = dirname(realpath(rafcon.__file__))
user_library_folder = join(user_data_folder, "rafcon", "libraries")
# The RAFCON_LIB_PATH points to a path with common RAFCON libraries
# If the env variable is not set, we have to determine it. In the future, this should always be
# ~/.local/share/rafcon/libraries, but for backward compatibility, also a relative RAFCON path is supported
if not os.environ.get('RAFCON_LIB_PATH', None):
if exists(user_library_folder):
os.environ['RAFCON_LIB_PATH'] = user_library_folder
else:
os.environ['RAFCON_LIB_PATH'] = join(dirname(dirname(rafcon_root_path)), 'share', 'libraries')
# Install dummy _ builtin function in case i18.setup_l10n() is not called
if sys.version_info >= (3,):
import builtins as builtins23
else:
import __builtin__ as builtins23
if "_" not in builtins23.__dict__:
builtins23.__dict__["_"] = lambda s: s | [
"def",
"setup_environment",
"(",
")",
":",
"try",
":",
"from",
"gi",
".",
"repository",
"import",
"GLib",
"user_data_folder",
"=",
"GLib",
".",
"get_user_data_dir",
"(",
")",
"except",
"ImportError",
":",
"user_data_folder",
"=",
"join",
"(",
"os",
".",
"pat... | Ensures that the environmental variable RAFCON_LIB_PATH is existent | [
"Ensures",
"that",
"the",
"environmental",
"variable",
"RAFCON_LIB_PATH",
"is",
"existent"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L69-L95 | train | 40,160 |
DLR-RM/RAFCON | source/rafcon/core/start.py | parse_state_machine_path | def parse_state_machine_path(path):
"""Parser for argparse checking pfor a proper state machine path
:param str path: Input path from the user
:return: The path
:raises argparse.ArgumentTypeError: if the path does not contain a statemachine.json file
"""
sm_root_file = join(path, storage.STATEMACHINE_FILE)
if exists(sm_root_file):
return path
else:
sm_root_file = join(path, storage.STATEMACHINE_FILE_OLD)
if exists(sm_root_file):
return path
raise argparse.ArgumentTypeError("Failed to open {0}: {1} not found in path".format(path,
storage.STATEMACHINE_FILE)) | python | def parse_state_machine_path(path):
"""Parser for argparse checking pfor a proper state machine path
:param str path: Input path from the user
:return: The path
:raises argparse.ArgumentTypeError: if the path does not contain a statemachine.json file
"""
sm_root_file = join(path, storage.STATEMACHINE_FILE)
if exists(sm_root_file):
return path
else:
sm_root_file = join(path, storage.STATEMACHINE_FILE_OLD)
if exists(sm_root_file):
return path
raise argparse.ArgumentTypeError("Failed to open {0}: {1} not found in path".format(path,
storage.STATEMACHINE_FILE)) | [
"def",
"parse_state_machine_path",
"(",
"path",
")",
":",
"sm_root_file",
"=",
"join",
"(",
"path",
",",
"storage",
".",
"STATEMACHINE_FILE",
")",
"if",
"exists",
"(",
"sm_root_file",
")",
":",
"return",
"path",
"else",
":",
"sm_root_file",
"=",
"join",
"(",... | Parser for argparse checking pfor a proper state machine path
:param str path: Input path from the user
:return: The path
:raises argparse.ArgumentTypeError: if the path does not contain a statemachine.json file | [
"Parser",
"for",
"argparse",
"checking",
"pfor",
"a",
"proper",
"state",
"machine",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L98-L113 | train | 40,161 |
DLR-RM/RAFCON | source/rafcon/core/start.py | setup_configuration | def setup_configuration(config_path):
"""Loads the core configuration from the specified path and uses its content for further setup
:param config_path: Path to the core config file
"""
if config_path is not None:
config_path, config_file = filesystem.separate_folder_path_and_file_name(config_path)
global_config.load(config_file=config_file, path=config_path)
else:
global_config.load(path=config_path)
# Initialize libraries
core_singletons.library_manager.initialize() | python | def setup_configuration(config_path):
"""Loads the core configuration from the specified path and uses its content for further setup
:param config_path: Path to the core config file
"""
if config_path is not None:
config_path, config_file = filesystem.separate_folder_path_and_file_name(config_path)
global_config.load(config_file=config_file, path=config_path)
else:
global_config.load(path=config_path)
# Initialize libraries
core_singletons.library_manager.initialize() | [
"def",
"setup_configuration",
"(",
"config_path",
")",
":",
"if",
"config_path",
"is",
"not",
"None",
":",
"config_path",
",",
"config_file",
"=",
"filesystem",
".",
"separate_folder_path_and_file_name",
"(",
"config_path",
")",
"global_config",
".",
"load",
"(",
... | Loads the core configuration from the specified path and uses its content for further setup
:param config_path: Path to the core config file | [
"Loads",
"the",
"core",
"configuration",
"from",
"the",
"specified",
"path",
"and",
"uses",
"its",
"content",
"for",
"further",
"setup"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L140-L152 | train | 40,162 |
DLR-RM/RAFCON | source/rafcon/core/start.py | open_state_machine | def open_state_machine(state_machine_path):
"""Executes the specified state machine
:param str state_machine_path: The file path to the state machine
:return StateMachine: The loaded state machine
"""
sm = storage.load_state_machine_from_path(state_machine_path)
core_singletons.state_machine_manager.add_state_machine(sm)
return sm | python | def open_state_machine(state_machine_path):
"""Executes the specified state machine
:param str state_machine_path: The file path to the state machine
:return StateMachine: The loaded state machine
"""
sm = storage.load_state_machine_from_path(state_machine_path)
core_singletons.state_machine_manager.add_state_machine(sm)
return sm | [
"def",
"open_state_machine",
"(",
"state_machine_path",
")",
":",
"sm",
"=",
"storage",
".",
"load_state_machine_from_path",
"(",
"state_machine_path",
")",
"core_singletons",
".",
"state_machine_manager",
".",
"add_state_machine",
"(",
"sm",
")",
"return",
"sm"
] | Executes the specified state machine
:param str state_machine_path: The file path to the state machine
:return StateMachine: The loaded state machine | [
"Executes",
"the",
"specified",
"state",
"machine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L155-L164 | train | 40,163 |
DLR-RM/RAFCON | source/rafcon/core/start.py | wait_for_state_machine_finished | def wait_for_state_machine_finished(state_machine):
""" wait for a state machine to finish its execution
:param state_machine: the statemachine to synchronize with
:return:
"""
global _user_abort
from rafcon.core.states.execution_state import ExecutionState
if not isinstance(state_machine.root_state, ExecutionState):
while len(state_machine.execution_histories[0]) < 1:
time.sleep(0.1)
else:
time.sleep(0.5)
while state_machine.root_state.state_execution_status is not StateExecutionStatus.INACTIVE:
try:
state_machine.root_state.concurrency_queue.get(timeout=1)
# this check triggers if the state machine could not be stopped in the signal handler
if _user_abort:
return
except Empty:
pass
# no logger output here to make it easier for the parser
logger.verbose("RAFCON live signal") | python | def wait_for_state_machine_finished(state_machine):
""" wait for a state machine to finish its execution
:param state_machine: the statemachine to synchronize with
:return:
"""
global _user_abort
from rafcon.core.states.execution_state import ExecutionState
if not isinstance(state_machine.root_state, ExecutionState):
while len(state_machine.execution_histories[0]) < 1:
time.sleep(0.1)
else:
time.sleep(0.5)
while state_machine.root_state.state_execution_status is not StateExecutionStatus.INACTIVE:
try:
state_machine.root_state.concurrency_queue.get(timeout=1)
# this check triggers if the state machine could not be stopped in the signal handler
if _user_abort:
return
except Empty:
pass
# no logger output here to make it easier for the parser
logger.verbose("RAFCON live signal") | [
"def",
"wait_for_state_machine_finished",
"(",
"state_machine",
")",
":",
"global",
"_user_abort",
"from",
"rafcon",
".",
"core",
".",
"states",
".",
"execution_state",
"import",
"ExecutionState",
"if",
"not",
"isinstance",
"(",
"state_machine",
".",
"root_state",
"... | wait for a state machine to finish its execution
:param state_machine: the statemachine to synchronize with
:return: | [
"wait",
"for",
"a",
"state",
"machine",
"to",
"finish",
"its",
"execution"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L175-L199 | train | 40,164 |
DLR-RM/RAFCON | source/rafcon/core/start.py | stop_reactor_on_state_machine_finish | def stop_reactor_on_state_machine_finish(state_machine):
""" Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with
"""
wait_for_state_machine_finished(state_machine)
from twisted.internet import reactor
if reactor.running:
plugins.run_hook("pre_destruction")
reactor.callFromThread(reactor.stop) | python | def stop_reactor_on_state_machine_finish(state_machine):
""" Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with
"""
wait_for_state_machine_finished(state_machine)
from twisted.internet import reactor
if reactor.running:
plugins.run_hook("pre_destruction")
reactor.callFromThread(reactor.stop) | [
"def",
"stop_reactor_on_state_machine_finish",
"(",
"state_machine",
")",
":",
"wait_for_state_machine_finished",
"(",
"state_machine",
")",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"if",
"reactor",
".",
"running",
":",
"plugins",
".",
"run_hook",
"(",... | Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with | [
"Wait",
"for",
"a",
"state",
"machine",
"to",
"be",
"finished",
"and",
"stops",
"the",
"reactor"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/start.py#L202-L211 | train | 40,165 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.wait_until_ready | async def wait_until_ready(
self, timeout: Optional[float] = None, no_raise: bool = False
) -> bool:
"""
Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wait indefinitely.
"""
if self.node.ready.is_set():
return True
try:
return await self.node.wait_until_ready(timeout=timeout)
except asyncio.TimeoutError:
if no_raise:
return False
else:
raise | python | async def wait_until_ready(
self, timeout: Optional[float] = None, no_raise: bool = False
) -> bool:
"""
Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wait indefinitely.
"""
if self.node.ready.is_set():
return True
try:
return await self.node.wait_until_ready(timeout=timeout)
except asyncio.TimeoutError:
if no_raise:
return False
else:
raise | [
"async",
"def",
"wait_until_ready",
"(",
"self",
",",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"no_raise",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"if",
"self",
".",
"node",
".",
"ready",
".",
"is_set",
"(",
")",
... | Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wait indefinitely. | [
"Waits",
"for",
"the",
"underlying",
"node",
"to",
"become",
"ready",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L94-L112 | train | 40,166 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.connect | async def connect(self):
"""
Connects to the voice channel associated with this Player.
"""
await self.node.join_voice_channel(self.channel.guild.id, self.channel.id) | python | async def connect(self):
"""
Connects to the voice channel associated with this Player.
"""
await self.node.join_voice_channel(self.channel.guild.id, self.channel.id) | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"await",
"self",
".",
"node",
".",
"join_voice_channel",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
",",
"self",
".",
"channel",
".",
"id",
")"
] | Connects to the voice channel associated with this Player. | [
"Connects",
"to",
"the",
"voice",
"channel",
"associated",
"with",
"this",
"Player",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L114-L118 | train | 40,167 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.move_to | async def move_to(self, channel: discord.VoiceChannel):
"""
Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel
"""
if channel.guild != self.channel.guild:
raise TypeError("Cannot move to a different guild.")
self.channel = channel
await self.connect() | python | async def move_to(self, channel: discord.VoiceChannel):
"""
Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel
"""
if channel.guild != self.channel.guild:
raise TypeError("Cannot move to a different guild.")
self.channel = channel
await self.connect() | [
"async",
"def",
"move_to",
"(",
"self",
",",
"channel",
":",
"discord",
".",
"VoiceChannel",
")",
":",
"if",
"channel",
".",
"guild",
"!=",
"self",
".",
"channel",
".",
"guild",
":",
"raise",
"TypeError",
"(",
"\"Cannot move to a different guild.\"",
")",
"s... | Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel | [
"Moves",
"this",
"player",
"to",
"a",
"voice",
"channel",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L120-L132 | train | 40,168 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.disconnect | async def disconnect(self, requested=True):
"""
Disconnects this player from it's voice channel.
"""
if self.state == PlayerState.DISCONNECTING:
return
await self.update_state(PlayerState.DISCONNECTING)
if not requested:
log.debug(
f"Forcing player disconnect for guild {self.channel.guild.id}"
f" due to player manager request."
)
guild_id = self.channel.guild.id
voice_ws = self.node.get_voice_ws(guild_id)
if not voice_ws.closed:
await voice_ws.voice_state(guild_id, None)
await self.node.destroy_guild(guild_id)
await self.close()
self.manager.remove_player(self) | python | async def disconnect(self, requested=True):
"""
Disconnects this player from it's voice channel.
"""
if self.state == PlayerState.DISCONNECTING:
return
await self.update_state(PlayerState.DISCONNECTING)
if not requested:
log.debug(
f"Forcing player disconnect for guild {self.channel.guild.id}"
f" due to player manager request."
)
guild_id = self.channel.guild.id
voice_ws = self.node.get_voice_ws(guild_id)
if not voice_ws.closed:
await voice_ws.voice_state(guild_id, None)
await self.node.destroy_guild(guild_id)
await self.close()
self.manager.remove_player(self) | [
"async",
"def",
"disconnect",
"(",
"self",
",",
"requested",
"=",
"True",
")",
":",
"if",
"self",
".",
"state",
"==",
"PlayerState",
".",
"DISCONNECTING",
":",
"return",
"await",
"self",
".",
"update_state",
"(",
"PlayerState",
".",
"DISCONNECTING",
")",
"... | Disconnects this player from it's voice channel. | [
"Disconnects",
"this",
"player",
"from",
"it",
"s",
"voice",
"channel",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L134-L157 | train | 40,169 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.handle_event | async def handle_event(self, event: "node.LavalinkEvents", extra):
"""
Handles various Lavalink Events.
If the event is TRACK END, extra will be TrackEndReason.
If the event is TRACK EXCEPTION, extra will be the string reason.
If the event is TRACK STUCK, extra will be the threshold ms.
Parameters
----------
event : node.LavalinkEvents
extra
"""
if event == LavalinkEvents.TRACK_END:
if extra == TrackEndReason.FINISHED:
await self.play()
else:
self._is_playing = False | python | async def handle_event(self, event: "node.LavalinkEvents", extra):
"""
Handles various Lavalink Events.
If the event is TRACK END, extra will be TrackEndReason.
If the event is TRACK EXCEPTION, extra will be the string reason.
If the event is TRACK STUCK, extra will be the threshold ms.
Parameters
----------
event : node.LavalinkEvents
extra
"""
if event == LavalinkEvents.TRACK_END:
if extra == TrackEndReason.FINISHED:
await self.play()
else:
self._is_playing = False | [
"async",
"def",
"handle_event",
"(",
"self",
",",
"event",
":",
"\"node.LavalinkEvents\"",
",",
"extra",
")",
":",
"if",
"event",
"==",
"LavalinkEvents",
".",
"TRACK_END",
":",
"if",
"extra",
"==",
"TrackEndReason",
".",
"FINISHED",
":",
"await",
"self",
"."... | Handles various Lavalink Events.
If the event is TRACK END, extra will be TrackEndReason.
If the event is TRACK EXCEPTION, extra will be the string reason.
If the event is TRACK STUCK, extra will be the threshold ms.
Parameters
----------
event : node.LavalinkEvents
extra | [
"Handles",
"various",
"Lavalink",
"Events",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L193-L212 | train | 40,170 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.handle_player_update | async def handle_player_update(self, state: "node.PlayerState"):
"""
Handles player updates from lavalink.
Parameters
----------
state : websocket.PlayerState
"""
if state.position > self.position:
self._is_playing = True
self.position = state.position | python | async def handle_player_update(self, state: "node.PlayerState"):
"""
Handles player updates from lavalink.
Parameters
----------
state : websocket.PlayerState
"""
if state.position > self.position:
self._is_playing = True
self.position = state.position | [
"async",
"def",
"handle_player_update",
"(",
"self",
",",
"state",
":",
"\"node.PlayerState\"",
")",
":",
"if",
"state",
".",
"position",
">",
"self",
".",
"position",
":",
"self",
".",
"_is_playing",
"=",
"True",
"self",
".",
"position",
"=",
"state",
"."... | Handles player updates from lavalink.
Parameters
----------
state : websocket.PlayerState | [
"Handles",
"player",
"updates",
"from",
"lavalink",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L214-L224 | train | 40,171 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.add | def add(self, requester: discord.User, track: Track):
"""
Adds a track to the queue.
Parameters
----------
requester : discord.User
User who requested the track.
track : Track
Result from any of the lavalink track search methods.
"""
track.requester = requester
self.queue.append(track) | python | def add(self, requester: discord.User, track: Track):
"""
Adds a track to the queue.
Parameters
----------
requester : discord.User
User who requested the track.
track : Track
Result from any of the lavalink track search methods.
"""
track.requester = requester
self.queue.append(track) | [
"def",
"add",
"(",
"self",
",",
"requester",
":",
"discord",
".",
"User",
",",
"track",
":",
"Track",
")",
":",
"track",
".",
"requester",
"=",
"requester",
"self",
".",
"queue",
".",
"append",
"(",
"track",
")"
] | Adds a track to the queue.
Parameters
----------
requester : discord.User
User who requested the track.
track : Track
Result from any of the lavalink track search methods. | [
"Adds",
"a",
"track",
"to",
"the",
"queue",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L227-L239 | train | 40,172 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.play | async def play(self):
"""
Starts playback from lavalink.
"""
if self.repeat and self.current is not None:
self.queue.append(self.current)
self.current = None
self.position = 0
self._paused = False
if not self.queue:
await self.stop()
else:
self._is_playing = True
if self.shuffle:
track = self.queue.pop(randrange(len(self.queue)))
else:
track = self.queue.pop(0)
self.current = track
log.debug("Assigned current.")
await self.node.play(self.channel.guild.id, track) | python | async def play(self):
"""
Starts playback from lavalink.
"""
if self.repeat and self.current is not None:
self.queue.append(self.current)
self.current = None
self.position = 0
self._paused = False
if not self.queue:
await self.stop()
else:
self._is_playing = True
if self.shuffle:
track = self.queue.pop(randrange(len(self.queue)))
else:
track = self.queue.pop(0)
self.current = track
log.debug("Assigned current.")
await self.node.play(self.channel.guild.id, track) | [
"async",
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"repeat",
"and",
"self",
".",
"current",
"is",
"not",
"None",
":",
"self",
".",
"queue",
".",
"append",
"(",
"self",
".",
"current",
")",
"self",
".",
"current",
"=",
"None",
"self",... | Starts playback from lavalink. | [
"Starts",
"playback",
"from",
"lavalink",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L241-L263 | train | 40,173 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.stop | async def stop(self):
"""
Stops playback from lavalink.
.. important::
This method will clear the queue.
"""
await self.node.stop(self.channel.guild.id)
self.queue = []
self.current = None
self.position = 0
self._paused = False | python | async def stop(self):
"""
Stops playback from lavalink.
.. important::
This method will clear the queue.
"""
await self.node.stop(self.channel.guild.id)
self.queue = []
self.current = None
self.position = 0
self._paused = False | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"node",
".",
"stop",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
")",
"self",
".",
"queue",
"=",
"[",
"]",
"self",
".",
"current",
"=",
"None",
"self",
".",
"position"... | Stops playback from lavalink.
.. important::
This method will clear the queue. | [
"Stops",
"playback",
"from",
"lavalink",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L265-L277 | train | 40,174 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.pause | async def pause(self, pause: bool = True):
"""
Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume.
"""
self._paused = pause
await self.node.pause(self.channel.guild.id, pause) | python | async def pause(self, pause: bool = True):
"""
Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume.
"""
self._paused = pause
await self.node.pause(self.channel.guild.id, pause) | [
"async",
"def",
"pause",
"(",
"self",
",",
"pause",
":",
"bool",
"=",
"True",
")",
":",
"self",
".",
"_paused",
"=",
"pause",
"await",
"self",
".",
"node",
".",
"pause",
"(",
"self",
".",
"channel",
".",
"guild",
".",
"id",
",",
"pause",
")"
] | Pauses the current song.
Parameters
----------
pause : bool
Set to ``False`` to resume. | [
"Pauses",
"the",
"current",
"song",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L285-L295 | train | 40,175 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.set_volume | async def set_volume(self, volume: int):
"""
Sets the volume of Lavalink.
Parameters
----------
volume : int
Between 0 and 150
"""
self._volume = max(min(volume, 150), 0)
await self.node.volume(self.channel.guild.id, self.volume) | python | async def set_volume(self, volume: int):
"""
Sets the volume of Lavalink.
Parameters
----------
volume : int
Between 0 and 150
"""
self._volume = max(min(volume, 150), 0)
await self.node.volume(self.channel.guild.id, self.volume) | [
"async",
"def",
"set_volume",
"(",
"self",
",",
"volume",
":",
"int",
")",
":",
"self",
".",
"_volume",
"=",
"max",
"(",
"min",
"(",
"volume",
",",
"150",
")",
",",
"0",
")",
"await",
"self",
".",
"node",
".",
"volume",
"(",
"self",
".",
"channel... | Sets the volume of Lavalink.
Parameters
----------
volume : int
Between 0 and 150 | [
"Sets",
"the",
"volume",
"of",
"Lavalink",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L297-L307 | train | 40,176 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | Player.seek | async def seek(self, position: int):
"""
If the track allows it, seeks to a position.
Parameters
----------
position : int
Between 0 and track length.
"""
if self.current.seekable:
position = max(min(position, self.current.length), 0)
await self.node.seek(self.channel.guild.id, position) | python | async def seek(self, position: int):
"""
If the track allows it, seeks to a position.
Parameters
----------
position : int
Between 0 and track length.
"""
if self.current.seekable:
position = max(min(position, self.current.length), 0)
await self.node.seek(self.channel.guild.id, position) | [
"async",
"def",
"seek",
"(",
"self",
",",
"position",
":",
"int",
")",
":",
"if",
"self",
".",
"current",
".",
"seekable",
":",
"position",
"=",
"max",
"(",
"min",
"(",
"position",
",",
"self",
".",
"current",
".",
"length",
")",
",",
"0",
")",
"... | If the track allows it, seeks to a position.
Parameters
----------
position : int
Between 0 and track length. | [
"If",
"the",
"track",
"allows",
"it",
"seeks",
"to",
"a",
"position",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L309-L320 | train | 40,177 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | PlayerManager.get_player | def get_player(self, guild_id: int) -> Player:
"""
Gets a Player object from a guild ID.
Parameters
----------
guild_id : int
Discord guild ID.
Returns
-------
Player
Raises
------
KeyError
If that guild does not have a Player, e.g. is not connected to any
voice channel.
"""
if guild_id in self._player_dict:
return self._player_dict[guild_id]
raise KeyError("No such player for that guild.") | python | def get_player(self, guild_id: int) -> Player:
"""
Gets a Player object from a guild ID.
Parameters
----------
guild_id : int
Discord guild ID.
Returns
-------
Player
Raises
------
KeyError
If that guild does not have a Player, e.g. is not connected to any
voice channel.
"""
if guild_id in self._player_dict:
return self._player_dict[guild_id]
raise KeyError("No such player for that guild.") | [
"def",
"get_player",
"(",
"self",
",",
"guild_id",
":",
"int",
")",
"->",
"Player",
":",
"if",
"guild_id",
"in",
"self",
".",
"_player_dict",
":",
"return",
"self",
".",
"_player_dict",
"[",
"guild_id",
"]",
"raise",
"KeyError",
"(",
"\"No such player for th... | Gets a Player object from a guild ID.
Parameters
----------
guild_id : int
Discord guild ID.
Returns
-------
Player
Raises
------
KeyError
If that guild does not have a Player, e.g. is not connected to any
voice channel. | [
"Gets",
"a",
"Player",
"object",
"from",
"a",
"guild",
"ID",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L368-L389 | train | 40,178 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | PlayerManager.disconnect | async def disconnect(self):
"""
Disconnects all players.
"""
for p in tuple(self.players):
await p.disconnect(requested=False)
log.debug("Disconnected players.") | python | async def disconnect(self):
"""
Disconnects all players.
"""
for p in tuple(self.players):
await p.disconnect(requested=False)
log.debug("Disconnected players.") | [
"async",
"def",
"disconnect",
"(",
"self",
")",
":",
"for",
"p",
"in",
"tuple",
"(",
"self",
".",
"players",
")",
":",
"await",
"p",
".",
"disconnect",
"(",
"requested",
"=",
"False",
")",
"log",
".",
"debug",
"(",
"\"Disconnected players.\"",
")"
] | Disconnects all players. | [
"Disconnects",
"all",
"players",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L475-L481 | train | 40,179 |
DLR-RM/RAFCON | source/rafcon/utils/resources.py | resource_filename | def resource_filename(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the path to the resource
:rtype: str
"""
if pkg_resources.resource_exists(package_or_requirement, resource_name):
return pkg_resources.resource_filename(package_or_requirement, resource_name)
path = _search_in_share_folders(package_or_requirement, resource_name)
if path:
return path
raise RuntimeError("Resource {} not found in {}".format(package_or_requirement, resource_name)) | python | def resource_filename(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the path to the resource
:rtype: str
"""
if pkg_resources.resource_exists(package_or_requirement, resource_name):
return pkg_resources.resource_filename(package_or_requirement, resource_name)
path = _search_in_share_folders(package_or_requirement, resource_name)
if path:
return path
raise RuntimeError("Resource {} not found in {}".format(package_or_requirement, resource_name)) | [
"def",
"resource_filename",
"(",
"package_or_requirement",
",",
"resource_name",
")",
":",
"if",
"pkg_resources",
".",
"resource_exists",
"(",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"pkg_resources",
".",
"resource_filename",
"(",
"package_or... | Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the path to the resource
:rtype: str | [
"Similar",
"to",
"pkg_resources",
".",
"resource_filename",
"but",
"if",
"the",
"resource",
"it",
"not",
"found",
"via",
"pkg_resources",
"it",
"also",
"looks",
"in",
"a",
"predefined",
"list",
"of",
"paths",
"in",
"order",
"to",
"find",
"the",
"resource"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/resources.py#L39-L57 | train | 40,180 |
DLR-RM/RAFCON | source/rafcon/utils/resources.py | resource_exists | def resource_exists(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_exists but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: a flag if the file exists
:rtype: bool
"""
if pkg_resources.resource_exists(package_or_requirement, resource_name):
return True
path = _search_in_share_folders(package_or_requirement, resource_name)
return True if path else False | python | def resource_exists(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_exists but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: a flag if the file exists
:rtype: bool
"""
if pkg_resources.resource_exists(package_or_requirement, resource_name):
return True
path = _search_in_share_folders(package_or_requirement, resource_name)
return True if path else False | [
"def",
"resource_exists",
"(",
"package_or_requirement",
",",
"resource_name",
")",
":",
"if",
"pkg_resources",
".",
"resource_exists",
"(",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"True",
"path",
"=",
"_search_in_share_folders",
"(",
"pack... | Similar to pkg_resources.resource_exists but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: a flag if the file exists
:rtype: bool | [
"Similar",
"to",
"pkg_resources",
".",
"resource_exists",
"but",
"if",
"the",
"resource",
"it",
"not",
"found",
"via",
"pkg_resources",
"it",
"also",
"looks",
"in",
"a",
"predefined",
"list",
"of",
"paths",
"in",
"order",
"to",
"find",
"the",
"resource"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/resources.py#L60-L75 | train | 40,181 |
DLR-RM/RAFCON | source/rafcon/utils/resources.py | resource_string | def resource_string(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_string but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the file content
:rtype: str
"""
with open(resource_filename(package_or_requirement, resource_name), 'r') as resource_file:
return resource_file.read() | python | def resource_string(package_or_requirement, resource_name):
"""
Similar to pkg_resources.resource_string but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the file content
:rtype: str
"""
with open(resource_filename(package_or_requirement, resource_name), 'r') as resource_file:
return resource_file.read() | [
"def",
"resource_string",
"(",
"package_or_requirement",
",",
"resource_name",
")",
":",
"with",
"open",
"(",
"resource_filename",
"(",
"package_or_requirement",
",",
"resource_name",
")",
",",
"'r'",
")",
"as",
"resource_file",
":",
"return",
"resource_file",
".",
... | Similar to pkg_resources.resource_string but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param resource_name: the name of the resource
:return: the file content
:rtype: str | [
"Similar",
"to",
"pkg_resources",
".",
"resource_string",
"but",
"if",
"the",
"resource",
"it",
"not",
"found",
"via",
"pkg_resources",
"it",
"also",
"looks",
"in",
"a",
"predefined",
"list",
"of",
"paths",
"in",
"order",
"to",
"find",
"the",
"resource"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/resources.py#L78-L89 | train | 40,182 |
DLR-RM/RAFCON | source/rafcon/utils/resources.py | resource_listdir | def resource_listdir(package_or_requirement, relative_path):
"""
Similar to pkg_resources.resource_listdir but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param relative_path: the relative path to the resource
:return: a list of all files residing in the target path
:rtype: list
"""
path = resource_filename(package_or_requirement, relative_path)
only_files = [f for f in listdir(path) if isfile(join(path, f))]
return only_files | python | def resource_listdir(package_or_requirement, relative_path):
"""
Similar to pkg_resources.resource_listdir but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param relative_path: the relative path to the resource
:return: a list of all files residing in the target path
:rtype: list
"""
path = resource_filename(package_or_requirement, relative_path)
only_files = [f for f in listdir(path) if isfile(join(path, f))]
return only_files | [
"def",
"resource_listdir",
"(",
"package_or_requirement",
",",
"relative_path",
")",
":",
"path",
"=",
"resource_filename",
"(",
"package_or_requirement",
",",
"relative_path",
")",
"only_files",
"=",
"[",
"f",
"for",
"f",
"in",
"listdir",
"(",
"path",
")",
"if"... | Similar to pkg_resources.resource_listdir but if the resource it not found via pkg_resources
it also looks in a predefined list of paths in order to find the resource
:param package_or_requirement: the module in which the resource resides
:param relative_path: the relative path to the resource
:return: a list of all files residing in the target path
:rtype: list | [
"Similar",
"to",
"pkg_resources",
".",
"resource_listdir",
"but",
"if",
"the",
"resource",
"it",
"not",
"found",
"via",
"pkg_resources",
"it",
"also",
"looks",
"in",
"a",
"predefined",
"list",
"of",
"paths",
"in",
"order",
"to",
"find",
"the",
"resource"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/resources.py#L92-L104 | train | 40,183 |
DLR-RM/RAFCON | source/rafcon/utils/plugins.py | load_plugins | def load_plugins():
"""Loads all plugins specified in the RAFCON_PLUGIN_PATH environment variable
"""
plugins = os.environ.get('RAFCON_PLUGIN_PATH', '')
plugin_list = set(plugins.split(os.pathsep))
global plugin_dict
for plugin_path in plugin_list:
if not plugin_path:
continue
plugin_path = os.path.expandvars(os.path.expanduser(plugin_path)).strip()
if not os.path.exists(plugin_path):
logger.error("The specified plugin path does not exist: {}".format(plugin_path))
continue
dir_name, plugin_name = os.path.split(plugin_path.rstrip('/'))
logger.info("Found plugin '{}' at {}".format(plugin_name, plugin_path))
sys.path.insert(0, dir_name)
if plugin_name in plugin_dict:
logger.error("Plugin '{}' already loaded".format(plugin_name))
else:
try:
module = importlib.import_module(plugin_name)
plugin_dict[plugin_name] = module
logger.info("Successfully loaded plugin '{}'".format(plugin_name))
except ImportError as e:
logger.error("Could not import plugin '{}': {}\n{}".format(plugin_name, e, str(traceback.format_exc()))) | python | def load_plugins():
"""Loads all plugins specified in the RAFCON_PLUGIN_PATH environment variable
"""
plugins = os.environ.get('RAFCON_PLUGIN_PATH', '')
plugin_list = set(plugins.split(os.pathsep))
global plugin_dict
for plugin_path in plugin_list:
if not plugin_path:
continue
plugin_path = os.path.expandvars(os.path.expanduser(plugin_path)).strip()
if not os.path.exists(plugin_path):
logger.error("The specified plugin path does not exist: {}".format(plugin_path))
continue
dir_name, plugin_name = os.path.split(plugin_path.rstrip('/'))
logger.info("Found plugin '{}' at {}".format(plugin_name, plugin_path))
sys.path.insert(0, dir_name)
if plugin_name in plugin_dict:
logger.error("Plugin '{}' already loaded".format(plugin_name))
else:
try:
module = importlib.import_module(plugin_name)
plugin_dict[plugin_name] = module
logger.info("Successfully loaded plugin '{}'".format(plugin_name))
except ImportError as e:
logger.error("Could not import plugin '{}': {}\n{}".format(plugin_name, e, str(traceback.format_exc()))) | [
"def",
"load_plugins",
"(",
")",
":",
"plugins",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'RAFCON_PLUGIN_PATH'",
",",
"''",
")",
"plugin_list",
"=",
"set",
"(",
"plugins",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
")",
"global",
"plugin_dict",
... | Loads all plugins specified in the RAFCON_PLUGIN_PATH environment variable | [
"Loads",
"all",
"plugins",
"specified",
"in",
"the",
"RAFCON_PLUGIN_PATH",
"environment",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/plugins.py#L34-L58 | train | 40,184 |
DLR-RM/RAFCON | source/rafcon/utils/plugins.py | run_hook | def run_hook(hook_name, *args, **kwargs):
"""Runs the passed hook on all registered plugins
The function checks, whether the hook is available in the plugin.
:param hook_name: Name of the hook, corresponds to the function name being called
:param args: Arguments
:param kwargs: Keyword arguments
"""
for module in plugin_dict.values():
if hasattr(module, "hooks") and callable(getattr(module.hooks, hook_name, None)):
getattr(module.hooks, hook_name)(*args, **kwargs) | python | def run_hook(hook_name, *args, **kwargs):
"""Runs the passed hook on all registered plugins
The function checks, whether the hook is available in the plugin.
:param hook_name: Name of the hook, corresponds to the function name being called
:param args: Arguments
:param kwargs: Keyword arguments
"""
for module in plugin_dict.values():
if hasattr(module, "hooks") and callable(getattr(module.hooks, hook_name, None)):
getattr(module.hooks, hook_name)(*args, **kwargs) | [
"def",
"run_hook",
"(",
"hook_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"module",
"in",
"plugin_dict",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"module",
",",
"\"hooks\"",
")",
"and",
"callable",
"(",
"getattr",
"(... | Runs the passed hook on all registered plugins
The function checks, whether the hook is available in the plugin.
:param hook_name: Name of the hook, corresponds to the function name being called
:param args: Arguments
:param kwargs: Keyword arguments | [
"Runs",
"the",
"passed",
"hook",
"on",
"all",
"registered",
"plugins"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/plugins.py#L61-L72 | train | 40,185 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | get_state_model_class_for_state | def get_state_model_class_for_state(state):
"""Determines the model required for the given state class
:param state: Instance of a state (ExecutionState, BarrierConcurrencyState, ...)
:return: The model class required for holding such a state instance
"""
from rafcon.gui.models.state import StateModel
from rafcon.gui.models.container_state import ContainerStateModel
from rafcon.gui.models.library_state import LibraryStateModel
if isinstance(state, ContainerState):
return ContainerStateModel
elif isinstance(state, LibraryState):
return LibraryStateModel
elif isinstance(state, State):
return StateModel
else:
logger.warning("There is not model for state of type {0} {1}".format(type(state), state))
return None | python | def get_state_model_class_for_state(state):
"""Determines the model required for the given state class
:param state: Instance of a state (ExecutionState, BarrierConcurrencyState, ...)
:return: The model class required for holding such a state instance
"""
from rafcon.gui.models.state import StateModel
from rafcon.gui.models.container_state import ContainerStateModel
from rafcon.gui.models.library_state import LibraryStateModel
if isinstance(state, ContainerState):
return ContainerStateModel
elif isinstance(state, LibraryState):
return LibraryStateModel
elif isinstance(state, State):
return StateModel
else:
logger.warning("There is not model for state of type {0} {1}".format(type(state), state))
return None | [
"def",
"get_state_model_class_for_state",
"(",
"state",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"models",
".",
"state",
"import",
"StateModel",
"from",
"rafcon",
".",
"gui",
".",
"models",
".",
"container_state",
"import",
"ContainerStateModel",
"from",
"ra... | Determines the model required for the given state class
:param state: Instance of a state (ExecutionState, BarrierConcurrencyState, ...)
:return: The model class required for holding such a state instance | [
"Determines",
"the",
"model",
"required",
"for",
"the",
"given",
"state",
"class"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L48-L65 | train | 40,186 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.update_is_start | def update_is_start(self):
"""Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within.
"""
self.is_start = self.state.is_root_state or \
self.parent is None or \
isinstance(self.parent.state, LibraryState) or \
self.state.state_id == self.state.parent.start_state_id | python | def update_is_start(self):
"""Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within.
"""
self.is_start = self.state.is_root_state or \
self.parent is None or \
isinstance(self.parent.state, LibraryState) or \
self.state.state_id == self.state.parent.start_state_id | [
"def",
"update_is_start",
"(",
"self",
")",
":",
"self",
".",
"is_start",
"=",
"self",
".",
"state",
".",
"is_root_state",
"or",
"self",
".",
"parent",
"is",
"None",
"or",
"isinstance",
"(",
"self",
".",
"parent",
".",
"state",
",",
"LibraryState",
")",
... | Updates the `is_start` property of the state
A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's
state_id is identical with the ContainerState.start_state_id of the ContainerState it is within. | [
"Updates",
"the",
"is_start",
"property",
"of",
"the",
"state",
"A",
"state",
"is",
"a",
"start",
"state",
"if",
"it",
"is",
"the",
"root",
"state",
"it",
"has",
"no",
"parent",
"the",
"parent",
"is",
"a",
"LibraryState",
"or",
"the",
"state",
"s",
"st... | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L185-L194 | train | 40,187 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.get_state_machine_m | def get_state_machine_m(self, two_factor_check=True):
""" Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model
"""
from rafcon.gui.singleton import state_machine_manager_model
state_machine = self.state.get_state_machine()
if state_machine:
if state_machine.state_machine_id in state_machine_manager_model.state_machines:
sm_m = state_machine_manager_model.state_machines[state_machine.state_machine_id]
if not two_factor_check or sm_m.get_state_model_by_path(self.state.get_path()) is self:
return sm_m
else:
logger.debug("State model requesting its state machine model parent seems to be obsolete. "
"This is a hint to duplicated models and dirty coding")
return None | python | def get_state_machine_m(self, two_factor_check=True):
""" Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model
"""
from rafcon.gui.singleton import state_machine_manager_model
state_machine = self.state.get_state_machine()
if state_machine:
if state_machine.state_machine_id in state_machine_manager_model.state_machines:
sm_m = state_machine_manager_model.state_machines[state_machine.state_machine_id]
if not two_factor_check or sm_m.get_state_model_by_path(self.state.get_path()) is self:
return sm_m
else:
logger.debug("State model requesting its state machine model parent seems to be obsolete. "
"This is a hint to duplicated models and dirty coding")
return None | [
"def",
"get_state_machine_m",
"(",
"self",
",",
"two_factor_check",
"=",
"True",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"singleton",
"import",
"state_machine_manager_model",
"state_machine",
"=",
"self",
".",
"state",
".",
"get_state_machine",
"(",
")",
"i... | Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model | [
"Get",
"respective",
"state",
"machine",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L274-L294 | train | 40,188 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.get_input_data_port_m | def get_input_data_port_m(self, data_port_id):
"""Returns the input data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.input_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | python | def get_input_data_port_m(self, data_port_id):
"""Returns the input data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.input_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | [
"def",
"get_input_data_port_m",
"(",
"self",
",",
"data_port_id",
")",
":",
"for",
"data_port_m",
"in",
"self",
".",
"input_data_ports",
":",
"if",
"data_port_m",
".",
"data_port",
".",
"data_port_id",
"==",
"data_port_id",
":",
"return",
"data_port_m",
"return",
... | Returns the input data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id | [
"Returns",
"the",
"input",
"data",
"port",
"model",
"for",
"the",
"given",
"data",
"port",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L296-L305 | train | 40,189 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.get_output_data_port_m | def get_output_data_port_m(self, data_port_id):
"""Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.output_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | python | def get_output_data_port_m(self, data_port_id):
"""Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id
"""
for data_port_m in self.output_data_ports:
if data_port_m.data_port.data_port_id == data_port_id:
return data_port_m
return None | [
"def",
"get_output_data_port_m",
"(",
"self",
",",
"data_port_id",
")",
":",
"for",
"data_port_m",
"in",
"self",
".",
"output_data_ports",
":",
"if",
"data_port_m",
".",
"data_port",
".",
"data_port_id",
"==",
"data_port_id",
":",
"return",
"data_port_m",
"return"... | Returns the output data port model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the data port with the given id | [
"Returns",
"the",
"output",
"data",
"port",
"model",
"for",
"the",
"given",
"data",
"port",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L307-L316 | train | 40,190 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.get_outcome_m | def get_outcome_m(self, outcome_id):
"""Returns the outcome model for the given outcome id
:param outcome_id: The outcome id to search for
:return: The model of the outcome with the given id
"""
for outcome_m in self.outcomes:
if outcome_m.outcome.outcome_id == outcome_id:
return outcome_m
return False | python | def get_outcome_m(self, outcome_id):
"""Returns the outcome model for the given outcome id
:param outcome_id: The outcome id to search for
:return: The model of the outcome with the given id
"""
for outcome_m in self.outcomes:
if outcome_m.outcome.outcome_id == outcome_id:
return outcome_m
return False | [
"def",
"get_outcome_m",
"(",
"self",
",",
"outcome_id",
")",
":",
"for",
"outcome_m",
"in",
"self",
".",
"outcomes",
":",
"if",
"outcome_m",
".",
"outcome",
".",
"outcome_id",
"==",
"outcome_id",
":",
"return",
"outcome_m",
"return",
"False"
] | Returns the outcome model for the given outcome id
:param outcome_id: The outcome id to search for
:return: The model of the outcome with the given id | [
"Returns",
"the",
"outcome",
"model",
"for",
"the",
"given",
"outcome",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L334-L343 | train | 40,191 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.action_signal_triggered | def action_signal_triggered(self, model, prop_name, info):
"""This method notifies the parent state and child state models about complex actions
"""
msg = info.arg
# print("action_signal_triggered state: ", self.state.state_id, model, prop_name, info)
if msg.action.startswith('sm_notification_'):
return
# # affected child propagation from state
# if hasattr(self, 'states'):
# for m in info['arg'].affected_models:
# print(m, self.states)
# print([m is mm for mm in self.states.values()], [m in self for m in info['arg'].affected_models], \)
# [m in self.states.values() for m in info['arg'].affected_models]
if any([m in self for m in info['arg'].affected_models]):
if not msg.action.startswith('parent_notification_'):
new_msg = msg._replace(action='parent_notification_' + msg.action)
else:
new_msg = msg
for m in info['arg'].affected_models:
# print('???propagate it to', m, m.parent)
if isinstance(m, AbstractStateModel) and m in self:
# print('!!!propagate it from {0} to {1} {2}'.format(self.state.state_id, m.state.state_id, m))
m.action_signal.emit(new_msg)
if msg.action.startswith('parent_notification_'):
return
# recursive propagation of action signal TODO remove finally
if self.parent is not None:
# Notify parent about change of meta data
info.arg = msg
# print("DONE1", self.state.state_id, msg)
self.parent.action_signal_triggered(model, prop_name, info)
# print("FINISH DONE1", self.state.state_id, msg)
# state machine propagation of action signal (indirect) TODO remove finally
elif not msg.action.startswith('sm_notification_'): # Prevent recursive call
# If we are the root state, inform the state machine model by emitting our own meta signal.
# To make the signal distinguishable for a change of meta data to our state, the change property of
# the message is prepended with 'sm_notification_'
# print("DONE2", self.state.state_id, msg)
new_msg = msg._replace(action='sm_notification_' + msg.action)
self.action_signal.emit(new_msg)
# print("FINISH DONE2", self.state.state_id, msg)
else:
# print("DONE3 NOTHING")
pass | python | def action_signal_triggered(self, model, prop_name, info):
"""This method notifies the parent state and child state models about complex actions
"""
msg = info.arg
# print("action_signal_triggered state: ", self.state.state_id, model, prop_name, info)
if msg.action.startswith('sm_notification_'):
return
# # affected child propagation from state
# if hasattr(self, 'states'):
# for m in info['arg'].affected_models:
# print(m, self.states)
# print([m is mm for mm in self.states.values()], [m in self for m in info['arg'].affected_models], \)
# [m in self.states.values() for m in info['arg'].affected_models]
if any([m in self for m in info['arg'].affected_models]):
if not msg.action.startswith('parent_notification_'):
new_msg = msg._replace(action='parent_notification_' + msg.action)
else:
new_msg = msg
for m in info['arg'].affected_models:
# print('???propagate it to', m, m.parent)
if isinstance(m, AbstractStateModel) and m in self:
# print('!!!propagate it from {0} to {1} {2}'.format(self.state.state_id, m.state.state_id, m))
m.action_signal.emit(new_msg)
if msg.action.startswith('parent_notification_'):
return
# recursive propagation of action signal TODO remove finally
if self.parent is not None:
# Notify parent about change of meta data
info.arg = msg
# print("DONE1", self.state.state_id, msg)
self.parent.action_signal_triggered(model, prop_name, info)
# print("FINISH DONE1", self.state.state_id, msg)
# state machine propagation of action signal (indirect) TODO remove finally
elif not msg.action.startswith('sm_notification_'): # Prevent recursive call
# If we are the root state, inform the state machine model by emitting our own meta signal.
# To make the signal distinguishable for a change of meta data to our state, the change property of
# the message is prepended with 'sm_notification_'
# print("DONE2", self.state.state_id, msg)
new_msg = msg._replace(action='sm_notification_' + msg.action)
self.action_signal.emit(new_msg)
# print("FINISH DONE2", self.state.state_id, msg)
else:
# print("DONE3 NOTHING")
pass | [
"def",
"action_signal_triggered",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"msg",
"=",
"info",
".",
"arg",
"# print(\"action_signal_triggered state: \", self.state.state_id, model, prop_name, info)",
"if",
"msg",
".",
"action",
".",
"startswit... | This method notifies the parent state and child state models about complex actions | [
"This",
"method",
"notifies",
"the",
"parent",
"state",
"and",
"child",
"state",
"models",
"about",
"complex",
"actions"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L376-L421 | train | 40,192 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.load_meta_data | def load_meta_data(self, path=None):
"""Load meta data of state model from the file system
The meta data of the state model is loaded from the file system and stored in the meta property of the model.
Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
etc) are loaded, as those stored in the same file as the meta data of the state.
This is either called on the __init__ of a new state model or if a state model for a container state is created,
which then calls load_meta_data for all its children.
:param str path: Optional file system path to the meta data file. If not given, the path will be derived from
the state's path on the filesystem
:return: if meta data file was loaded True otherwise False
:rtype: bool
"""
# TODO: for an Execution state this method is called for each hierarchy level again and again, still?? check it!
# print("1AbstractState_load_meta_data: ", path, not path)
if not path:
path = self.state.file_system_path
# print("2AbstractState_load_meta_data: ", path)
if path is None:
self.meta = Vividict({})
return False
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA)
# TODO: Should be removed with next minor release
if not os.path.exists(path_meta_data):
logger.debug("Because meta data was not found in {0} use backup option {1}"
"".format(path_meta_data, os.path.join(path, storage.FILE_NAME_META_DATA_OLD)))
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA_OLD)
# TODO use the following logger message to debug meta data load process and to avoid maybe repetitive loads
# if not os.path.exists(path_meta_data):
# logger.info("path not found {0}".format(path_meta_data))
try:
# print("try to load meta data from {0} for state {1}".format(path_meta_data, self.state))
tmp_meta = storage.load_data_file(path_meta_data)
except ValueError as e:
# if no element which is newly generated log a warning
# if os.path.exists(os.path.dirname(path)):
# logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
if not path.startswith(constants.RAFCON_TEMP_PATH_STORAGE) and not os.path.exists(os.path.dirname(path)):
logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
tmp_meta = {}
# JSON returns a dict, which must be converted to a Vividict
tmp_meta = Vividict(tmp_meta)
if tmp_meta:
self._parse_for_element_meta_data(tmp_meta)
# assign the meta data to the state
self.meta = tmp_meta
self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True))
return True
else:
# print("nothing to parse", tmp_meta)
return False | python | def load_meta_data(self, path=None):
"""Load meta data of state model from the file system
The meta data of the state model is loaded from the file system and stored in the meta property of the model.
Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
etc) are loaded, as those stored in the same file as the meta data of the state.
This is either called on the __init__ of a new state model or if a state model for a container state is created,
which then calls load_meta_data for all its children.
:param str path: Optional file system path to the meta data file. If not given, the path will be derived from
the state's path on the filesystem
:return: if meta data file was loaded True otherwise False
:rtype: bool
"""
# TODO: for an Execution state this method is called for each hierarchy level again and again, still?? check it!
# print("1AbstractState_load_meta_data: ", path, not path)
if not path:
path = self.state.file_system_path
# print("2AbstractState_load_meta_data: ", path)
if path is None:
self.meta = Vividict({})
return False
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA)
# TODO: Should be removed with next minor release
if not os.path.exists(path_meta_data):
logger.debug("Because meta data was not found in {0} use backup option {1}"
"".format(path_meta_data, os.path.join(path, storage.FILE_NAME_META_DATA_OLD)))
path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA_OLD)
# TODO use the following logger message to debug meta data load process and to avoid maybe repetitive loads
# if not os.path.exists(path_meta_data):
# logger.info("path not found {0}".format(path_meta_data))
try:
# print("try to load meta data from {0} for state {1}".format(path_meta_data, self.state))
tmp_meta = storage.load_data_file(path_meta_data)
except ValueError as e:
# if no element which is newly generated log a warning
# if os.path.exists(os.path.dirname(path)):
# logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
if not path.startswith(constants.RAFCON_TEMP_PATH_STORAGE) and not os.path.exists(os.path.dirname(path)):
logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
tmp_meta = {}
# JSON returns a dict, which must be converted to a Vividict
tmp_meta = Vividict(tmp_meta)
if tmp_meta:
self._parse_for_element_meta_data(tmp_meta)
# assign the meta data to the state
self.meta = tmp_meta
self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True))
return True
else:
# print("nothing to parse", tmp_meta)
return False | [
"def",
"load_meta_data",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"# TODO: for an Execution state this method is called for each hierarchy level again and again, still?? check it!",
"# print(\"1AbstractState_load_meta_data: \", path, not path)",
"if",
"not",
"path",
":",
"pat... | Load meta data of state model from the file system
The meta data of the state model is loaded from the file system and stored in the meta property of the model.
Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
etc) are loaded, as those stored in the same file as the meta data of the state.
This is either called on the __init__ of a new state model or if a state model for a container state is created,
which then calls load_meta_data for all its children.
:param str path: Optional file system path to the meta data file. If not given, the path will be derived from
the state's path on the filesystem
:return: if meta data file was loaded True otherwise False
:rtype: bool | [
"Load",
"meta",
"data",
"of",
"state",
"model",
"from",
"the",
"file",
"system"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L466-L522 | train | 40,193 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel.store_meta_data | def store_meta_data(self, copy_path=None):
"""Save meta data of state model to the file system
This method generates a dictionary of the meta data of the state together with the meta data of all state
elements (data ports, outcomes, etc.) and stores it on the filesystem.
Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
maybe wrong or None.
The copy path is considered to be a state machine file system path but not the current one but e.g.
of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
machine hierarchy. This folder has to exist.
Dues the core elements of the state machine has to be stored first.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
"""
if copy_path:
meta_file_path_json = os.path.join(copy_path, self.state.get_storage_path(), storage.FILE_NAME_META_DATA)
else:
if self.state.file_system_path is None:
logger.error("Meta data of {0} can be stored temporary arbitrary but by default first after the "
"respective state was stored and a file system path is set.".format(self))
return
meta_file_path_json = os.path.join(self.state.file_system_path, storage.FILE_NAME_META_DATA)
meta_data = deepcopy(self.meta)
self._generate_element_meta_data(meta_data)
storage_utils.write_dict_to_json(meta_data, meta_file_path_json) | python | def store_meta_data(self, copy_path=None):
"""Save meta data of state model to the file system
This method generates a dictionary of the meta data of the state together with the meta data of all state
elements (data ports, outcomes, etc.) and stores it on the filesystem.
Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
maybe wrong or None.
The copy path is considered to be a state machine file system path but not the current one but e.g.
of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
machine hierarchy. This folder has to exist.
Dues the core elements of the state machine has to be stored first.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
"""
if copy_path:
meta_file_path_json = os.path.join(copy_path, self.state.get_storage_path(), storage.FILE_NAME_META_DATA)
else:
if self.state.file_system_path is None:
logger.error("Meta data of {0} can be stored temporary arbitrary but by default first after the "
"respective state was stored and a file system path is set.".format(self))
return
meta_file_path_json = os.path.join(self.state.file_system_path, storage.FILE_NAME_META_DATA)
meta_data = deepcopy(self.meta)
self._generate_element_meta_data(meta_data)
storage_utils.write_dict_to_json(meta_data, meta_file_path_json) | [
"def",
"store_meta_data",
"(",
"self",
",",
"copy_path",
"=",
"None",
")",
":",
"if",
"copy_path",
":",
"meta_file_path_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"copy_path",
",",
"self",
".",
"state",
".",
"get_storage_path",
"(",
")",
",",
"stor... | Save meta data of state model to the file system
This method generates a dictionary of the meta data of the state together with the meta data of all state
elements (data ports, outcomes, etc.) and stores it on the filesystem.
Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
maybe wrong or None.
The copy path is considered to be a state machine file system path but not the current one but e.g.
of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
machine hierarchy. This folder has to exist.
Dues the core elements of the state machine has to be stored first.
:param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine | [
"Save",
"meta",
"data",
"of",
"state",
"model",
"to",
"the",
"file",
"system"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L524-L548 | train | 40,194 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel._parse_for_element_meta_data | def _parse_for_element_meta_data(self, meta_data):
"""Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
:param meta_data: Dictionary of loaded meta data
"""
# print("_parse meta data", meta_data)
for data_port_m in self.input_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "input_data_port",
data_port_m.data_port.data_port_id)
for data_port_m in self.output_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "output_data_port",
data_port_m.data_port.data_port_id)
for outcome_m in self.outcomes:
self._copy_element_meta_data_from_meta_file_data(meta_data, outcome_m, "outcome",
outcome_m.outcome.outcome_id)
if "income" in meta_data:
if "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation
del meta_data["gui"]["editor_gaphas"]["income"]
elif "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation in meta data
meta_data["income"]["gui"]["editor_gaphas"] = meta_data["gui"]["editor_gaphas"]["income"]
del meta_data["gui"]["editor_gaphas"]["income"]
self._copy_element_meta_data_from_meta_file_data(meta_data, self.income, "income", "") | python | def _parse_for_element_meta_data(self, meta_data):
"""Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
:param meta_data: Dictionary of loaded meta data
"""
# print("_parse meta data", meta_data)
for data_port_m in self.input_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "input_data_port",
data_port_m.data_port.data_port_id)
for data_port_m in self.output_data_ports:
self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "output_data_port",
data_port_m.data_port.data_port_id)
for outcome_m in self.outcomes:
self._copy_element_meta_data_from_meta_file_data(meta_data, outcome_m, "outcome",
outcome_m.outcome.outcome_id)
if "income" in meta_data:
if "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation
del meta_data["gui"]["editor_gaphas"]["income"]
elif "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
"income" in meta_data["gui"]["editor_gaphas"]: # chain necessary to prevent key generation in meta data
meta_data["income"]["gui"]["editor_gaphas"] = meta_data["gui"]["editor_gaphas"]["income"]
del meta_data["gui"]["editor_gaphas"]["income"]
self._copy_element_meta_data_from_meta_file_data(meta_data, self.income, "income", "") | [
"def",
"_parse_for_element_meta_data",
"(",
"self",
",",
"meta_data",
")",
":",
"# print(\"_parse meta data\", meta_data)",
"for",
"data_port_m",
"in",
"self",
".",
"input_data_ports",
":",
"self",
".",
"_copy_element_meta_data_from_meta_file_data",
"(",
"meta_data",
",",
... | Load meta data for state elements
The meta data of the state meta data file also contains the meta data for state elements (data ports,
outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
elements is removed from the passed dictionary.
:param meta_data: Dictionary of loaded meta data | [
"Load",
"meta",
"data",
"for",
"state",
"elements"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L574-L601 | train | 40,195 |
DLR-RM/RAFCON | source/rafcon/gui/models/abstract_state.py | AbstractStateModel._copy_element_meta_data_from_meta_file_data | def _copy_element_meta_data_from_meta_file_data(meta_data, element_m, element_name, element_id):
"""Helper method to assign the meta of the given element
The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is
then removed from the dictionary.
:param meta_data: The loaded meta data
:param element_m: The element model that is supposed to retrieve the meta data
:param element_name: The name string of the element type in the dictionary
:param element_id: The id of the element
"""
meta_data_element_id = element_name + str(element_id)
meta_data_element = meta_data[meta_data_element_id]
# print(meta_data_element_id, element_m, meta_data_element)
element_m.meta = meta_data_element
del meta_data[meta_data_element_id] | python | def _copy_element_meta_data_from_meta_file_data(meta_data, element_m, element_name, element_id):
"""Helper method to assign the meta of the given element
The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is
then removed from the dictionary.
:param meta_data: The loaded meta data
:param element_m: The element model that is supposed to retrieve the meta data
:param element_name: The name string of the element type in the dictionary
:param element_id: The id of the element
"""
meta_data_element_id = element_name + str(element_id)
meta_data_element = meta_data[meta_data_element_id]
# print(meta_data_element_id, element_m, meta_data_element)
element_m.meta = meta_data_element
del meta_data[meta_data_element_id] | [
"def",
"_copy_element_meta_data_from_meta_file_data",
"(",
"meta_data",
",",
"element_m",
",",
"element_name",
",",
"element_id",
")",
":",
"meta_data_element_id",
"=",
"element_name",
"+",
"str",
"(",
"element_id",
")",
"meta_data_element",
"=",
"meta_data",
"[",
"me... | Helper method to assign the meta of the given element
The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is
then removed from the dictionary.
:param meta_data: The loaded meta data
:param element_m: The element model that is supposed to retrieve the meta data
:param element_name: The name string of the element type in the dictionary
:param element_id: The id of the element | [
"Helper",
"method",
"to",
"assign",
"the",
"meta",
"of",
"the",
"given",
"element"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/abstract_state.py#L604-L619 | train | 40,196 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/source_editor.py | SourceEditorController.apply_clicked | def apply_clicked(self, button):
"""Triggered when the Apply button in the source editor is clicked.
"""
if isinstance(self.model.state, LibraryState):
logger.warning("It is not allowed to modify libraries.")
self.view.set_text("")
return
# Ugly workaround to give user at least some feedback about the parser
# Without the loop, this function would block the GTK main loop and the log message would appear after the
# function has finished
# TODO: run parser in separate thread
while Gtk.events_pending():
Gtk.main_iteration_do(False)
# get script
current_text = self.view.get_text()
# Directly apply script if linter was deactivated
if not self.view['pylint_check_button'].get_active():
self.set_script_text(current_text)
return
logger.debug("Parsing execute script...")
with open(self.tmp_file, "w") as text_file:
text_file.write(current_text)
# clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state
MANAGER.astroid_cache.clear()
lint_config_file = resource_filename(rafcon.__name__, "pylintrc")
args = ["--rcfile={}".format(lint_config_file)] # put your own here
with contextlib.closing(StringIO()) as dummy_buffer:
json_report = JSONReporter(dummy_buffer.getvalue())
try:
lint.Run([self.tmp_file] + args, reporter=json_report, exit=False)
except:
logger.exception("Could not run linter to check script")
os.remove(self.tmp_file)
if json_report.messages:
def on_message_dialog_response_signal(widget, response_id):
if response_id == 1:
self.set_script_text(current_text)
else:
logger.debug("The script was not saved")
widget.destroy()
message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:"
line = None
for message in json_report.messages:
(error_string, line) = self.format_error_string(message)
message_string += "\n\n" + error_string
# focus line of error
if line:
tbuffer = self.view.get_buffer()
start_iter = tbuffer.get_start_iter()
start_iter.set_line(int(line)-1)
tbuffer.place_cursor(start_iter)
message_string += "\n\nThe line was focused in the source editor."
self.view.scroll_to_cursor_onscreen()
# select state to show source editor
sm_m = state_machine_manager_model.get_state_machine_model(self.model)
if sm_m.selection.get_selected_state() is not self.model:
sm_m.selection.set(self.model)
dialog = RAFCONButtonDialog(message_string, ["Save with errors", "Do not save"],
on_message_dialog_response_signal,
message_type=Gtk.MessageType.WARNING, parent=self.get_root_window())
result = dialog.run()
else:
self.set_script_text(current_text) | python | def apply_clicked(self, button):
"""Triggered when the Apply button in the source editor is clicked.
"""
if isinstance(self.model.state, LibraryState):
logger.warning("It is not allowed to modify libraries.")
self.view.set_text("")
return
# Ugly workaround to give user at least some feedback about the parser
# Without the loop, this function would block the GTK main loop and the log message would appear after the
# function has finished
# TODO: run parser in separate thread
while Gtk.events_pending():
Gtk.main_iteration_do(False)
# get script
current_text = self.view.get_text()
# Directly apply script if linter was deactivated
if not self.view['pylint_check_button'].get_active():
self.set_script_text(current_text)
return
logger.debug("Parsing execute script...")
with open(self.tmp_file, "w") as text_file:
text_file.write(current_text)
# clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state
MANAGER.astroid_cache.clear()
lint_config_file = resource_filename(rafcon.__name__, "pylintrc")
args = ["--rcfile={}".format(lint_config_file)] # put your own here
with contextlib.closing(StringIO()) as dummy_buffer:
json_report = JSONReporter(dummy_buffer.getvalue())
try:
lint.Run([self.tmp_file] + args, reporter=json_report, exit=False)
except:
logger.exception("Could not run linter to check script")
os.remove(self.tmp_file)
if json_report.messages:
def on_message_dialog_response_signal(widget, response_id):
if response_id == 1:
self.set_script_text(current_text)
else:
logger.debug("The script was not saved")
widget.destroy()
message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:"
line = None
for message in json_report.messages:
(error_string, line) = self.format_error_string(message)
message_string += "\n\n" + error_string
# focus line of error
if line:
tbuffer = self.view.get_buffer()
start_iter = tbuffer.get_start_iter()
start_iter.set_line(int(line)-1)
tbuffer.place_cursor(start_iter)
message_string += "\n\nThe line was focused in the source editor."
self.view.scroll_to_cursor_onscreen()
# select state to show source editor
sm_m = state_machine_manager_model.get_state_machine_model(self.model)
if sm_m.selection.get_selected_state() is not self.model:
sm_m.selection.set(self.model)
dialog = RAFCONButtonDialog(message_string, ["Save with errors", "Do not save"],
on_message_dialog_response_signal,
message_type=Gtk.MessageType.WARNING, parent=self.get_root_window())
result = dialog.run()
else:
self.set_script_text(current_text) | [
"def",
"apply_clicked",
"(",
"self",
",",
"button",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
".",
"state",
",",
"LibraryState",
")",
":",
"logger",
".",
"warning",
"(",
"\"It is not allowed to modify libraries.\"",
")",
"self",
".",
"view",
"... | Triggered when the Apply button in the source editor is clicked. | [
"Triggered",
"when",
"the",
"Apply",
"button",
"in",
"the",
"source",
"editor",
"is",
"clicked",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/source_editor.py#L143-L217 | train | 40,197 |
DLR-RM/RAFCON | source/rafcon/gui/views/logging_console.py | LoggingConsoleView.update_auto_scroll_mode | def update_auto_scroll_mode(self):
""" Register or un-register signals for follow mode """
if self._enables['CONSOLE_FOLLOW_LOGGING']:
if self._auto_scroll_handler_id is None:
self._auto_scroll_handler_id = self.text_view.connect("size-allocate", self._auto_scroll)
else:
if self._auto_scroll_handler_id is not None:
self.text_view.disconnect(self._auto_scroll_handler_id)
self._auto_scroll_handler_id = None | python | def update_auto_scroll_mode(self):
""" Register or un-register signals for follow mode """
if self._enables['CONSOLE_FOLLOW_LOGGING']:
if self._auto_scroll_handler_id is None:
self._auto_scroll_handler_id = self.text_view.connect("size-allocate", self._auto_scroll)
else:
if self._auto_scroll_handler_id is not None:
self.text_view.disconnect(self._auto_scroll_handler_id)
self._auto_scroll_handler_id = None | [
"def",
"update_auto_scroll_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_enables",
"[",
"'CONSOLE_FOLLOW_LOGGING'",
"]",
":",
"if",
"self",
".",
"_auto_scroll_handler_id",
"is",
"None",
":",
"self",
".",
"_auto_scroll_handler_id",
"=",
"self",
".",
"text_vi... | Register or un-register signals for follow mode | [
"Register",
"or",
"un",
"-",
"register",
"signals",
"for",
"follow",
"mode"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/logging_console.py#L140-L148 | train | 40,198 |
DLR-RM/RAFCON | source/rafcon/gui/views/logging_console.py | LoggingConsoleView._auto_scroll | def _auto_scroll(self, *args):
""" Scroll to the end of the text view """
adj = self['scrollable'].get_vadjustment()
adj.set_value(adj.get_upper() - adj.get_page_size()) | python | def _auto_scroll(self, *args):
""" Scroll to the end of the text view """
adj = self['scrollable'].get_vadjustment()
adj.set_value(adj.get_upper() - adj.get_page_size()) | [
"def",
"_auto_scroll",
"(",
"self",
",",
"*",
"args",
")",
":",
"adj",
"=",
"self",
"[",
"'scrollable'",
"]",
".",
"get_vadjustment",
"(",
")",
"adj",
".",
"set_value",
"(",
"adj",
".",
"get_upper",
"(",
")",
"-",
"adj",
".",
"get_page_size",
"(",
")... | Scroll to the end of the text view | [
"Scroll",
"to",
"the",
"end",
"of",
"the",
"text",
"view"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/logging_console.py#L150-L153 | train | 40,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.