Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Towers.__contains__
(self, x)
Does this :class:`Towers` contain the given :class:`Rod`. :param Rod x: The :class:`Rod` to find. :rtype: bool
Does this :class:`Towers` contain the given :class:`Rod`.
def __contains__(self, x): """ Does this :class:`Towers` contain the given :class:`Rod`. :param Rod x: The :class:`Rod` to find. :rtype: bool """ if isinstance(x, Rod): return x in self._rods
[ "def", "__contains__", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "Rod", ")", ":", "return", "x", "in", "self", ".", "_rods" ]
[ 202, 4 ]
[ 212, 34 ]
python
en
['en', 'error', 'th']
False
Towers.__len__
(self)
Determine how many :class:`Rod`'s this :class:`Towers` contains. :rtype: int
Determine how many :class:`Rod`'s this :class:`Towers` contains.
def __len__(self): """ Determine how many :class:`Rod`'s this :class:`Towers` contains. :rtype: int """ return len(self._rods)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_rods", ")" ]
[ 214, 4 ]
[ 221, 30 ]
python
en
['en', 'error', 'th']
False
Towers.__iter__
(self)
Run the towers, yielding :class:`Move` instances.
Run the towers, yielding :class:`Move` instances.
def __iter__(self): """ Run the towers, yielding :class:`Move` instances. """ for i in self.move_tower( height=self.height, start=self.start_rod, end=self.end_rod, tmp=self.tmp_rod, ): yield i
[ "def", "__iter__", "(", "self", ")", ":", "for", "i", "in", "self", ".", "move_tower", "(", "height", "=", "self", ".", "height", ",", "start", "=", "self", ".", "start_rod", ",", "end", "=", "self", ".", "end_rod", ",", "tmp", "=", "self", ".", "tmp_rod", ",", ")", ":", "yield", "i" ]
[ 223, 4 ]
[ 233, 19 ]
python
en
['en', 'error', 'th']
False
Towers.verbose
(self)
Obtain this instance's verbose flag. :rtype: bool
Obtain this instance's verbose flag.
def verbose(self): """ Obtain this instance's verbose flag. :rtype: bool """ return self._verbose
[ "def", "verbose", "(", "self", ")", ":", "return", "self", ".", "_verbose" ]
[ 239, 4 ]
[ 246, 28 ]
python
en
['en', 'error', 'th']
False
Towers.verbose
(self, verbose)
Set this instance's verbose flag :param object verbose: True=enable verbose logging mode.
Set this instance's verbose flag
def verbose(self, verbose): """ Set this instance's verbose flag :param object verbose: True=enable verbose logging mode. """ self._verbose = bool(verbose)
[ "def", "verbose", "(", "self", ",", "verbose", ")", ":", "self", ".", "_verbose", "=", "bool", "(", "verbose", ")" ]
[ 249, 4 ]
[ 256, 37 ]
python
en
['en', 'error', 'th']
False
Towers.moves
(self)
Determine how many moves have occurred so far. :rtype: int
Determine how many moves have occurred so far.
def moves(self): """ Determine how many moves have occurred so far. :rtype: int """ return self._moves
[ "def", "moves", "(", "self", ")", ":", "return", "self", ".", "_moves" ]
[ 259, 4 ]
[ 266, 26 ]
python
en
['en', 'error', 'th']
False
Towers.height
(self)
Obtain the height of the :class:`Towers` (ie: max number of disks each one rod can hold). :rtype: int
Obtain the height of the :class:`Towers` (ie: max number of disks each one rod can hold).
def height(self): """ Obtain the height of the :class:`Towers` (ie: max number of disks each one rod can hold). :rtype: int """ return self._rods.height
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "_rods", ".", "height" ]
[ 269, 4 ]
[ 276, 32 ]
python
en
['en', 'error', 'th']
False
Towers.moves_for_height
(height)
Determine the max number of moves required to solve the puzzle for the given height :param int height: The height of the :class:`Rods` (number of :class:`Disk` on a :class:`Rod`). :rtype: int
Determine the max number of moves required to solve the puzzle for the given height
def moves_for_height(height): """ Determine the max number of moves required to solve the puzzle for the given height :param int height: The height of the :class:`Rods` (number of :class:`Disk` on a :class:`Rod`). :rtype: int """ return int(math.pow(2, height)) - 1
[ "def", "moves_for_height", "(", "height", ")", ":", "return", "int", "(", "math", ".", "pow", "(", "2", ",", "height", ")", ")", "-", "1" ]
[ 279, 4 ]
[ 287, 43 ]
python
en
['en', 'error', 'th']
False
Towers.validate_start
(self)
Validate the start conditions for this towers :raises InvalidTowerHeight: The height of the :class:`Towers` is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size. :raises InvalidStartingConditions: Initial conditions are invalid.
Validate the start conditions for this towers
def validate_start(self): """ Validate the start conditions for this towers :raises InvalidTowerHeight: The height of the :class:`Towers` is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size. :raises InvalidStartingConditions: Initial conditions are invalid. """ validate_height(self.height) self._rods.validate() if not (bool(self._rods.start) and not bool(self._rods.end)): raise InvalidStartingConditions(self._rods, self.moves) if self.moves != 0: raise InvalidStartingConditions(self._rods, self.moves)
[ "def", "validate_start", "(", "self", ")", ":", "validate_height", "(", "self", ".", "height", ")", "self", ".", "_rods", ".", "validate", "(", ")", "if", "not", "(", "bool", "(", "self", ".", "_rods", ".", "start", ")", "and", "not", "bool", "(", "self", ".", "_rods", ".", "end", ")", ")", ":", "raise", "InvalidStartingConditions", "(", "self", ".", "_rods", ",", "self", ".", "moves", ")", "if", "self", ".", "moves", "!=", "0", ":", "raise", "InvalidStartingConditions", "(", "self", ".", "_rods", ",", "self", ".", "moves", ")" ]
[ 289, 4 ]
[ 309, 67 ]
python
en
['en', 'error', 'th']
False
Towers.validate_end
(self)
Validate the end conditions for this towers. :raises InvalidTowerHeight: The height of the tower is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size. :raises InvalidEndingConditions: End conditions are invalid.
Validate the end conditions for this towers.
def validate_end(self): """ Validate the end conditions for this towers. :raises InvalidTowerHeight: The height of the tower is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size. :raises InvalidEndingConditions: End conditions are invalid. """ validate_height(self.height) self._rods.validate() if not (bool(self._rods.end) and not bool(self._rods.start)): raise InvalidEndingConditions(self._rods)
[ "def", "validate_end", "(", "self", ")", ":", "validate_height", "(", "self", ".", "height", ")", "self", ".", "_rods", ".", "validate", "(", ")", "if", "not", "(", "bool", "(", "self", ".", "_rods", ".", "end", ")", "and", "not", "bool", "(", "self", ".", "_rods", ".", "start", ")", ")", ":", "raise", "InvalidEndingConditions", "(", "self", ".", "_rods", ")" ]
[ 311, 4 ]
[ 328, 53 ]
python
en
['en', 'error', 'th']
False
Towers.validate
(self)
Perform self validation. :raises InvalidTowerHeight: The height of the tower is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size.
Perform self validation.
def validate(self): """ Perform self validation. :raises InvalidTowerHeight: The height of the tower is invalid :raises DuplicateDisk: This :class:`Rod` already contains this :class:`Disk`. :raises CorruptRod: A :class:`Disk` is on top of a :class:`Disk` of smaller size. """ validate_height(self.height) self._rods.validate()
[ "def", "validate", "(", "self", ")", ":", "validate_height", "(", "self", ".", "height", ")", "self", ".", "_rods", ".", "validate", "(", ")" ]
[ 330, 4 ]
[ 342, 29 ]
python
en
['en', 'error', 'th']
False
Towers.__enter__
(self)
Context-Manager entry, validate our entry state for towers-start conditions. :raises: See :func:`Towers.validate_start`.
Context-Manager entry, validate our entry state for towers-start conditions.
def __enter__(self): """ Context-Manager entry, validate our entry state for towers-start conditions. :raises: See :func:`Towers.validate_start`. """ self.validate_start()
[ "def", "__enter__", "(", "self", ")", ":", "self", ".", "validate_start", "(", ")" ]
[ 344, 4 ]
[ 351, 29 ]
python
en
['en', 'error', 'th']
False
Towers.__exit__
(self, *args, **kwargs)
Context-Manager exit, validate our exit state for towers-end conditions. :raises: See :func:`Towers.validate_end`.
Context-Manager exit, validate our exit state for towers-end conditions.
def __exit__(self, *args, **kwargs): """ Context-Manager exit, validate our exit state for towers-end conditions. :raises: See :func:`Towers.validate_end`. """ self.validate_end()
[ "def", "__exit__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "validate_end", "(", ")" ]
[ 353, 4 ]
[ 360, 27 ]
python
en
['en', 'error', 'th']
False
Towers.__call__
(self)
Run the towers. Convenience method. :raises: See :func:`Towers.move_tower`.
Run the towers. Convenience method.
def __call__(self): """ Run the towers. Convenience method. :raises: See :func:`Towers.move_tower`. """ for i in self: if self.verbose: print(i)
[ "def", "__call__", "(", "self", ")", ":", "for", "i", "in", "self", ":", "if", "self", ".", "verbose", ":", "print", "(", "i", ")" ]
[ 362, 4 ]
[ 371, 24 ]
python
en
['en', 'error', 'th']
False
Towers.start_rod
(self)
Retrieve the start :class:`Rod` for this towers. :rtype: Rod
Retrieve the start :class:`Rod` for this towers.
def start_rod(self): """ Retrieve the start :class:`Rod` for this towers. :rtype: Rod """ return self._rods.start
[ "def", "start_rod", "(", "self", ")", ":", "return", "self", ".", "_rods", ".", "start" ]
[ 374, 4 ]
[ 381, 31 ]
python
en
['en', 'error', 'th']
False
Towers.end_rod
(self)
Retrieve the end :class:`Rod` for this towers. :rtype: Rod
Retrieve the end :class:`Rod` for this towers.
def end_rod(self): """ Retrieve the end :class:`Rod` for this towers. :rtype: Rod """ return self._rods.end
[ "def", "end_rod", "(", "self", ")", ":", "return", "self", ".", "_rods", ".", "end" ]
[ 384, 4 ]
[ 391, 29 ]
python
en
['en', 'error', 'th']
False
Towers.tmp_rod
(self)
Retrieve the temporary :class:`Rod` for this towers. :rtype: Rod
Retrieve the temporary :class:`Rod` for this towers.
def tmp_rod(self): """ Retrieve the temporary :class:`Rod` for this towers. :rtype: Rod """ return self._rods.tmp
[ "def", "tmp_rod", "(", "self", ")", ":", "return", "self", ".", "_rods", ".", "tmp" ]
[ 394, 4 ]
[ 401, 29 ]
python
en
['en', 'error', 'th']
False
Towers.move_tower
(self, height, start, end, tmp)
Move the stack of `Disks` on a `Rod`. :param int height: The height of the :class:`Disk` to move. :param Rod start: The :class:`Rod` to move the :class:`Disk` from. :param Rod end: The :class:`Rod` to move the :class:`Disk` to. :param Rod tmp: The intermediary :class:`Rod` to use when moving the :class:`Disk`.
Move the stack of `Disks` on a `Rod`.
def move_tower(self, height, start, end, tmp): """ Move the stack of `Disks` on a `Rod`. :param int height: The height of the :class:`Disk` to move. :param Rod start: The :class:`Rod` to move the :class:`Disk` from. :param Rod end: The :class:`Rod` to move the :class:`Disk` to. :param Rod tmp: The intermediary :class:`Rod` to use when moving the :class:`Disk`. """ if height >= 1: for i in self.move_tower(height - 1, start, tmp, end): yield i for i in self.move_disk(start, end): yield i for i in self.move_tower(height - 1, tmp, end, start): yield i elif height == 1: for i in self.move_disk(start, end): yield i
[ "def", "move_tower", "(", "self", ",", "height", ",", "start", ",", "end", ",", "tmp", ")", ":", "if", "height", ">=", "1", ":", "for", "i", "in", "self", ".", "move_tower", "(", "height", "-", "1", ",", "start", ",", "tmp", ",", "end", ")", ":", "yield", "i", "for", "i", "in", "self", ".", "move_disk", "(", "start", ",", "end", ")", ":", "yield", "i", "for", "i", "in", "self", ".", "move_tower", "(", "height", "-", "1", ",", "tmp", ",", "end", ",", "start", ")", ":", "yield", "i", "elif", "height", "==", "1", ":", "for", "i", "in", "self", ".", "move_disk", "(", "start", ",", "end", ")", ":", "yield", "i" ]
[ 403, 4 ]
[ 425, 23 ]
python
en
['en', 'error', 'th']
False
Towers.move_disk
(self, start, end)
Move the `Disk` from one Rod to another. :note: Generator, yields `Move` instances. :param Rod start: The :class:`Rod` to remove the :class:`Disk` from. :param Rod end: The :class:`Rods` to move the :class:`Disk` to.
Move the `Disk` from one Rod to another.
def move_disk(self, start, end): """ Move the `Disk` from one Rod to another. :note: Generator, yields `Move` instances. :param Rod start: The :class:`Rod` to remove the :class:`Disk` from. :param Rod end: The :class:`Rods` to move the :class:`Disk` to. """ start_rod = copy.deepcopy(start) end_rod = copy.deepcopy(end) moves = self.moves disk = start.pop() move = Move(disk, start_rod, end_rod, moves) end.append(disk) self._moves += 1 yield move
[ "def", "move_disk", "(", "self", ",", "start", ",", "end", ")", ":", "start_rod", "=", "copy", ".", "deepcopy", "(", "start", ")", "end_rod", "=", "copy", ".", "deepcopy", "(", "end", ")", "moves", "=", "self", ".", "moves", "disk", "=", "start", ".", "pop", "(", ")", "move", "=", "Move", "(", "disk", ",", "start_rod", ",", "end_rod", ",", "moves", ")", "end", ".", "append", "(", "disk", ")", "self", ".", "_moves", "+=", "1", "yield", "move" ]
[ 427, 4 ]
[ 449, 18 ]
python
en
['en', 'error', 'th']
False
Stat.__getattr__
(self, id)
Calculate missing attribute
Calculate missing attribute
def __getattr__(self, id): """Calculate missing attribute""" if id[:4] == "_get": raise AttributeError(id) # calculate missing attribute v = getattr(self, "_get" + id)() setattr(self, id, v) return v
[ "def", "__getattr__", "(", "self", ",", "id", ")", ":", "if", "id", "[", ":", "4", "]", "==", "\"_get\"", ":", "raise", "AttributeError", "(", "id", ")", "# calculate missing attribute", "v", "=", "getattr", "(", "self", ",", "\"_get\"", "+", "id", ")", "(", ")", "setattr", "(", "self", ",", "id", ",", "v", ")", "return", "v" ]
[ 41, 4 ]
[ 48, 16 ]
python
en
['en', 'co', 'en']
True
Stat._getextrema
(self)
Get min/max values for each band in the image
Get min/max values for each band in the image
def _getextrema(self): """Get min/max values for each band in the image""" def minmax(histogram): n = 255 x = 0 for i in range(256): if histogram[i]: n = min(n, i) x = max(x, i) return n, x # returns (255, 0) if there's no data in the histogram v = [] for i in range(0, len(self.h), 256): v.append(minmax(self.h[i:])) return v
[ "def", "_getextrema", "(", "self", ")", ":", "def", "minmax", "(", "histogram", ")", ":", "n", "=", "255", "x", "=", "0", "for", "i", "in", "range", "(", "256", ")", ":", "if", "histogram", "[", "i", "]", ":", "n", "=", "min", "(", "n", ",", "i", ")", "x", "=", "max", "(", "x", ",", "i", ")", "return", "n", ",", "x", "# returns (255, 0) if there's no data in the histogram", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "v", ".", "append", "(", "minmax", "(", "self", ".", "h", "[", "i", ":", "]", ")", ")", "return", "v" ]
[ 50, 4 ]
[ 65, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getcount
(self)
Get total number of pixels in each layer
Get total number of pixels in each layer
def _getcount(self): """Get total number of pixels in each layer""" v = [] for i in range(0, len(self.h), 256): v.append(functools.reduce(operator.add, self.h[i : i + 256])) return v
[ "def", "_getcount", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "v", ".", "append", "(", "functools", ".", "reduce", "(", "operator", ".", "add", ",", "self", ".", "h", "[", "i", ":", "i", "+", "256", "]", ")", ")", "return", "v" ]
[ 67, 4 ]
[ 73, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getsum
(self)
Get sum of all pixels in each layer
Get sum of all pixels in each layer
def _getsum(self): """Get sum of all pixels in each layer""" v = [] for i in range(0, len(self.h), 256): layerSum = 0.0 for j in range(256): layerSum += j * self.h[i + j] v.append(layerSum) return v
[ "def", "_getsum", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "layerSum", "=", "0.0", "for", "j", "in", "range", "(", "256", ")", ":", "layerSum", "+=", "j", "*", "self", ".", "h", "[", "i", "+", "j", "]", "v", ".", "append", "(", "layerSum", ")", "return", "v" ]
[ 75, 4 ]
[ 84, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getsum2
(self)
Get squared sum of all pixels in each layer
Get squared sum of all pixels in each layer
def _getsum2(self): """Get squared sum of all pixels in each layer""" v = [] for i in range(0, len(self.h), 256): sum2 = 0.0 for j in range(256): sum2 += (j ** 2) * float(self.h[i + j]) v.append(sum2) return v
[ "def", "_getsum2", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "sum2", "=", "0.0", "for", "j", "in", "range", "(", "256", ")", ":", "sum2", "+=", "(", "j", "**", "2", ")", "*", "float", "(", "self", ".", "h", "[", "i", "+", "j", "]", ")", "v", ".", "append", "(", "sum2", ")", "return", "v" ]
[ 86, 4 ]
[ 95, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getmean
(self)
Get average pixel level for each layer
Get average pixel level for each layer
def _getmean(self): """Get average pixel level for each layer""" v = [] for i in self.bands: v.append(self.sum[i] / self.count[i]) return v
[ "def", "_getmean", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "v", ".", "append", "(", "self", ".", "sum", "[", "i", "]", "/", "self", ".", "count", "[", "i", "]", ")", "return", "v" ]
[ 97, 4 ]
[ 103, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getmedian
(self)
Get median pixel level for each layer
Get median pixel level for each layer
def _getmedian(self): """Get median pixel level for each layer""" v = [] for i in self.bands: s = 0 half = self.count[i] // 2 b = i * 256 for j in range(256): s = s + self.h[b + j] if s > half: break v.append(j) return v
[ "def", "_getmedian", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "s", "=", "0", "half", "=", "self", ".", "count", "[", "i", "]", "//", "2", "b", "=", "i", "*", "256", "for", "j", "in", "range", "(", "256", ")", ":", "s", "=", "s", "+", "self", ".", "h", "[", "b", "+", "j", "]", "if", "s", ">", "half", ":", "break", "v", ".", "append", "(", "j", ")", "return", "v" ]
[ 105, 4 ]
[ 118, 16 ]
python
en
['en', 'da', 'en']
True
Stat._getrms
(self)
Get RMS for each layer
Get RMS for each layer
def _getrms(self): """Get RMS for each layer""" v = [] for i in self.bands: v.append(math.sqrt(self.sum2[i] / self.count[i])) return v
[ "def", "_getrms", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "v", ".", "append", "(", "math", ".", "sqrt", "(", "self", ".", "sum2", "[", "i", "]", "/", "self", ".", "count", "[", "i", "]", ")", ")", "return", "v" ]
[ 120, 4 ]
[ 126, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getvar
(self)
Get variance for each layer
Get variance for each layer
def _getvar(self): """Get variance for each layer""" v = [] for i in self.bands: n = self.count[i] v.append((self.sum2[i] - (self.sum[i] ** 2.0) / n) / n) return v
[ "def", "_getvar", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "n", "=", "self", ".", "count", "[", "i", "]", "v", ".", "append", "(", "(", "self", ".", "sum2", "[", "i", "]", "-", "(", "self", ".", "sum", "[", "i", "]", "**", "2.0", ")", "/", "n", ")", "/", "n", ")", "return", "v" ]
[ 128, 4 ]
[ 135, 16 ]
python
en
['en', 'en', 'en']
True
Stat._getstddev
(self)
Get standard deviation for each layer
Get standard deviation for each layer
def _getstddev(self): """Get standard deviation for each layer""" v = [] for i in self.bands: v.append(math.sqrt(self.var[i])) return v
[ "def", "_getstddev", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "self", ".", "bands", ":", "v", ".", "append", "(", "math", ".", "sqrt", "(", "self", ".", "var", "[", "i", "]", ")", ")", "return", "v" ]
[ 137, 4 ]
[ 143, 16 ]
python
en
['en', 'en', 'en']
True
downsample_state
(observation, image_height=84, image_width=84, image_channels=1)
Downsamples the Observations to a lower resolution. Args: observation(array): downscale_height(int): downscale_width(int): Returns: Downsampled image
Downsamples the Observations to a lower resolution. Args: observation(array): downscale_height(int): downscale_width(int):
def downsample_state(observation, image_height=84, image_width=84, image_channels=1): """Downsamples the Observations to a lower resolution. Args: observation(array): downscale_height(int): downscale_width(int): Returns: Downsampled image """ return np.resize(observation, (image_height, image_width, image_channels))
[ "def", "downsample_state", "(", "observation", ",", "image_height", "=", "84", ",", "image_width", "=", "84", ",", "image_channels", "=", "1", ")", ":", "return", "np", ".", "resize", "(", "observation", ",", "(", "image_height", ",", "image_width", ",", "image_channels", ")", ")" ]
[ 36, 0 ]
[ 46, 76 ]
python
en
['en', 'en', 'en']
True
convert_greyscale
(observation)
Converts the RGB Image to greyscale. Args: observation(array): Returns: Greyscale observation(array):
Converts the RGB Image to greyscale. Args: observation(array): Returns: Greyscale observation(array):
def convert_greyscale(observation): """Converts the RGB Image to greyscale. Args: observation(array): Returns: Greyscale observation(array): """ greyscale_image = np.dot(observation[..., :3], GREY_FILTER) greyscale_image = np.expand_dims(greyscale_image, axis=-1) return greyscale_image
[ "def", "convert_greyscale", "(", "observation", ")", ":", "greyscale_image", "=", "np", ".", "dot", "(", "observation", "[", "...", ",", ":", "3", "]", ",", "GREY_FILTER", ")", "greyscale_image", "=", "np", ".", "expand_dims", "(", "greyscale_image", ",", "axis", "=", "-", "1", ")", "return", "greyscale_image" ]
[ 49, 0 ]
[ 58, 24 ]
python
en
['en', 'en', 'en']
True
anneal_exploration
(eta, curr_step, max_step, train_step, init_val=0.99, min_eta=0.1, type="linear")
Anneals the probability of the agent to take random actions. Args: eta(float): current random value betwee 0 and 1 current_steps(int): Current number of steps taken by the agent total_steps(int): Total number of steps for the simulation Returns:
Anneals the probability of the agent to take random actions.
def anneal_exploration(eta, curr_step, max_step, train_step, init_val=0.99, min_eta=0.1, type="linear"): """ Anneals the probability of the agent to take random actions. Args: eta(float): current random value betwee 0 and 1 current_steps(int): Current number of steps taken by the agent total_steps(int): Total number of steps for the simulation Returns: """ if type == "linear" and curr_step > train_step: decay_value = ((curr_step - train_step) / float(max_step)) * ( init_val - min_eta) eta = init_val - decay_value eta = max(eta, min_eta) #TODO:(praneetdutta): Add exponential decay function return eta
[ "def", "anneal_exploration", "(", "eta", ",", "curr_step", ",", "max_step", ",", "train_step", ",", "init_val", "=", "0.99", ",", "min_eta", "=", "0.1", ",", "type", "=", "\"linear\"", ")", ":", "if", "type", "==", "\"linear\"", "and", "curr_step", ">", "train_step", ":", "decay_value", "=", "(", "(", "curr_step", "-", "train_step", ")", "/", "float", "(", "max_step", ")", ")", "*", "(", "init_val", "-", "min_eta", ")", "eta", "=", "init_val", "-", "decay_value", "eta", "=", "max", "(", "eta", ",", "min_eta", ")", "#TODO:(praneetdutta): Add exponential decay function", "return", "eta" ]
[ 61, 0 ]
[ 84, 12 ]
python
en
['en', 'en', 'en']
True
huber_loss
(Q_true, Q_estimate)
Huber loss implemented as per the original DQN paper. Args: Q_true: Ground truth Q-Value for future states Q_estimate: Predicted Q-Value Returns: tf.losses.huber_loss: Tensorflow Loss function
Huber loss implemented as per the original DQN paper.
def huber_loss(Q_true, Q_estimate): """ Huber loss implemented as per the original DQN paper. Args: Q_true: Ground truth Q-Value for future states Q_estimate: Predicted Q-Value Returns: tf.losses.huber_loss: Tensorflow Loss function """ return tf.losses.huber_loss(Q_true, Q_estimate)
[ "def", "huber_loss", "(", "Q_true", ",", "Q_estimate", ")", ":", "return", "tf", ".", "losses", ".", "huber_loss", "(", "Q_true", ",", "Q_estimate", ")" ]
[ 86, 0 ]
[ 96, 49 ]
python
en
['en', 'id', 'en']
True
hp_directory
(model_dir)
If running a hyperparam job, create subfolder name with trial ID. If not running a hyperparam job, just keep original model_dir.
If running a hyperparam job, create subfolder name with trial ID.
def hp_directory(model_dir): """If running a hyperparam job, create subfolder name with trial ID. If not running a hyperparam job, just keep original model_dir.""" trial_id = json.loads( os.environ.get('TF_CONFIG', '{}') ).get('task', {}).get('trial', '') return os.path.join(model_dir, trial_id)
[ "def", "hp_directory", "(", "model_dir", ")", ":", "trial_id", "=", "json", ".", "loads", "(", "os", ".", "environ", ".", "get", "(", "'TF_CONFIG'", ",", "'{}'", ")", ")", ".", "get", "(", "'task'", ",", "{", "}", ")", ".", "get", "(", "'trial'", ",", "''", ")", "return", "os", ".", "path", ".", "join", "(", "model_dir", ",", "trial_id", ")" ]
[ 99, 0 ]
[ 106, 42 ]
python
en
['en', 'en', 'en']
True
_eval_single_task
(task, action_tier_name, start, num_attempts)
Evalute the task on attmepts random action from tier.
Evalute the task on attmepts random action from tier.
def _eval_single_task(task, action_tier_name, start, num_attempts): """Evalute the task on attmepts random action from tier.""" task_id = task.taskId action_simulator = phyre.ActionSimulator([task], action_tier_name) actions = _get_actions(action_simulator, start, num_attempts) statuses = collections.defaultdict(int) stable_solutions, unstable_solutions = [], [] for action in actions: status = action_simulator.simulate_action(0, action, need_images=False, stable=True).status statuses[status] += 1 if status == STABLY_SOLVED: stable_solutions.append(action.tolist()) if status == UNSTABLY_SOLVED: unstable_solutions.append(action.tolist()) return dict(task_id=task_id, tier=action_tier_name, stable_solutions=stable_solutions[:MAX_SOLUTIONS_TO_KEEP], unstable_solutions=unstable_solutions[:MAX_SOLUTIONS_TO_KEEP], statuses=statuses)
[ "def", "_eval_single_task", "(", "task", ",", "action_tier_name", ",", "start", ",", "num_attempts", ")", ":", "task_id", "=", "task", ".", "taskId", "action_simulator", "=", "phyre", ".", "ActionSimulator", "(", "[", "task", "]", ",", "action_tier_name", ")", "actions", "=", "_get_actions", "(", "action_simulator", ",", "start", ",", "num_attempts", ")", "statuses", "=", "collections", ".", "defaultdict", "(", "int", ")", "stable_solutions", ",", "unstable_solutions", "=", "[", "]", ",", "[", "]", "for", "action", "in", "actions", ":", "status", "=", "action_simulator", ".", "simulate_action", "(", "0", ",", "action", ",", "need_images", "=", "False", ",", "stable", "=", "True", ")", ".", "status", "statuses", "[", "status", "]", "+=", "1", "if", "status", "==", "STABLY_SOLVED", ":", "stable_solutions", ".", "append", "(", "action", ".", "tolist", "(", ")", ")", "if", "status", "==", "UNSTABLY_SOLVED", ":", "unstable_solutions", ".", "append", "(", "action", ".", "tolist", "(", ")", ")", "return", "dict", "(", "task_id", "=", "task_id", ",", "tier", "=", "action_tier_name", ",", "stable_solutions", "=", "stable_solutions", "[", ":", "MAX_SOLUTIONS_TO_KEEP", "]", ",", "unstable_solutions", "=", "unstable_solutions", "[", ":", "MAX_SOLUTIONS_TO_KEEP", "]", ",", "statuses", "=", "statuses", ")" ]
[ 111, 0 ]
[ 132, 34 ]
python
en
['en', 'en', 'en']
True
compute_flags
(tier, status_counts)
Given status counts run statisical tests and return a list of labels.
Given status counts run statisical tests and return a list of labels.
def compute_flags(tier, status_counts): """Given status counts run statisical tests and return a list of labels.""" total_attempts = sum(status_counts.values()) valid_attempts = total_attempts - status_counts[INVALID_INPUT] stable_solution_attempts = status_counts[STABLY_SOLVED] solution_attempts = status_counts[UNSTABLY_SOLVED] + stable_solution_attempts flags = {} threshold = SOLVABILITY_THRESHOLD_PROBS[tier] for suffix, count in [('', solution_attempts), ('_stable', stable_solution_attempts)]: flags[f'good{suffix}'] = scipy.stats.binom_test( count, n=valid_attempts, p=threshold, alternative='greater') < P_VALUE flags[f'bad{suffix}'] = scipy.stats.binom_test( count, n=valid_attempts, p=2 * threshold, alternative='less') < P_VALUE if not solution_attempts: flags[f'impossible'] = True if stable_solution_attempts / max(total_attempts, 1) >= 0.1: flags['trivial'] = True return frozenset(getattr(Flags, k.upper()) for k, v in flags.items() if v)
[ "def", "compute_flags", "(", "tier", ",", "status_counts", ")", ":", "total_attempts", "=", "sum", "(", "status_counts", ".", "values", "(", ")", ")", "valid_attempts", "=", "total_attempts", "-", "status_counts", "[", "INVALID_INPUT", "]", "stable_solution_attempts", "=", "status_counts", "[", "STABLY_SOLVED", "]", "solution_attempts", "=", "status_counts", "[", "UNSTABLY_SOLVED", "]", "+", "stable_solution_attempts", "flags", "=", "{", "}", "threshold", "=", "SOLVABILITY_THRESHOLD_PROBS", "[", "tier", "]", "for", "suffix", ",", "count", "in", "[", "(", "''", ",", "solution_attempts", ")", ",", "(", "'_stable'", ",", "stable_solution_attempts", ")", "]", ":", "flags", "[", "f'good{suffix}'", "]", "=", "scipy", ".", "stats", ".", "binom_test", "(", "count", ",", "n", "=", "valid_attempts", ",", "p", "=", "threshold", ",", "alternative", "=", "'greater'", ")", "<", "P_VALUE", "flags", "[", "f'bad{suffix}'", "]", "=", "scipy", ".", "stats", ".", "binom_test", "(", "count", ",", "n", "=", "valid_attempts", ",", "p", "=", "2", "*", "threshold", ",", "alternative", "=", "'less'", ")", "<", "P_VALUE", "if", "not", "solution_attempts", ":", "flags", "[", "f'impossible'", "]", "=", "True", "if", "stable_solution_attempts", "/", "max", "(", "total_attempts", ",", "1", ")", ">=", "0.1", ":", "flags", "[", "'trivial'", "]", "=", "True", "return", "frozenset", "(", "getattr", "(", "Flags", ",", "k", ".", "upper", "(", ")", ")", "for", "k", ",", "v", "in", "flags", ".", "items", "(", ")", "if", "v", ")" ]
[ 135, 0 ]
[ 159, 78 ]
python
en
['en', 'en', 'en']
True
load_all_eval_stats
(num_workers=None, mode=LoadingMode.FULL)
Load all computed up-to-date eval stats. Args: num_workers: None or int, num workers to use for loading. If None will load in the main thread. mode: LoadingMode, defines a subset of fields to load. Returns: dict of dicts: template_id -> tasl_id -> eval_stats
Load all computed up-to-date eval stats.
def load_all_eval_stats(num_workers=None, mode=LoadingMode.FULL): """Load all computed up-to-date eval stats. Args: num_workers: None or int, num workers to use for loading. If None will load in the main thread. mode: LoadingMode, defines a subset of fields to load. Returns: dict of dicts: template_id -> tasl_id -> eval_stats """ known_template_ids = [ x.split('.')[0] for x in os.listdir(str(phyre.settings.TASK_EVAL_DIR)) if x.endswith('.json') ] local_maybe_load_evaluation = functools.partial(maybe_load_evaluation, mode=mode) if num_workers is None: eval_stats = {} for template_id in known_template_ids: eval_stats[template_id] = local_maybe_load_evaluation(template_id) else: num_workers = num_workers if num_workers > 0 else None with multiprocessing.Pool(num_workers) as pool: eval_stats = pool.map(local_maybe_load_evaluation, known_template_ids) eval_stats = dict(zip(known_template_ids, eval_stats)) eval_stats = {k: v for k, v in eval_stats.items() if v is not None} return eval_stats
[ "def", "load_all_eval_stats", "(", "num_workers", "=", "None", ",", "mode", "=", "LoadingMode", ".", "FULL", ")", ":", "known_template_ids", "=", "[", "x", ".", "split", "(", "'.'", ")", "[", "0", "]", "for", "x", "in", "os", ".", "listdir", "(", "str", "(", "phyre", ".", "settings", ".", "TASK_EVAL_DIR", ")", ")", "if", "x", ".", "endswith", "(", "'.json'", ")", "]", "local_maybe_load_evaluation", "=", "functools", ".", "partial", "(", "maybe_load_evaluation", ",", "mode", "=", "mode", ")", "if", "num_workers", "is", "None", ":", "eval_stats", "=", "{", "}", "for", "template_id", "in", "known_template_ids", ":", "eval_stats", "[", "template_id", "]", "=", "local_maybe_load_evaluation", "(", "template_id", ")", "else", ":", "num_workers", "=", "num_workers", "if", "num_workers", ">", "0", "else", "None", "with", "multiprocessing", ".", "Pool", "(", "num_workers", ")", "as", "pool", ":", "eval_stats", "=", "pool", ".", "map", "(", "local_maybe_load_evaluation", ",", "known_template_ids", ")", "eval_stats", "=", "dict", "(", "zip", "(", "known_template_ids", ",", "eval_stats", ")", ")", "eval_stats", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "eval_stats", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "return", "eval_stats" ]
[ 328, 0 ]
[ 359, 21 ]
python
en
['en', 'en', 'pt']
True
maybe_load_evaluation
(template_id, mode=LoadingMode.FULL)
Loads evaluation file if up-to-date.
Loads evaluation file if up-to-date.
def maybe_load_evaluation(template_id, mode=LoadingMode.FULL): """Loads evaluation file if up-to-date.""" task_path = str(phyre.settings.TASK_SCRIPTS_DIR / f'task{template_id}.py') if not os.path.exists(task_path): logging.warning('Rogue eval file for %s', template_id) return None if does_evaluation_need_update(task_path): return None with open(get_evaluation_meta_path(task_path)) as stream: eval_data = json.load(stream) eval_data.update(joblib.load(get_evaluation_path(task_path))) if mode == LoadingMode.FULL: solution_power = joblib.load( phyre.compute_solution_power.get_solution_power_path(task_path)) else: solution_power = None if mode == LoadingMode.FULL: needed_stats = STATS elif mode == LoadingMode.FIRST_SOLUTION_ONLY: needed_stats = ('solutions',) else: raise ValueError('Unknown loading mode: %s' % mode) final_eval_data = { stat: {tier: {} for tier in phyre.action_mappers.ACTION_MAPPERS } for stat in STATS } for task, per_task_stats in eval_data['eval_stats'].items(): for tier, per_tier_stats in per_task_stats.items(): for stat_name, value in _clean_stats(per_tier_stats, tier).items(): final_eval_data[stat_name][tier][task] = value if solution_power is not None: for tier in phyre.action_mappers.ACTION_MAPPERS: final_eval_data['solution_power'][tier][ 'task_ids'] = solution_power['task_ids'] final_eval_data['solution_power'][tier][ 'actions_on_tasks'] = solution_power[f'{tier}_actions_on_tasks'] final_eval_data = {k: final_eval_data[k] for k in needed_stats} if mode == LoadingMode.FIRST_SOLUTION_ONLY: for per_task_solution_list in final_eval_data['solutions'].values(): for solution_list in per_task_solution_list.values(): solution_list[:] = solution_list[:1] return final_eval_data
[ "def", "maybe_load_evaluation", "(", "template_id", ",", "mode", "=", "LoadingMode", ".", "FULL", ")", ":", "task_path", "=", "str", "(", "phyre", ".", "settings", ".", "TASK_SCRIPTS_DIR", "/", "f'task{template_id}.py'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "task_path", ")", ":", "logging", ".", "warning", "(", "'Rogue eval file for %s'", ",", "template_id", ")", "return", "None", "if", "does_evaluation_need_update", "(", "task_path", ")", ":", "return", "None", "with", "open", "(", "get_evaluation_meta_path", "(", "task_path", ")", ")", "as", "stream", ":", "eval_data", "=", "json", ".", "load", "(", "stream", ")", "eval_data", ".", "update", "(", "joblib", ".", "load", "(", "get_evaluation_path", "(", "task_path", ")", ")", ")", "if", "mode", "==", "LoadingMode", ".", "FULL", ":", "solution_power", "=", "joblib", ".", "load", "(", "phyre", ".", "compute_solution_power", ".", "get_solution_power_path", "(", "task_path", ")", ")", "else", ":", "solution_power", "=", "None", "if", "mode", "==", "LoadingMode", ".", "FULL", ":", "needed_stats", "=", "STATS", "elif", "mode", "==", "LoadingMode", ".", "FIRST_SOLUTION_ONLY", ":", "needed_stats", "=", "(", "'solutions'", ",", ")", "else", ":", "raise", "ValueError", "(", "'Unknown loading mode: %s'", "%", "mode", ")", "final_eval_data", "=", "{", "stat", ":", "{", "tier", ":", "{", "}", "for", "tier", "in", "phyre", ".", "action_mappers", ".", "ACTION_MAPPERS", "}", "for", "stat", "in", "STATS", "}", "for", "task", ",", "per_task_stats", "in", "eval_data", "[", "'eval_stats'", "]", ".", "items", "(", ")", ":", "for", "tier", ",", "per_tier_stats", "in", "per_task_stats", ".", "items", "(", ")", ":", "for", "stat_name", ",", "value", "in", "_clean_stats", "(", "per_tier_stats", ",", "tier", ")", ".", "items", "(", ")", ":", "final_eval_data", "[", "stat_name", "]", "[", "tier", "]", "[", "task", "]", "=", "value", "if", "solution_power", "is", "not", "None", ":", "for", "tier", "in", "phyre", ".", "action_mappers", ".", "ACTION_MAPPERS", ":", "final_eval_data", "[", "'solution_power'", "]", "[", "tier", "]", "[", "'task_ids'", "]", "=", "solution_power", "[", "'task_ids'", "]", "final_eval_data", "[", "'solution_power'", "]", "[", "tier", "]", "[", "'actions_on_tasks'", "]", "=", "solution_power", "[", "f'{tier}_actions_on_tasks'", "]", "final_eval_data", "=", "{", "k", ":", "final_eval_data", "[", "k", "]", "for", "k", "in", "needed_stats", "}", "if", "mode", "==", "LoadingMode", ".", "FIRST_SOLUTION_ONLY", ":", "for", "per_task_solution_list", "in", "final_eval_data", "[", "'solutions'", "]", ".", "values", "(", ")", ":", "for", "solution_list", "in", "per_task_solution_list", ".", "values", "(", ")", ":", "solution_list", "[", ":", "]", "=", "solution_list", "[", ":", "1", "]", "return", "final_eval_data" ]
[ 376, 0 ]
[ 419, 26 ]
python
en
['es', 'en', 'en']
True
sig_handler
(signum, frame)
USR1 signal handler that requeues the job.
USR1 signal handler that requeues the job.
def sig_handler(signum, frame): """USR1 signal handler that requeues the job.""" del frame # Unused. logging.warning('Signal handler called with signal %s', signum) prod_id = int(os.environ['SLURM_PROCID']) if 'SLURM_ARRAY_JOB_ID' in os.environ: job_id = '%s_%s' % (os.environ['SLURM_ARRAY_JOB_ID'], os.environ['SLURM_ARRAY_TASK_ID']) else: job_id = os.environ['SLURM_JOB_ID'] if prod_id == 0: logging.warning('Requeuing job %s', job_id) os.system('scontrol requeue %s' % job_id) else: logging.warning('Not the master process, no need to requeue.') sys.exit(-1)
[ "def", "sig_handler", "(", "signum", ",", "frame", ")", ":", "del", "frame", "# Unused.", "logging", ".", "warning", "(", "'Signal handler called with signal %s'", ",", "signum", ")", "prod_id", "=", "int", "(", "os", ".", "environ", "[", "'SLURM_PROCID'", "]", ")", "if", "'SLURM_ARRAY_JOB_ID'", "in", "os", ".", "environ", ":", "job_id", "=", "'%s_%s'", "%", "(", "os", ".", "environ", "[", "'SLURM_ARRAY_JOB_ID'", "]", ",", "os", ".", "environ", "[", "'SLURM_ARRAY_TASK_ID'", "]", ")", "else", ":", "job_id", "=", "os", ".", "environ", "[", "'SLURM_JOB_ID'", "]", "if", "prod_id", "==", "0", ":", "logging", ".", "warning", "(", "'Requeuing job %s'", ",", "job_id", ")", "os", ".", "system", "(", "'scontrol requeue %s'", "%", "job_id", ")", "else", ":", "logging", ".", "warning", "(", "'Not the master process, no need to requeue.'", ")", "sys", ".", "exit", "(", "-", "1", ")" ]
[ 497, 0 ]
[ 512, 16 ]
python
en
['en', 'ca', 'en']
True
term_handler
(signum, frame)
Dummy TERM signal handler that does nothing.
Dummy TERM signal handler that does nothing.
def term_handler(signum, frame): """Dummy TERM signal handler that does nothing.""" del frame # Unused. logging.warning('Signal handler called with signal %s', signum) logging.warning('Bypassing SIGTERM.')
[ "def", "term_handler", "(", "signum", ",", "frame", ")", ":", "del", "frame", "# Unused.", "logging", ".", "warning", "(", "'Signal handler called with signal %s'", ",", "signum", ")", "logging", ".", "warning", "(", "'Bypassing SIGTERM.'", ")" ]
[ 515, 0 ]
[ 519, 41 ]
python
en
['en', 'en', 'en']
True
init_signal_handler
()
Handle signals sent by SLURM for time limit / pre-emption.
Handle signals sent by SLURM for time limit / pre-emption.
def init_signal_handler(): """Handle signals sent by SLURM for time limit / pre-emption.""" signal.signal(signal.SIGUSR1, sig_handler) signal.signal(signal.SIGTERM, term_handler) logging.warning('Signal handler installed.')
[ "def", "init_signal_handler", "(", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGUSR1", ",", "sig_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "term_handler", ")", "logging", ".", "warning", "(", "'Signal handler installed.'", ")" ]
[ 522, 0 ]
[ 526, 48 ]
python
en
['en', 'fr', 'en']
True
TaskEvaller.step
(self)
Schedule a chunk of evaluation jobs.
Schedule a chunk of evaluation jobs.
def step(self): """Schedule a chunk of evaluation jobs.""" done_simulations_per_task_tier = {} for key, stats in self._state['stats_per_task_tier'].items(): if key in self._state['done_task_tier']: continue counts = sum(stats['status_counts'].values()) done_simulations_per_task_tier[key] = counts num_unresolved_task_tier_pairs = len(done_simulations_per_task_tier) if self.reject_ball_solvable: # First compute stats for ball tier. ball_only = { k: v for k, v in done_simulations_per_task_tier.items() if k[1] == 'ball' } if ball_only: done_simulations_per_task_tier = ball_only simluation_tasks = [] for key in itertools.cycle(list(done_simulations_per_task_tier)): start = done_simulations_per_task_tier[key] done_simulations_per_task_tier[key] += self.simulate_worker_size task_id, tier = key simluation_tasks.append((self._task_id_to_tasks[task_id], tier, start, self.simulate_worker_size)) if len(simluation_tasks) >= self.warp_size: break logging.info( 'Starting simulation chunk with %d items. Total unresolved tasks:' ' %s. Simulations_done: %d', len(simluation_tasks), num_unresolved_task_tier_pairs, sum( sum(x['status_counts'].values()) for x in self._state['stats_per_task_tier'].values())) for result in self._pool.imap(_worker, simluation_tasks): key = (result['task_id'], result['tier']) if key in self._state['done_task_tier']: # We scheduled a simulation task, but already got enough data. # So just ignoring this bit to be agnostic of warp_size. continue # Note, we may "overshoot" here: update stats that are already complete. stats = self._state['stats_per_task_tier'][key] for status, count in result['statuses'].items(): stats['status_counts'][status] += count stats['solutions'].extend(result['stable_solutions']) del stats['solutions'][MAX_SOLUTIONS_TO_KEEP:] stats['unstable_solutions'].extend(result['unstable_solutions']) del stats['unstable_solutions'][MAX_SOLUTIONS_TO_KEEP:] self._update_done_stats(*key) return self.done()
[ "def", "step", "(", "self", ")", ":", "done_simulations_per_task_tier", "=", "{", "}", "for", "key", ",", "stats", "in", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", ".", "items", "(", ")", ":", "if", "key", "in", "self", ".", "_state", "[", "'done_task_tier'", "]", ":", "continue", "counts", "=", "sum", "(", "stats", "[", "'status_counts'", "]", ".", "values", "(", ")", ")", "done_simulations_per_task_tier", "[", "key", "]", "=", "counts", "num_unresolved_task_tier_pairs", "=", "len", "(", "done_simulations_per_task_tier", ")", "if", "self", ".", "reject_ball_solvable", ":", "# First compute stats for ball tier.", "ball_only", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "done_simulations_per_task_tier", ".", "items", "(", ")", "if", "k", "[", "1", "]", "==", "'ball'", "}", "if", "ball_only", ":", "done_simulations_per_task_tier", "=", "ball_only", "simluation_tasks", "=", "[", "]", "for", "key", "in", "itertools", ".", "cycle", "(", "list", "(", "done_simulations_per_task_tier", ")", ")", ":", "start", "=", "done_simulations_per_task_tier", "[", "key", "]", "done_simulations_per_task_tier", "[", "key", "]", "+=", "self", ".", "simulate_worker_size", "task_id", ",", "tier", "=", "key", "simluation_tasks", ".", "append", "(", "(", "self", ".", "_task_id_to_tasks", "[", "task_id", "]", ",", "tier", ",", "start", ",", "self", ".", "simulate_worker_size", ")", ")", "if", "len", "(", "simluation_tasks", ")", ">=", "self", ".", "warp_size", ":", "break", "logging", ".", "info", "(", "'Starting simulation chunk with %d items. Total unresolved tasks:'", "' %s. Simulations_done: %d'", ",", "len", "(", "simluation_tasks", ")", ",", "num_unresolved_task_tier_pairs", ",", "sum", "(", "sum", "(", "x", "[", "'status_counts'", "]", ".", "values", "(", ")", ")", "for", "x", "in", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", ".", "values", "(", ")", ")", ")", "for", "result", "in", "self", ".", "_pool", ".", "imap", "(", "_worker", ",", "simluation_tasks", ")", ":", "key", "=", "(", "result", "[", "'task_id'", "]", ",", "result", "[", "'tier'", "]", ")", "if", "key", "in", "self", ".", "_state", "[", "'done_task_tier'", "]", ":", "# We scheduled a simulation task, but already got enough data.", "# So just ignoring this bit to be agnostic of warp_size.", "continue", "# Note, we may \"overshoot\" here: update stats that are already complete.", "stats", "=", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", "[", "key", "]", "for", "status", ",", "count", "in", "result", "[", "'statuses'", "]", ".", "items", "(", ")", ":", "stats", "[", "'status_counts'", "]", "[", "status", "]", "+=", "count", "stats", "[", "'solutions'", "]", ".", "extend", "(", "result", "[", "'stable_solutions'", "]", ")", "del", "stats", "[", "'solutions'", "]", "[", "MAX_SOLUTIONS_TO_KEEP", ":", "]", "stats", "[", "'unstable_solutions'", "]", ".", "extend", "(", "result", "[", "'unstable_solutions'", "]", ")", "del", "stats", "[", "'unstable_solutions'", "]", "[", "MAX_SOLUTIONS_TO_KEEP", ":", "]", "self", ".", "_update_done_stats", "(", "*", "key", ")", "return", "self", ".", "done", "(", ")" ]
[ 202, 4 ]
[ 254, 26 ]
python
en
['en', 'en', 'en']
True
TaskEvaller._update_done_stats
(self, task_id, action_tier)
Update a set of "done" tasks after new data for task_id and action_tier.
Update a set of "done" tasks after new data for task_id and action_tier.
def _update_done_stats(self, task_id, action_tier): """Update a set of "done" tasks after new data for task_id and action_tier.""" key = (task_id, action_tier) status_counts = self._state['stats_per_task_tier'][key]['status_counts'] valid_attempts = sum( status_counts.values()) - status_counts[INVALID_INPUT] if valid_attempts < self.min_valid_attempts: return flags = compute_flags(action_tier, status_counts) if not ({Flags.GOOD, Flags.BAD} & flags): return if not ({Flags.GOOD_STABLE, Flags.BAD_STABLE} & flags): return num_solved = status_counts[UNSTABLY_SOLVED] + status_counts[ STABLY_SOLVED] if Flags.GOOD in flags and num_solved < MIN_SOLUTIONS: return if (Flags.GOOD_STABLE in flags and status_counts[STABLY_SOLVED] < MIN_SOLUTIONS): return self._state['done_task_tier'].add(key) logging.info('Done simulation for %s. Stats: %s. Flags: %s', key, status_counts, flags) # If reject_ball_solvable, add task ids for ball solved task to # done_task_tiers_reasons. solved_by_ball = (action_tier == 'ball' and Flags.GOOD_STABLE in flags) if self.reject_ball_solvable and solved_by_ball: for tier in phyre.action_mappers.ACTION_MAPPERS: tier_key = (task_id, tier) if tier_key in self._state['done_task_tier']: continue logging.info( 'Removing %s. Solved by ball and reject_ball_solvable is' ' True', tier_key) self._state['done_task_tier'].add(tier_key)
[ "def", "_update_done_stats", "(", "self", ",", "task_id", ",", "action_tier", ")", ":", "key", "=", "(", "task_id", ",", "action_tier", ")", "status_counts", "=", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", "[", "key", "]", "[", "'status_counts'", "]", "valid_attempts", "=", "sum", "(", "status_counts", ".", "values", "(", ")", ")", "-", "status_counts", "[", "INVALID_INPUT", "]", "if", "valid_attempts", "<", "self", ".", "min_valid_attempts", ":", "return", "flags", "=", "compute_flags", "(", "action_tier", ",", "status_counts", ")", "if", "not", "(", "{", "Flags", ".", "GOOD", ",", "Flags", ".", "BAD", "}", "&", "flags", ")", ":", "return", "if", "not", "(", "{", "Flags", ".", "GOOD_STABLE", ",", "Flags", ".", "BAD_STABLE", "}", "&", "flags", ")", ":", "return", "num_solved", "=", "status_counts", "[", "UNSTABLY_SOLVED", "]", "+", "status_counts", "[", "STABLY_SOLVED", "]", "if", "Flags", ".", "GOOD", "in", "flags", "and", "num_solved", "<", "MIN_SOLUTIONS", ":", "return", "if", "(", "Flags", ".", "GOOD_STABLE", "in", "flags", "and", "status_counts", "[", "STABLY_SOLVED", "]", "<", "MIN_SOLUTIONS", ")", ":", "return", "self", ".", "_state", "[", "'done_task_tier'", "]", ".", "add", "(", "key", ")", "logging", ".", "info", "(", "'Done simulation for %s. Stats: %s. Flags: %s'", ",", "key", ",", "status_counts", ",", "flags", ")", "# If reject_ball_solvable, add task ids for ball solved task to", "# done_task_tiers_reasons.", "solved_by_ball", "=", "(", "action_tier", "==", "'ball'", "and", "Flags", ".", "GOOD_STABLE", "in", "flags", ")", "if", "self", ".", "reject_ball_solvable", "and", "solved_by_ball", ":", "for", "tier", "in", "phyre", ".", "action_mappers", ".", "ACTION_MAPPERS", ":", "tier_key", "=", "(", "task_id", ",", "tier", ")", "if", "tier_key", "in", "self", ".", "_state", "[", "'done_task_tier'", "]", ":", "continue", "logging", ".", "info", "(", "'Removing %s. Solved by ball and reject_ball_solvable is'", "' True'", ",", "tier_key", ")", "self", ".", "_state", "[", "'done_task_tier'", "]", ".", "add", "(", "tier_key", ")" ]
[ 256, 4 ]
[ 296, 59 ]
python
en
['en', 'en', 'en']
True
TaskEvaller.done
(self)
Checks whether evaluation for all jobs is done.
Checks whether evaluation for all jobs is done.
def done(self): """Checks whether evaluation for all jobs is done.""" return len(self._state['done_task_tier']) == len( self._state['stats_per_task_tier'])
[ "def", "done", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_state", "[", "'done_task_tier'", "]", ")", "==", "len", "(", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", ")" ]
[ 298, 4 ]
[ 301, 47 ]
python
en
['en', 'en', 'en']
True
TaskEvaller.result
(self)
Returns evaluation results.
Returns evaluation results.
def result(self): """Returns evaluation results.""" assert self.done() return self._state['stats_per_task_tier']
[ "def", "result", "(", "self", ")", ":", "assert", "self", ".", "done", "(", ")", "return", "self", ".", "_state", "[", "'stats_per_task_tier'", "]" ]
[ 303, 4 ]
[ 306, 49 ]
python
en
['es', 'en', 'en']
True
TaskEvaller.maybe_load
(self, checkpoint_path)
If checkpoint is provided will load evaluation state.
If checkpoint is provided will load evaluation state.
def maybe_load(self, checkpoint_path): """If checkpoint is provided will load evaluation state.""" if checkpoint_path is not None and os.path.exists(checkpoint_path): logging.info('Loading %s', checkpoint_path) with open(checkpoint_path, 'rb') as stream: self._state = pickle.load(stream) # Re-compute done_task_tier. self._state['done_task_tier'] = set() for key in self._state['stats_per_task_tier']: self._update_done_stats(*key)
[ "def", "maybe_load", "(", "self", ",", "checkpoint_path", ")", ":", "if", "checkpoint_path", "is", "not", "None", "and", "os", ".", "path", ".", "exists", "(", "checkpoint_path", ")", ":", "logging", ".", "info", "(", "'Loading %s'", ",", "checkpoint_path", ")", "with", "open", "(", "checkpoint_path", ",", "'rb'", ")", "as", "stream", ":", "self", ".", "_state", "=", "pickle", ".", "load", "(", "stream", ")", "# Re-compute done_task_tier.", "self", ".", "_state", "[", "'done_task_tier'", "]", "=", "set", "(", ")", "for", "key", "in", "self", ".", "_state", "[", "'stats_per_task_tier'", "]", ":", "self", ".", "_update_done_stats", "(", "*", "key", ")" ]
[ 308, 4 ]
[ 317, 45 ]
python
en
['en', 'en', 'en']
True
TaskEvaller.maybe_save
(self, checkpoint_path)
If checkpoint is provided will save evaluation state.
If checkpoint is provided will save evaluation state.
def maybe_save(self, checkpoint_path): """If checkpoint is provided will save evaluation state.""" if checkpoint_path is not None: tmp_path = checkpoint_path + '.tmp' with open(tmp_path, 'wb') as stream: pickle.dump(self._state, stream) os.rename(tmp_path, checkpoint_path)
[ "def", "maybe_save", "(", "self", ",", "checkpoint_path", ")", ":", "if", "checkpoint_path", "is", "not", "None", ":", "tmp_path", "=", "checkpoint_path", "+", "'.tmp'", "with", "open", "(", "tmp_path", ",", "'wb'", ")", "as", "stream", ":", "pickle", ".", "dump", "(", "self", ".", "_state", ",", "stream", ")", "os", ".", "rename", "(", "tmp_path", ",", "checkpoint_path", ")" ]
[ 319, 4 ]
[ 325, 48 ]
python
en
['en', 'en', 'en']
True
run_flow
(flow, storage, flags=None, http=None)
Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. The tools module defines an ``ArgumentParser`` the already contains the flag definitions that ``run()`` requires. You can pass that ``ArgumentParser`` to your ``ArgumentParser`` constructor:: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. flags: ``argparse.Namespace``, (Optional) The command-line flags. This is the object returned from calling ``parse_args()`` on ``argparse.ArgumentParser`` as described above. Defaults to ``argparser.parse_args()``. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential.
Core code for a command-line application.
def run_flow(flow, storage, flags=None, http=None): """Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. The tools module defines an ``ArgumentParser`` the already contains the flag definitions that ``run()`` requires. You can pass that ``ArgumentParser`` to your ``ArgumentParser`` constructor:: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. flags: ``argparse.Namespace``, (Optional) The command-line flags. This is the object returned from calling ``parse_args()`` on ``argparse.ArgumentParser`` as described above. Defaults to ``argparser.parse_args()``. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential. """ if flags is None: flags = argparser.parse_args() logging.getLogger().setLevel(getattr(logging, flags.logging_level)) if not flags.noauth_local_webserver: success = False port_number = 0 for port in flags.auth_host_port: port_number = port try: httpd = ClientRedirectServer((flags.auth_host_name, port), ClientRedirectHandler) except socket.error: pass else: success = True break flags.noauth_local_webserver = not success if not success: print(_FAILED_START_MESSAGE) if not flags.noauth_local_webserver: oauth_callback = 'http://{host}:{port}/'.format( host=flags.auth_host_name, port=port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if not flags.noauth_local_webserver: import webbrowser webbrowser.open(authorize_url, new=1, autoraise=True) print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url)) else: print(_GO_TO_LINK_MESSAGE.format(address=authorize_url)) code = None if not flags.noauth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print('Failed to find "code" in the query parameters ' 'of the redirect.') sys.exit('Try running with --noauth_local_webserver.') else: code = input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: sys.exit('Authentication has failed: {0}'.format(e)) storage.put(credential) credential.set_store(storage) print('Authentication successful.') return credential
[ "def", "run_flow", "(", "flow", ",", "storage", ",", "flags", "=", "None", ",", "http", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "argparser", ".", "parse_args", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "getattr", "(", "logging", ",", "flags", ".", "logging_level", ")", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "success", "=", "False", "port_number", "=", "0", "for", "port", "in", "flags", ".", "auth_host_port", ":", "port_number", "=", "port", "try", ":", "httpd", "=", "ClientRedirectServer", "(", "(", "flags", ".", "auth_host_name", ",", "port", ")", ",", "ClientRedirectHandler", ")", "except", "socket", ".", "error", ":", "pass", "else", ":", "success", "=", "True", "break", "flags", ".", "noauth_local_webserver", "=", "not", "success", "if", "not", "success", ":", "print", "(", "_FAILED_START_MESSAGE", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "oauth_callback", "=", "'http://{host}:{port}/'", ".", "format", "(", "host", "=", "flags", ".", "auth_host_name", ",", "port", "=", "port_number", ")", "else", ":", "oauth_callback", "=", "client", ".", "OOB_CALLBACK_URN", "flow", ".", "redirect_uri", "=", "oauth_callback", "authorize_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "import", "webbrowser", "webbrowser", ".", "open", "(", "authorize_url", ",", "new", "=", "1", ",", "autoraise", "=", "True", ")", "print", "(", "_BROWSER_OPENED_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "else", ":", "print", "(", "_GO_TO_LINK_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "code", "=", "None", "if", "not", "flags", ".", "noauth_local_webserver", ":", "httpd", ".", "handle_request", "(", ")", "if", "'error'", "in", "httpd", ".", "query_params", ":", "sys", ".", "exit", "(", "'Authentication request was rejected.'", ")", "if", "'code'", "in", "httpd", ".", "query_params", ":", "code", "=", "httpd", ".", "query_params", "[", "'code'", "]", "else", ":", "print", "(", "'Failed to find \"code\" in the query parameters '", "'of the redirect.'", ")", "sys", ".", "exit", "(", "'Try running with --noauth_local_webserver.'", ")", "else", ":", "code", "=", "input", "(", "'Enter verification code: '", ")", ".", "strip", "(", ")", "try", ":", "credential", "=", "flow", ".", "step2_exchange", "(", "code", ",", "http", "=", "http", ")", "except", "client", ".", "FlowExchangeError", "as", "e", ":", "sys", ".", "exit", "(", "'Authentication has failed: {0}'", ".", "format", "(", "e", ")", ")", "storage", ".", "put", "(", "credential", ")", "credential", ".", "set_store", "(", "storage", ")", "print", "(", "'Authentication successful.'", ")", "return", "credential" ]
[ 141, 0 ]
[ 250, 21 ]
python
en
['en', 'en', 'en']
True
message_if_missing
(filename)
Helpful message to display if the CLIENT_SECRETS file is missing.
Helpful message to display if the CLIENT_SECRETS file is missing.
def message_if_missing(filename): """Helpful message to display if the CLIENT_SECRETS file is missing.""" return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)
[ "def", "message_if_missing", "(", "filename", ")", ":", "return", "_CLIENT_SECRETS_MESSAGE", ".", "format", "(", "file_path", "=", "filename", ")" ]
[ 253, 0 ]
[ 255, 61 ]
python
en
['en', 'en', 'en']
True
ClientRedirectHandler.do_GET
(self)
Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred.
Handle a GET request.
def do_GET(self): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ self.send_response(http_client.OK) self.send_header('Content-type', 'text/html') self.end_headers() parts = urllib.parse.urlparse(self.path) query = _helpers.parse_unique_urlencoded(parts.query) self.server.query_params = query self.wfile.write( b'<html><head><title>Authentication Status</title></head>') self.wfile.write( b'<body><p>The authentication flow has completed.</p>') self.wfile.write(b'</body></html>')
[ "def", "do_GET", "(", "self", ")", ":", "self", ".", "send_response", "(", "http_client", ".", "OK", ")", "self", ".", "send_header", "(", "'Content-type'", ",", "'text/html'", ")", "self", ".", "end_headers", "(", ")", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "self", ".", "path", ")", "query", "=", "_helpers", ".", "parse_unique_urlencoded", "(", "parts", ".", "query", ")", "self", ".", "server", ".", "query_params", "=", "query", "self", ".", "wfile", ".", "write", "(", "b'<html><head><title>Authentication Status</title></head>'", ")", "self", ".", "wfile", ".", "write", "(", "b'<body><p>The authentication flow has completed.</p>'", ")", "self", ".", "wfile", ".", "write", "(", "b'</body></html>'", ")" ]
[ 117, 4 ]
[ 134, 43 ]
python
en
['en', 'en', 'en']
True
ClientRedirectHandler.log_message
(self, format, *args)
Do not log messages to stdout while running as cmd. line program.
Do not log messages to stdout while running as cmd. line program.
def log_message(self, format, *args): """Do not log messages to stdout while running as cmd. line program."""
[ "def", "log_message", "(", "self", ",", "format", ",", "*", "args", ")", ":" ]
[ 136, 4 ]
[ 137, 79 ]
python
en
['en', 'en', 'en']
True
make_link_node
(rawtext, app, type, slug, options)
Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func.
Create a link to a github resource.
def make_link_node(rawtext, app, type, slug, options): """Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func. """ try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) ref = base + type + '/' + slug + '/' set_classes(options) prefix = "#" if type == 'pull': prefix = "PR " + prefix node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, **options) return node
[ "def", "make_link_node", "(", "rawtext", ",", "app", ",", "type", ",", "slug", ",", "options", ")", ":", "try", ":", "base", "=", "app", ".", "config", ".", "github_project_url", "if", "not", "base", ":", "raise", "AttributeError", "if", "not", "base", ".", "endswith", "(", "'/'", ")", ":", "base", "+=", "'/'", "except", "AttributeError", "as", "err", ":", "raise", "ValueError", "(", "'github_project_url configuration value is not set (%s)'", "%", "str", "(", "err", ")", ")", "ref", "=", "base", "+", "type", "+", "'/'", "+", "slug", "+", "'/'", "set_classes", "(", "options", ")", "prefix", "=", "\"#\"", "if", "type", "==", "'pull'", ":", "prefix", "=", "\"PR \"", "+", "prefix", "node", "=", "nodes", ".", "reference", "(", "rawtext", ",", "prefix", "+", "utils", ".", "unescape", "(", "slug", ")", ",", "refuri", "=", "ref", ",", "*", "*", "options", ")", "return", "node" ]
[ 22, 0 ]
[ 48, 15 ]
python
en
['en', 'en', 'en']
True
ghissue_role
(name, rawtext, text, lineno, inliner, options={}, content=[])
Link to a GitHub issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization.
Link to a GitHub issue.
def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] app = inliner.document.settings.env.app #app.info('issue %r' % text) if 'pull' in name.lower(): category = 'pull' elif 'issue' in name.lower(): category = 'issues' else: msg = inliner.reporter.error( 'GitHub roles include "ghpull" and "ghissue", ' '"%s" is invalid.' % name, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = make_link_node(rawtext, app, category, str(issue_num), options) return [node], []
[ "def", "ghissue_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "try", ":", "issue_num", "=", "int", "(", "text", ")", "if", "issue_num", "<=", "0", ":", "raise", "ValueError", "except", "ValueError", ":", "msg", "=", "inliner", ".", "reporter", ".", "error", "(", "'GitHub issue number must be a number greater than or equal to 1; '", "'\"%s\" is invalid.'", "%", "text", ",", "line", "=", "lineno", ")", "prb", "=", "inliner", ".", "problematic", "(", "rawtext", ",", "rawtext", ",", "msg", ")", "return", "[", "prb", "]", ",", "[", "msg", "]", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "#app.info('issue %r' % text)", "if", "'pull'", "in", "name", ".", "lower", "(", ")", ":", "category", "=", "'pull'", "elif", "'issue'", "in", "name", ".", "lower", "(", ")", ":", "category", "=", "'issues'", "else", ":", "msg", "=", "inliner", ".", "reporter", ".", "error", "(", "'GitHub roles include \"ghpull\" and \"ghissue\", '", "'\"%s\" is invalid.'", "%", "name", ",", "line", "=", "lineno", ")", "prb", "=", "inliner", ".", "problematic", "(", "rawtext", ",", "rawtext", ",", "msg", ")", "return", "[", "prb", "]", ",", "[", "msg", "]", "node", "=", "make_link_node", "(", "rawtext", ",", "app", ",", "category", ",", "str", "(", "issue_num", ")", ",", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
[ 50, 0 ]
[ 89, 21 ]
python
en
['en', 'en', 'en']
True
ghuser_role
(name, rawtext, text, lineno, inliner, options={}, content=[])
Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization.
Link to a GitHub user.
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ app = inliner.document.settings.env.app #app.info('user link %r' % text) ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], []
[ "def", "ghuser_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "#app.info('user link %r' % text)", "ref", "=", "'https://www.github.com/'", "+", "text", "node", "=", "nodes", ".", "reference", "(", "rawtext", ",", "text", ",", "refuri", "=", "ref", ",", "*", "*", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
[ 91, 0 ]
[ 110, 21 ]
python
en
['en', 'ceb', 'en']
True
ghcommit_role
(name, rawtext, text, lineno, inliner, options={}, content=[])
Link to a GitHub commit. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization.
Link to a GitHub commit.
def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub commit. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ app = inliner.document.settings.env.app #app.info('user link %r' % text) try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) ref = base + text node = nodes.reference(rawtext, text[:6], refuri=ref, **options) return [node], []
[ "def", "ghcommit_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "#app.info('user link %r' % text)", "try", ":", "base", "=", "app", ".", "config", ".", "github_project_url", "if", "not", "base", ":", "raise", "AttributeError", "if", "not", "base", ".", "endswith", "(", "'/'", ")", ":", "base", "+=", "'/'", "except", "AttributeError", "as", "err", ":", "raise", "ValueError", "(", "'github_project_url configuration value is not set (%s)'", "%", "str", "(", "err", ")", ")", "ref", "=", "base", "+", "text", "node", "=", "nodes", ".", "reference", "(", "rawtext", ",", "text", "[", ":", "6", "]", ",", "refuri", "=", "ref", ",", "*", "*", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
[ 112, 0 ]
[ 140, 21 ]
python
en
['en', 'en', 'pt']
True
setup
(app)
Install the plugin. :param app: Sphinx application context.
Install the plugin. :param app: Sphinx application context.
def setup(app): """Install the plugin. :param app: Sphinx application context. """ app.info('Initializing GitHub plugin') app.add_role('ghissue', ghissue_role) app.add_role('ghpull', ghissue_role) app.add_role('ghuser', ghuser_role) app.add_role('ghcommit', ghcommit_role) app.add_config_value('github_project_url', None, 'env') return
[ "def", "setup", "(", "app", ")", ":", "app", ".", "info", "(", "'Initializing GitHub plugin'", ")", "app", ".", "add_role", "(", "'ghissue'", ",", "ghissue_role", ")", "app", ".", "add_role", "(", "'ghpull'", ",", "ghissue_role", ")", "app", ".", "add_role", "(", "'ghuser'", ",", "ghuser_role", ")", "app", ".", "add_role", "(", "'ghcommit'", ",", "ghcommit_role", ")", "app", ".", "add_config_value", "(", "'github_project_url'", ",", "None", ",", "'env'", ")", "return" ]
[ 143, 0 ]
[ 154, 10 ]
python
en
['en', 'zh', 'en']
True
ScanningLoader.loadTestsFromModule
(self, module, pattern=None)
Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests.
Return a suite of all tests cases contained in the given module
def loadTestsFromModule(self, module, pattern=None): """Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests. """ if module in self._visited: return None self._visited.add(module) tests = [] tests.append(TestLoader.loadTestsFromModule(self, module)) if hasattr(module, "additional_tests"): tests.append(module.additional_tests()) if hasattr(module, '__path__'): for file in resource_listdir(module.__name__, ''): if file.endswith('.py') and file != '__init__.py': submodule = module.__name__ + '.' + file[:-3] else: if resource_exists(module.__name__, file + '/__init__.py'): submodule = module.__name__ + '.' + file else: continue tests.append(self.loadTestsFromName(submodule)) if len(tests) != 1: return self.suiteClass(tests) else: return tests[0]
[ "def", "loadTestsFromModule", "(", "self", ",", "module", ",", "pattern", "=", "None", ")", ":", "if", "module", "in", "self", ".", "_visited", ":", "return", "None", "self", ".", "_visited", ".", "add", "(", "module", ")", "tests", "=", "[", "]", "tests", ".", "append", "(", "TestLoader", ".", "loadTestsFromModule", "(", "self", ",", "module", ")", ")", "if", "hasattr", "(", "module", ",", "\"additional_tests\"", ")", ":", "tests", ".", "append", "(", "module", ".", "additional_tests", "(", ")", ")", "if", "hasattr", "(", "module", ",", "'__path__'", ")", ":", "for", "file", "in", "resource_listdir", "(", "module", ".", "__name__", ",", "''", ")", ":", "if", "file", ".", "endswith", "(", "'.py'", ")", "and", "file", "!=", "'__init__.py'", ":", "submodule", "=", "module", ".", "__name__", "+", "'.'", "+", "file", "[", ":", "-", "3", "]", "else", ":", "if", "resource_exists", "(", "module", ".", "__name__", ",", "file", "+", "'/__init__.py'", ")", ":", "submodule", "=", "module", ".", "__name__", "+", "'.'", "+", "file", "else", ":", "continue", "tests", ".", "append", "(", "self", ".", "loadTestsFromName", "(", "submodule", ")", ")", "if", "len", "(", "tests", ")", "!=", "1", ":", "return", "self", ".", "suiteClass", "(", "tests", ")", "else", ":", "return", "tests", "[", "0", "]" ]
[ 25, 4 ]
[ 56, 27 ]
python
en
['en', 'en', 'en']
True
test.with_project_on_sys_path
(self, func)
Backward compatibility for project_on_sys_path context.
Backward compatibility for project_on_sys_path context.
def with_project_on_sys_path(self, func): """ Backward compatibility for project_on_sys_path context. """ with self.project_on_sys_path(): func()
[ "def", "with_project_on_sys_path", "(", "self", ",", "func", ")", ":", "with", "self", ".", "project_on_sys_path", "(", ")", ":", "func", "(", ")" ]
[ 119, 4 ]
[ 124, 18 ]
python
en
['en', 'error', 'th']
False
test.paths_on_pythonpath
(paths)
Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths. Do this in a context that restores the value on exit.
Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths.
def paths_on_pythonpath(paths): """ Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths. Do this in a context that restores the value on exit. """ nothing = object() orig_pythonpath = os.environ.get('PYTHONPATH', nothing) current_pythonpath = os.environ.get('PYTHONPATH', '') try: prefix = os.pathsep.join(paths) to_join = filter(None, [prefix, current_pythonpath]) new_path = os.pathsep.join(to_join) if new_path: os.environ['PYTHONPATH'] = new_path yield finally: if orig_pythonpath is nothing: os.environ.pop('PYTHONPATH', None) else: os.environ['PYTHONPATH'] = orig_pythonpath
[ "def", "paths_on_pythonpath", "(", "paths", ")", ":", "nothing", "=", "object", "(", ")", "orig_pythonpath", "=", "os", ".", "environ", ".", "get", "(", "'PYTHONPATH'", ",", "nothing", ")", "current_pythonpath", "=", "os", ".", "environ", ".", "get", "(", "'PYTHONPATH'", ",", "''", ")", "try", ":", "prefix", "=", "os", ".", "pathsep", ".", "join", "(", "paths", ")", "to_join", "=", "filter", "(", "None", ",", "[", "prefix", ",", "current_pythonpath", "]", ")", "new_path", "=", "os", ".", "pathsep", ".", "join", "(", "to_join", ")", "if", "new_path", ":", "os", ".", "environ", "[", "'PYTHONPATH'", "]", "=", "new_path", "yield", "finally", ":", "if", "orig_pythonpath", "is", "nothing", ":", "os", ".", "environ", ".", "pop", "(", "'PYTHONPATH'", ",", "None", ")", "else", ":", "os", ".", "environ", "[", "'PYTHONPATH'", "]", "=", "orig_pythonpath" ]
[ 174, 4 ]
[ 196, 58 ]
python
en
['en', 'error', 'th']
False
test.install_dists
(dist)
Install the requirements indicated by self.distribution and return an iterable of the dists that were built.
Install the requirements indicated by self.distribution and return an iterable of the dists that were built.
def install_dists(dist): """ Install the requirements indicated by self.distribution and return an iterable of the dists that were built. """ ir_d = dist.fetch_build_eggs(dist.install_requires) tr_d = dist.fetch_build_eggs(dist.tests_require or []) er_d = dist.fetch_build_eggs( v for k, v in dist.extras_require.items() if k.startswith(':') and evaluate_marker(k[1:]) ) return itertools.chain(ir_d, tr_d, er_d)
[ "def", "install_dists", "(", "dist", ")", ":", "ir_d", "=", "dist", ".", "fetch_build_eggs", "(", "dist", ".", "install_requires", ")", "tr_d", "=", "dist", ".", "fetch_build_eggs", "(", "dist", ".", "tests_require", "or", "[", "]", ")", "er_d", "=", "dist", ".", "fetch_build_eggs", "(", "v", "for", "k", ",", "v", "in", "dist", ".", "extras_require", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "':'", ")", "and", "evaluate_marker", "(", "k", "[", "1", ":", "]", ")", ")", "return", "itertools", ".", "chain", "(", "ir_d", ",", "tr_d", ",", "er_d", ")" ]
[ 199, 4 ]
[ 210, 48 ]
python
en
['en', 'error', 'th']
False
test._resolve_as_ep
(val)
Load the indicated attribute value, called, as a as if it were specified as an entry point.
Load the indicated attribute value, called, as a as if it were specified as an entry point.
def _resolve_as_ep(val): """ Load the indicated attribute value, called, as a as if it were specified as an entry point. """ if val is None: return parsed = EntryPoint.parse("x=" + val) return parsed.resolve()()
[ "def", "_resolve_as_ep", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "parsed", "=", "EntryPoint", ".", "parse", "(", "\"x=\"", "+", "val", ")", "return", "parsed", ".", "resolve", "(", ")", "(", ")" ]
[ 259, 4 ]
[ 267, 33 ]
python
en
['en', 'error', 'th']
False
_running_under_venv
()
Checks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments.
Checks if sys.base_prefix and sys.prefix match.
def _running_under_venv(): # type: () -> bool """Checks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments. """ return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
[ "def", "_running_under_venv", "(", ")", ":", "# type: () -> bool", "return", "sys", ".", "prefix", "!=", "getattr", "(", "sys", ",", "\"base_prefix\"", ",", "sys", ".", "prefix", ")" ]
[ 13, 0 ]
[ 19, 64 ]
python
en
['en', 'ht', 'en']
True
_running_under_regular_virtualenv
()
Checks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv.
Checks if sys.real_prefix is set.
def _running_under_regular_virtualenv(): # type: () -> bool """Checks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv. """ # pypa/virtualenv case return hasattr(sys, "real_prefix")
[ "def", "_running_under_regular_virtualenv", "(", ")", ":", "# type: () -> bool", "# pypa/virtualenv case", "return", "hasattr", "(", "sys", ",", "\"real_prefix\"", ")" ]
[ 22, 0 ]
[ 29, 38 ]
python
en
['en', 'en', 'en']
True
running_under_virtualenv
()
Return True if we're running inside a virtualenv, False otherwise.
Return True if we're running inside a virtualenv, False otherwise.
def running_under_virtualenv(): # type: () -> bool """Return True if we're running inside a virtualenv, False otherwise.""" return _running_under_venv() or _running_under_regular_virtualenv()
[ "def", "running_under_virtualenv", "(", ")", ":", "# type: () -> bool", "return", "_running_under_venv", "(", ")", "or", "_running_under_regular_virtualenv", "(", ")" ]
[ 32, 0 ]
[ 35, 71 ]
python
en
['en', 'en', 'en']
True
_get_pyvenv_cfg_lines
()
Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file.
Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
def _get_pyvenv_cfg_lines(): # type: () -> Optional[List[str]] """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file. """ pyvenv_cfg_file = os.path.join(sys.prefix, "pyvenv.cfg") try: # Although PEP 405 does not specify, the built-in venv module always # writes with UTF-8. (pypa/pip#8717) with open(pyvenv_cfg_file, encoding="utf-8") as f: return f.read().splitlines() # avoids trailing newlines except OSError: return None
[ "def", "_get_pyvenv_cfg_lines", "(", ")", ":", "# type: () -> Optional[List[str]]", "pyvenv_cfg_file", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "\"pyvenv.cfg\"", ")", "try", ":", "# Although PEP 405 does not specify, the built-in venv module always", "# writes with UTF-8. (pypa/pip#8717)", "with", "open", "(", "pyvenv_cfg_file", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "# avoids trailing newlines", "except", "OSError", ":", "return", "None" ]
[ 38, 0 ]
[ 51, 19 ]
python
en
['en', 'en', 'en']
True
_no_global_under_venv
()
Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-site-packages = false Additionally, log a warning if accessing the file fails.
Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
def _no_global_under_venv(): # type: () -> bool """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-site-packages = false Additionally, log a warning if accessing the file fails. """ cfg_lines = _get_pyvenv_cfg_lines() if cfg_lines is None: # We're not in a "sane" venv, so assume there is no system # site-packages access (since that's PEP 405's default state). logger.warning( "Could not access 'pyvenv.cfg' despite a virtual environment " "being active. Assuming global site-packages is not accessible " "in this environment." ) return True for line in cfg_lines: match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line) if match is not None and match.group("value") == "false": return True return False
[ "def", "_no_global_under_venv", "(", ")", ":", "# type: () -> bool", "cfg_lines", "=", "_get_pyvenv_cfg_lines", "(", ")", "if", "cfg_lines", "is", "None", ":", "# We're not in a \"sane\" venv, so assume there is no system", "# site-packages access (since that's PEP 405's default state).", "logger", ".", "warning", "(", "\"Could not access 'pyvenv.cfg' despite a virtual environment \"", "\"being active. Assuming global site-packages is not accessible \"", "\"in this environment.\"", ")", "return", "True", "for", "line", "in", "cfg_lines", ":", "match", "=", "_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX", ".", "match", "(", "line", ")", "if", "match", "is", "not", "None", "and", "match", ".", "group", "(", "\"value\"", ")", "==", "\"false\"", ":", "return", "True", "return", "False" ]
[ 54, 0 ]
[ 81, 16 ]
python
en
['en', 'en', 'en']
True
_no_global_under_regular_virtualenv
()
Check if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment.
Check if "no-global-site-packages.txt" exists beside site.py
def _no_global_under_regular_virtualenv(): # type: () -> bool """Check if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment. """ site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_site_packages_file = os.path.join( site_mod_dir, "no-global-site-packages.txt", ) return os.path.exists(no_global_site_packages_file)
[ "def", "_no_global_under_regular_virtualenv", "(", ")", ":", "# type: () -> bool", "site_mod_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "site", ".", "__file__", ")", ")", "no_global_site_packages_file", "=", "os", ".", "path", ".", "join", "(", "site_mod_dir", ",", "\"no-global-site-packages.txt\"", ",", ")", "return", "os", ".", "path", ".", "exists", "(", "no_global_site_packages_file", ")" ]
[ 84, 0 ]
[ 96, 55 ]
python
en
['en', 'en', 'en']
True
virtualenv_no_global
()
Returns a boolean, whether running in venv with no system site-packages.
Returns a boolean, whether running in venv with no system site-packages.
def virtualenv_no_global(): # type: () -> bool """Returns a boolean, whether running in venv with no system site-packages.""" # PEP 405 compliance needs to be checked first since virtualenv >=20 would # return True for both checks, but is only able to use the PEP 405 config. if _running_under_venv(): return _no_global_under_venv() if _running_under_regular_virtualenv(): return _no_global_under_regular_virtualenv() return False
[ "def", "virtualenv_no_global", "(", ")", ":", "# type: () -> bool", "# PEP 405 compliance needs to be checked first since virtualenv >=20 would", "# return True for both checks, but is only able to use the PEP 405 config.", "if", "_running_under_venv", "(", ")", ":", "return", "_no_global_under_venv", "(", ")", "if", "_running_under_regular_virtualenv", "(", ")", ":", "return", "_no_global_under_regular_virtualenv", "(", ")", "return", "False" ]
[ 99, 0 ]
[ 110, 16 ]
python
en
['en', 'en', 'en']
True
main
(args=None)
This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498.
This is preserved for old console scripts that may still be referencing it.
def main(args=None): # type: (Optional[List[str]]) -> int """This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper return _wrapper(args)
[ "def", "main", "(", "args", "=", "None", ")", ":", "# type: (Optional[List[str]]) -> int", "from", "pip", ".", "_internal", ".", "utils", ".", "entrypoints", "import", "_wrapper", "return", "_wrapper", "(", "args", ")" ]
[ 3, 0 ]
[ 12, 25 ]
python
en
['en', 'en', 'en']
True
run_and_get_output
(popen_args)
Run process and get all output
Run process and get all output
def run_and_get_output(popen_args): """Run process and get all output""" process_output = namedtuple('ProcessOutput', ['stdout', 'stderr', 'retcode']) try: GlobalConfig.logger.debug('run_and_get_output({0})'.format(repr(popen_args))) proc = Popen(popen_args, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = proc.communicate(b'') proc_out = process_output(stdout, stderr, proc.returncode) GlobalConfig.logger.debug('\tprocess_output: {0}'.format(proc_out)) return proc_out except Exception as exc: GlobalConfig.logger.error('\texception: {0}'.format(exc)) return process_output('', exc.message, -1)
[ "def", "run_and_get_output", "(", "popen_args", ")", ":", "process_output", "=", "namedtuple", "(", "'ProcessOutput'", ",", "[", "'stdout'", ",", "'stderr'", ",", "'retcode'", "]", ")", "try", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'run_and_get_output({0})'", ".", "format", "(", "repr", "(", "popen_args", ")", ")", ")", "proc", "=", "Popen", "(", "popen_args", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "stdout", ",", "stderr", "=", "proc", ".", "communicate", "(", "b''", ")", "proc_out", "=", "process_output", "(", "stdout", ",", "stderr", ",", "proc", ".", "returncode", ")", "GlobalConfig", ".", "logger", ".", "debug", "(", "'\\tprocess_output: {0}'", ".", "format", "(", "proc_out", ")", ")", "return", "proc_out", "except", "Exception", "as", "exc", ":", "GlobalConfig", ".", "logger", ".", "error", "(", "'\\texception: {0}'", ".", "format", "(", "exc", ")", ")", "return", "process_output", "(", "''", ",", "exc", ".", "message", ",", "-", "1", ")" ]
[ 56, 0 ]
[ 70, 50 ]
python
en
['en', 'en', 'en']
True
get_dependencies
(filename)
input: filename must be an absolute path Should call `otool` and returns the list of dependencies, unsorted, unmodified, just the raw list so then we could eventually re-use in other more specialized functions
input: filename must be an absolute path Should call `otool` and returns the list of dependencies, unsorted, unmodified, just the raw list so then we could eventually re-use in other more specialized functions
def get_dependencies(filename): """ input: filename must be an absolute path Should call `otool` and returns the list of dependencies, unsorted, unmodified, just the raw list so then we could eventually re-use in other more specialized functions """ GlobalConfig.logger.debug('get_dependencies({0})'.format(filename)) popen_args = ['otool', '-L', filename] proc_out = run_and_get_output(popen_args) deps = [] if proc_out.retcode == 0: # some string splitting deps = [s.strip().split(b' ')[0].decode('utf-8') for s in proc_out.stdout.splitlines()[1:] if s] # prevent infinite recursion when a binary depends on itself (seen with QtWidgets)... deps = [s for s in deps if os.path.basename(filename) not in s] return deps
[ "def", "get_dependencies", "(", "filename", ")", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'get_dependencies({0})'", ".", "format", "(", "filename", ")", ")", "popen_args", "=", "[", "'otool'", ",", "'-L'", ",", "filename", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "deps", "=", "[", "]", "if", "proc_out", ".", "retcode", "==", "0", ":", "# some string splitting", "deps", "=", "[", "s", ".", "strip", "(", ")", ".", "split", "(", "b' '", ")", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", "for", "s", "in", "proc_out", ".", "stdout", ".", "splitlines", "(", ")", "[", "1", ":", "]", "if", "s", "]", "# prevent infinite recursion when a binary depends on itself (seen with QtWidgets)...", "deps", "=", "[", "s", "for", "s", "in", "deps", "if", "os", ".", "path", ".", "basename", "(", "filename", ")", "not", "in", "s", "]", "return", "deps" ]
[ 73, 0 ]
[ 89, 15 ]
python
en
['en', 'error', 'th']
False
is_qt_plugin
(filename)
Checks if a given file is a qt plugin. Accepts absolute path as well as path containing @executable_path
Checks if a given file is a qt plugin. Accepts absolute path as well as path containing
def is_qt_plugin(filename): """ Checks if a given file is a qt plugin. Accepts absolute path as well as path containing @executable_path """ qtlib_name_rgx = re.compile(QTPLUGIN_NAME_REGEX) return qtlib_name_rgx.match(filename) is not None
[ "def", "is_qt_plugin", "(", "filename", ")", ":", "qtlib_name_rgx", "=", "re", ".", "compile", "(", "QTPLUGIN_NAME_REGEX", ")", "return", "qtlib_name_rgx", ".", "match", "(", "filename", ")", "is", "not", "None" ]
[ 92, 0 ]
[ 98, 53 ]
python
en
['en', 'error', 'th']
False
is_qt_lib
(filename)
Checks if a given file is a qt library. Accepts absolute path as well as path containing @executable_path
Checks if a given file is a qt library. Accepts absolute path as well as path containing
def is_qt_lib(filename): """ Checks if a given file is a qt library. Accepts absolute path as well as path containing @executable_path """ qtlib_name_rgx = re.compile(QTLIB_NAME_REGEX) return qtlib_name_rgx.match(filename) is not None
[ "def", "is_qt_lib", "(", "filename", ")", ":", "qtlib_name_rgx", "=", "re", ".", "compile", "(", "QTLIB_NAME_REGEX", ")", "return", "qtlib_name_rgx", ".", "match", "(", "filename", ")", "is", "not", "None" ]
[ 101, 0 ]
[ 107, 53 ]
python
en
['en', 'error', 'th']
False
is_loader_path_lib
(filename)
Checks if a given file is loaded via @loader_path or @rpath
Checks if a given file is loaded via
def is_loader_path_lib(filename): """ Checks if a given file is loaded via @loader_path or @rpath """ qtlib_name_rgx = re.compile(LOADERPATH_REGEX) return qtlib_name_rgx.match(filename) is not None
[ "def", "is_loader_path_lib", "(", "filename", ")", ":", "qtlib_name_rgx", "=", "re", ".", "compile", "(", "LOADERPATH_REGEX", ")", "return", "qtlib_name_rgx", ".", "match", "(", "filename", ")", "is", "not", "None" ]
[ 110, 0 ]
[ 115, 53 ]
python
en
['en', 'error', 'th']
False
normalize_qtplugin_name
(filename)
input: a path to a qt plugin, as returned by otool, that can have this form : - an absolute path /../plugins/PLUGINTYPE/PLUGINNAME.dylib - @executable_path/../plugins/PLUGINTYPE/PLUGINNAME.dylib output: a tuple (qtlib, abspath, rpath) where: - qtname is the name of the plugin (libqcocoa.dylib, etc.) - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle
input: a path to a qt plugin, as returned by otool, that can have this form : - an absolute path /../plugins/PLUGINTYPE/PLUGINNAME.dylib -
def normalize_qtplugin_name(filename): """ input: a path to a qt plugin, as returned by otool, that can have this form : - an absolute path /../plugins/PLUGINTYPE/PLUGINNAME.dylib - @executable_path/../plugins/PLUGINTYPE/PLUGINNAME.dylib output: a tuple (qtlib, abspath, rpath) where: - qtname is the name of the plugin (libqcocoa.dylib, etc.) - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle """ GlobalConfig.logger.debug('normalize_plugin_name({0})'.format(filename)) qtplugin_name_rgx = re.compile(QTPLUGIN_NAME_REGEX) rgxret = qtplugin_name_rgx.match(filename) if not rgxret: msg = 'couldn\'t normalize a non-qt plugin filename: {0}'.format(filename) GlobalConfig.logger.critical(msg) raise Exception(msg) # qtplugin normalization settings qtplugintype = rgxret.groups()[0] qtpluginname = rgxret.groups()[1] templ = Template(QTPLUGIN_NORMALIZED) # from qtlib, forge 2 path : # - absolute path of qt lib in bundle, abspath = os.path.normpath(templ.safe_substitute( prefix=os.path.dirname(GlobalConfig.exepath) + '/..', plugintype=qtplugintype, pluginname=qtpluginname)) # - and rpath containing @executable_path, relative to exepath rpath = templ.safe_substitute( prefix='@executable_path/..', plugintype=qtplugintype, pluginname=qtpluginname) GlobalConfig.logger.debug('\treturns({0})'.format((qtpluginname, abspath, rpath))) return qtpluginname, abspath, rpath
[ "def", "normalize_qtplugin_name", "(", "filename", ")", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'normalize_plugin_name({0})'", ".", "format", "(", "filename", ")", ")", "qtplugin_name_rgx", "=", "re", ".", "compile", "(", "QTPLUGIN_NAME_REGEX", ")", "rgxret", "=", "qtplugin_name_rgx", ".", "match", "(", "filename", ")", "if", "not", "rgxret", ":", "msg", "=", "'couldn\\'t normalize a non-qt plugin filename: {0}'", ".", "format", "(", "filename", ")", "GlobalConfig", ".", "logger", ".", "critical", "(", "msg", ")", "raise", "Exception", "(", "msg", ")", "# qtplugin normalization settings", "qtplugintype", "=", "rgxret", ".", "groups", "(", ")", "[", "0", "]", "qtpluginname", "=", "rgxret", ".", "groups", "(", ")", "[", "1", "]", "templ", "=", "Template", "(", "QTPLUGIN_NORMALIZED", ")", "# from qtlib, forge 2 path :", "# - absolute path of qt lib in bundle,", "abspath", "=", "os", ".", "path", ".", "normpath", "(", "templ", ".", "safe_substitute", "(", "prefix", "=", "os", ".", "path", ".", "dirname", "(", "GlobalConfig", ".", "exepath", ")", "+", "'/..'", ",", "plugintype", "=", "qtplugintype", ",", "pluginname", "=", "qtpluginname", ")", ")", "# - and rpath containing @executable_path, relative to exepath", "rpath", "=", "templ", ".", "safe_substitute", "(", "prefix", "=", "'@executable_path/..'", ",", "plugintype", "=", "qtplugintype", ",", "pluginname", "=", "qtpluginname", ")", "GlobalConfig", ".", "logger", ".", "debug", "(", "'\\treturns({0})'", ".", "format", "(", "(", "qtpluginname", ",", "abspath", ",", "rpath", ")", ")", ")", "return", "qtpluginname", ",", "abspath", ",", "rpath" ]
[ 118, 0 ]
[ 159, 39 ]
python
en
['en', 'error', 'th']
False
normalize_qtlib_name
(filename)
input: a path to a qt library, as returned by otool, that can have this form : - an absolute path /lib/xxx/yyy - @executable_path/../Frameworks/QtSerialPort.framework/Versions/5/QtSerialPort output: a tuple (qtlib, abspath, rpath) where: - qtlib is the name of the qtlib (QtCore, QtWidgets, etc.) - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle
input: a path to a qt library, as returned by otool, that can have this form : - an absolute path /lib/xxx/yyy -
def normalize_qtlib_name(filename): """ input: a path to a qt library, as returned by otool, that can have this form : - an absolute path /lib/xxx/yyy - @executable_path/../Frameworks/QtSerialPort.framework/Versions/5/QtSerialPort output: a tuple (qtlib, abspath, rpath) where: - qtlib is the name of the qtlib (QtCore, QtWidgets, etc.) - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle """ GlobalConfig.logger.debug('normalize_qtlib_name({0})'.format(filename)) qtlib_name_rgx = re.compile(QTLIB_NAME_REGEX) rgxret = qtlib_name_rgx.match(filename) if not rgxret: msg = 'couldn\'t normalize a non-qt lib filename: {0}'.format(filename) GlobalConfig.logger.critical(msg) raise Exception(msg) # qtlib normalization settings qtlib = rgxret.groups()[0] qtversion = 5 templ = Template(QTLIB_NORMALIZED) # from qtlib, forge 2 path : # - absolute path of qt lib in bundle, abspath = os.path.normpath(templ.safe_substitute( prefix=os.path.dirname(GlobalConfig.exepath) + '/..', qtlib=qtlib, qtversion=qtversion)) # - and rpath containing @executable_path, relative to exepath rpath = templ.safe_substitute( prefix='@executable_path/..', qtlib=qtlib, qtversion=qtversion) GlobalConfig.logger.debug('\treturns({0})'.format((qtlib, abspath, rpath))) return qtlib, abspath, rpath
[ "def", "normalize_qtlib_name", "(", "filename", ")", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'normalize_qtlib_name({0})'", ".", "format", "(", "filename", ")", ")", "qtlib_name_rgx", "=", "re", ".", "compile", "(", "QTLIB_NAME_REGEX", ")", "rgxret", "=", "qtlib_name_rgx", ".", "match", "(", "filename", ")", "if", "not", "rgxret", ":", "msg", "=", "'couldn\\'t normalize a non-qt lib filename: {0}'", ".", "format", "(", "filename", ")", "GlobalConfig", ".", "logger", ".", "critical", "(", "msg", ")", "raise", "Exception", "(", "msg", ")", "# qtlib normalization settings", "qtlib", "=", "rgxret", ".", "groups", "(", ")", "[", "0", "]", "qtversion", "=", "5", "templ", "=", "Template", "(", "QTLIB_NORMALIZED", ")", "# from qtlib, forge 2 path :", "# - absolute path of qt lib in bundle,", "abspath", "=", "os", ".", "path", ".", "normpath", "(", "templ", ".", "safe_substitute", "(", "prefix", "=", "os", ".", "path", ".", "dirname", "(", "GlobalConfig", ".", "exepath", ")", "+", "'/..'", ",", "qtlib", "=", "qtlib", ",", "qtversion", "=", "qtversion", ")", ")", "# - and rpath containing @executable_path, relative to exepath", "rpath", "=", "templ", ".", "safe_substitute", "(", "prefix", "=", "'@executable_path/..'", ",", "qtlib", "=", "qtlib", ",", "qtversion", "=", "qtversion", ")", "GlobalConfig", ".", "logger", ".", "debug", "(", "'\\treturns({0})'", ".", "format", "(", "(", "qtlib", ",", "abspath", ",", "rpath", ")", ")", ")", "return", "qtlib", ",", "abspath", ",", "rpath" ]
[ 162, 0 ]
[ 202, 32 ]
python
en
['en', 'error', 'th']
False
normalize_loaderpath_name
(filename)
input: a path to a loaderpath library, as returned by otool, that can have this form : - an relative path @loaderpath/yyy output: a tuple (loaderpathlib, abspath, rpath) where: - loaderpathlib is the name of the loaderpath lib - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle
input: a path to a loaderpath library, as returned by otool, that can have this form : - an relative path
def normalize_loaderpath_name(filename): """ input: a path to a loaderpath library, as returned by otool, that can have this form : - an relative path @loaderpath/yyy output: a tuple (loaderpathlib, abspath, rpath) where: - loaderpathlib is the name of the loaderpath lib - abspath is the absolute path of the qt lib inside the app bundle of exepath - relpath is the correct rpath to a qt lib inside the app bundle """ GlobalConfig.logger.debug('normalize_loaderpath_name({0})'.format(filename)) loaderpath_name_rgx = re.compile(LOADERPATH_REGEX) rgxret = loaderpath_name_rgx.match(filename) if not rgxret: msg = 'couldn\'t normalize a loaderpath lib filename: {0}'.format(filename) GlobalConfig.logger.critical(msg) raise Exception(msg) # loaderpath normalization settings loaderpathlib = rgxret.groups()[0] templ = Template(LOADERPATH_NORMALIZED) # from loaderpath, forge 2 path : # - absolute path of qt lib in bundle, abspath = os.path.normpath(templ.safe_substitute( prefix=os.path.dirname(GlobalConfig.exepath) + '/..', loaderpathlib=loaderpathlib)) # - and rpath containing @executable_path, relative to exepath rpath = templ.safe_substitute( prefix='@executable_path/..', loaderpathlib=loaderpathlib) GlobalConfig.logger.debug('\treturns({0})'.format((loaderpathlib, abspath, rpath))) return loaderpathlib, abspath, rpath
[ "def", "normalize_loaderpath_name", "(", "filename", ")", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'normalize_loaderpath_name({0})'", ".", "format", "(", "filename", ")", ")", "loaderpath_name_rgx", "=", "re", ".", "compile", "(", "LOADERPATH_REGEX", ")", "rgxret", "=", "loaderpath_name_rgx", ".", "match", "(", "filename", ")", "if", "not", "rgxret", ":", "msg", "=", "'couldn\\'t normalize a loaderpath lib filename: {0}'", ".", "format", "(", "filename", ")", "GlobalConfig", ".", "logger", ".", "critical", "(", "msg", ")", "raise", "Exception", "(", "msg", ")", "# loaderpath normalization settings", "loaderpathlib", "=", "rgxret", ".", "groups", "(", ")", "[", "0", "]", "templ", "=", "Template", "(", "LOADERPATH_NORMALIZED", ")", "# from loaderpath, forge 2 path :", "# - absolute path of qt lib in bundle,", "abspath", "=", "os", ".", "path", ".", "normpath", "(", "templ", ".", "safe_substitute", "(", "prefix", "=", "os", ".", "path", ".", "dirname", "(", "GlobalConfig", ".", "exepath", ")", "+", "'/..'", ",", "loaderpathlib", "=", "loaderpathlib", ")", ")", "# - and rpath containing @executable_path, relative to exepath", "rpath", "=", "templ", ".", "safe_substitute", "(", "prefix", "=", "'@executable_path/..'", ",", "loaderpathlib", "=", "loaderpathlib", ")", "GlobalConfig", ".", "logger", ".", "debug", "(", "'\\treturns({0})'", ".", "format", "(", "(", "loaderpathlib", ",", "abspath", ",", "rpath", ")", ")", ")", "return", "loaderpathlib", ",", "abspath", ",", "rpath" ]
[ 205, 0 ]
[ 240, 40 ]
python
en
['en', 'error', 'th']
False
fix_dependency
(binary, dep)
fix 'dep' dependency of 'binary'. 'dep' is a qt library
fix 'dep' dependency of 'binary'. 'dep' is a qt library
def fix_dependency(binary, dep): """ fix 'dep' dependency of 'binary'. 'dep' is a qt library """ if is_qt_lib(dep): qtname, dep_abspath, dep_rpath = normalize_qtlib_name(dep) qtnamesrc = os.path.join(GlobalConfig.qtpath, 'lib', '{0}.framework'. format(qtname), qtname) elif is_qt_plugin(dep): qtname, dep_abspath, dep_rpath = normalize_qtplugin_name(dep) qtnamesrc = os.path.join(GlobalConfig.qtpath, 'lib', '{0}.framework'. format(qtname), qtname) elif is_loader_path_lib(dep): qtname, dep_abspath, dep_rpath = normalize_loaderpath_name(dep) qtnamesrc = os.path.join(GlobalConfig.qtpath + '/lib', qtname) else: return True # if the source path doesn't exist it's probably not a dependency # originating with vcpkg and we should leave it alone if not os.path.exists(qtnamesrc): return True dep_ok = True # check that rpath of 'dep' inside binary has been correctly set # (ie: relative to exepath using '@executable_path' syntax) if dep != dep_rpath: # dep rpath is not ok GlobalConfig.logger.info('changing rpath \'{0}\' in binary {1}'.format(dep, binary)) # call install_name_tool -change on binary popen_args = ['install_name_tool', '-change', dep, dep_rpath, binary] proc_out = run_and_get_output(popen_args) if proc_out.retcode != 0: GlobalConfig.logger.error(proc_out.stderr) dep_ok = False else: # call install_name_tool -id on binary popen_args = ['install_name_tool', '-id', dep_rpath, binary] proc_out = run_and_get_output(popen_args) if proc_out.retcode != 0: GlobalConfig.logger.error(proc_out.stderr) dep_ok = False # now ensure that 'dep' exists at the specified path, relative to bundle if dep_ok and not os.path.exists(dep_abspath): # ensure destination directory exists GlobalConfig.logger.info('ensuring directory \'{0}\' exists: {0}'. format(os.path.dirname(dep_abspath))) popen_args = ['mkdir', '-p', os.path.dirname(dep_abspath)] proc_out = run_and_get_output(popen_args) if proc_out.retcode != 0: GlobalConfig.logger.info(proc_out.stderr) dep_ok = False else: # copy missing dependency into bundle GlobalConfig.logger.info('copying missing dependency in bundle: {0}'. format(qtname)) popen_args = ['cp', qtnamesrc, dep_abspath] proc_out = run_and_get_output(popen_args) if proc_out.retcode != 0: GlobalConfig.logger.info(proc_out.stderr) dep_ok = False else: # ensure permissions are correct if we ever have to change its rpath GlobalConfig.logger.info('ensuring 755 perm to {0}'.format(dep_abspath)) popen_args = ['chmod', '755', dep_abspath] proc_out = run_and_get_output(popen_args) if proc_out.retcode != 0: GlobalConfig.logger.info(proc_out.stderr) dep_ok = False else: GlobalConfig.logger.debug('{0} is at correct location in bundle'.format(qtname)) if dep_ok: return fix_binary(dep_abspath) return False
[ "def", "fix_dependency", "(", "binary", ",", "dep", ")", ":", "if", "is_qt_lib", "(", "dep", ")", ":", "qtname", ",", "dep_abspath", ",", "dep_rpath", "=", "normalize_qtlib_name", "(", "dep", ")", "qtnamesrc", "=", "os", ".", "path", ".", "join", "(", "GlobalConfig", ".", "qtpath", ",", "'lib'", ",", "'{0}.framework'", ".", "format", "(", "qtname", ")", ",", "qtname", ")", "elif", "is_qt_plugin", "(", "dep", ")", ":", "qtname", ",", "dep_abspath", ",", "dep_rpath", "=", "normalize_qtplugin_name", "(", "dep", ")", "qtnamesrc", "=", "os", ".", "path", ".", "join", "(", "GlobalConfig", ".", "qtpath", ",", "'lib'", ",", "'{0}.framework'", ".", "format", "(", "qtname", ")", ",", "qtname", ")", "elif", "is_loader_path_lib", "(", "dep", ")", ":", "qtname", ",", "dep_abspath", ",", "dep_rpath", "=", "normalize_loaderpath_name", "(", "dep", ")", "qtnamesrc", "=", "os", ".", "path", ".", "join", "(", "GlobalConfig", ".", "qtpath", "+", "'/lib'", ",", "qtname", ")", "else", ":", "return", "True", "# if the source path doesn't exist it's probably not a dependency", "# originating with vcpkg and we should leave it alone", "if", "not", "os", ".", "path", ".", "exists", "(", "qtnamesrc", ")", ":", "return", "True", "dep_ok", "=", "True", "# check that rpath of 'dep' inside binary has been correctly set", "# (ie: relative to exepath using '@executable_path' syntax)", "if", "dep", "!=", "dep_rpath", ":", "# dep rpath is not ok", "GlobalConfig", ".", "logger", ".", "info", "(", "'changing rpath \\'{0}\\' in binary {1}'", ".", "format", "(", "dep", ",", "binary", ")", ")", "# call install_name_tool -change on binary", "popen_args", "=", "[", "'install_name_tool'", ",", "'-change'", ",", "dep", ",", "dep_rpath", ",", "binary", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "if", "proc_out", ".", "retcode", "!=", "0", ":", "GlobalConfig", ".", "logger", ".", "error", "(", "proc_out", ".", "stderr", ")", "dep_ok", "=", "False", "else", ":", "# call install_name_tool -id on binary", "popen_args", "=", "[", "'install_name_tool'", ",", "'-id'", ",", "dep_rpath", ",", "binary", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "if", "proc_out", ".", "retcode", "!=", "0", ":", "GlobalConfig", ".", "logger", ".", "error", "(", "proc_out", ".", "stderr", ")", "dep_ok", "=", "False", "# now ensure that 'dep' exists at the specified path, relative to bundle", "if", "dep_ok", "and", "not", "os", ".", "path", ".", "exists", "(", "dep_abspath", ")", ":", "# ensure destination directory exists", "GlobalConfig", ".", "logger", ".", "info", "(", "'ensuring directory \\'{0}\\' exists: {0}'", ".", "format", "(", "os", ".", "path", ".", "dirname", "(", "dep_abspath", ")", ")", ")", "popen_args", "=", "[", "'mkdir'", ",", "'-p'", ",", "os", ".", "path", ".", "dirname", "(", "dep_abspath", ")", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "if", "proc_out", ".", "retcode", "!=", "0", ":", "GlobalConfig", ".", "logger", ".", "info", "(", "proc_out", ".", "stderr", ")", "dep_ok", "=", "False", "else", ":", "# copy missing dependency into bundle", "GlobalConfig", ".", "logger", ".", "info", "(", "'copying missing dependency in bundle: {0}'", ".", "format", "(", "qtname", ")", ")", "popen_args", "=", "[", "'cp'", ",", "qtnamesrc", ",", "dep_abspath", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "if", "proc_out", ".", "retcode", "!=", "0", ":", "GlobalConfig", ".", "logger", ".", "info", "(", "proc_out", ".", "stderr", ")", "dep_ok", "=", "False", "else", ":", "# ensure permissions are correct if we ever have to change its rpath", "GlobalConfig", ".", "logger", ".", "info", "(", "'ensuring 755 perm to {0}'", ".", "format", "(", "dep_abspath", ")", ")", "popen_args", "=", "[", "'chmod'", ",", "'755'", ",", "dep_abspath", "]", "proc_out", "=", "run_and_get_output", "(", "popen_args", ")", "if", "proc_out", ".", "retcode", "!=", "0", ":", "GlobalConfig", ".", "logger", ".", "info", "(", "proc_out", ".", "stderr", ")", "dep_ok", "=", "False", "else", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'{0} is at correct location in bundle'", ".", "format", "(", "qtname", ")", ")", "if", "dep_ok", ":", "return", "fix_binary", "(", "dep_abspath", ")", "return", "False" ]
[ 243, 0 ]
[ 320, 16 ]
python
en
['en', 'error', 'th']
False
fix_binary
(binary)
input: binary: relative or absolute path (no @executable_path syntax) process: - first fix the rpath for the qt libs on which 'binary' depend - copy into the bundle of exepath the eventual libraries that are missing - (create the soft links) needed ? - do the same for all qt dependencies of binary (recursive)
input: binary: relative or absolute path (no
def fix_binary(binary): """ input: binary: relative or absolute path (no @executable_path syntax) process: - first fix the rpath for the qt libs on which 'binary' depend - copy into the bundle of exepath the eventual libraries that are missing - (create the soft links) needed ? - do the same for all qt dependencies of binary (recursive) """ GlobalConfig.logger.debug('fix_binary({0})'.format(binary)) # loop on 'binary' dependencies for dep in get_dependencies(binary): if not fix_dependency(binary, dep): GlobalConfig.logger.error('quitting early: couldn\'t fix dependency {0} of {1}'.format(dep, binary)) return False return True
[ "def", "fix_binary", "(", "binary", ")", ":", "GlobalConfig", ".", "logger", ".", "debug", "(", "'fix_binary({0})'", ".", "format", "(", "binary", ")", ")", "# loop on 'binary' dependencies", "for", "dep", "in", "get_dependencies", "(", "binary", ")", ":", "if", "not", "fix_dependency", "(", "binary", ",", "dep", ")", ":", "GlobalConfig", ".", "logger", ".", "error", "(", "'quitting early: couldn\\'t fix dependency {0} of {1}'", ".", "format", "(", "dep", ",", "binary", ")", ")", "return", "False", "return", "True" ]
[ 323, 0 ]
[ 340, 15 ]
python
en
['en', 'error', 'th']
False
fix_main_binaries
()
list the main binaries of the app bundle and fix them
list the main binaries of the app bundle and fix them
def fix_main_binaries(): """ list the main binaries of the app bundle and fix them """ # deduce bundle path bundlepath = os.path.sep.join(GlobalConfig.exepath.split(os.path.sep)[0:-3]) # fix main binary GlobalConfig.logger.info('fixing executable \'{0}\''.format(GlobalConfig.exepath)) if fix_binary(GlobalConfig.exepath): GlobalConfig.logger.info('fixing plugins') for root, dummy, files in os.walk(bundlepath): for name in [f for f in files if os.path.splitext(f)[1] == '.dylib']: GlobalConfig.logger.info('fixing plugin {0}'.format(name)) if not fix_binary(os.path.join(root, name)): return False return True
[ "def", "fix_main_binaries", "(", ")", ":", "# deduce bundle path", "bundlepath", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "GlobalConfig", ".", "exepath", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "0", ":", "-", "3", "]", ")", "# fix main binary", "GlobalConfig", ".", "logger", ".", "info", "(", "'fixing executable \\'{0}\\''", ".", "format", "(", "GlobalConfig", ".", "exepath", ")", ")", "if", "fix_binary", "(", "GlobalConfig", ".", "exepath", ")", ":", "GlobalConfig", ".", "logger", ".", "info", "(", "'fixing plugins'", ")", "for", "root", ",", "dummy", ",", "files", "in", "os", ".", "walk", "(", "bundlepath", ")", ":", "for", "name", "in", "[", "f", "for", "f", "in", "files", "if", "os", ".", "path", ".", "splitext", "(", "f", ")", "[", "1", "]", "==", "'.dylib'", "]", ":", "GlobalConfig", ".", "logger", ".", "info", "(", "'fixing plugin {0}'", ".", "format", "(", "name", ")", ")", "if", "not", "fix_binary", "(", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", ")", ":", "return", "False", "return", "True" ]
[ 343, 0 ]
[ 359, 15 ]
python
en
['en', 'error', 'th']
False
check_red_hat_firewall_issue
()
Checking if a firewall is found on the device if firewall was found, trying to see if the agent port was added as exception if so restart the firewall :return:
Checking if a firewall is found on the device if firewall was found, trying to see if the agent port was added as exception if so restart the firewall :return:
def check_red_hat_firewall_issue(): ''' Checking if a firewall is found on the device if firewall was found, trying to see if the agent port was added as exception if so restart the firewall :return: ''' print_notice("Checking if firewalld is installed.") print_notice("systemctl status firewalld") firewall_status = subprocess.Popen(["systemctl", "status", "firewalld"], stdout=subprocess.PIPE) o, e = firewall_status.communicate() if e is not None: print_error("Error: could not check CentOS / RHEL 7 firewalld status.") else: if "running" in str(o): print_warning( "Warning: you have a firewall running on your linux machine this can prevent communication between the syslog daemon and the omsagent.") print("Checking if firewall has exception for omsagent port.[" + agent_port + "]") if red_hat_firewall_d_exception_for_omsagent(): print_ok("Found exception in the firewalld for the omsagent port.[" + agent_port + "]") restart_red_hat_firewall_d() else: print_warning("Warning: no exception found for omsagent in the firewall") print_warning( "You can add exception for the agent port[" + agent_port + "] by using the following commands:") print_warning("Add exception:") print_notice( "sudo firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport " + agent_port + " -j ACCEPT") print_warning("Validate the exception was added in the configuration:") print_notice("sudo firewall-cmd --direct --get-rules ipv4 filter INPUT") print_warning("Reload the firewall:") print_notice("sudo firewall-cmd --reload") print_warning("You can disable your firewall by using this command - not recommended:") print_notice("sudo systemctl stop firewalld")
[ "def", "check_red_hat_firewall_issue", "(", ")", ":", "print_notice", "(", "\"Checking if firewalld is installed.\"", ")", "print_notice", "(", "\"systemctl status firewalld\"", ")", "firewall_status", "=", "subprocess", ".", "Popen", "(", "[", "\"systemctl\"", ",", "\"status\"", ",", "\"firewalld\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "firewall_status", ".", "communicate", "(", ")", "if", "e", "is", "not", "None", ":", "print_error", "(", "\"Error: could not check CentOS / RHEL 7 firewalld status.\"", ")", "else", ":", "if", "\"running\"", "in", "str", "(", "o", ")", ":", "print_warning", "(", "\"Warning: you have a firewall running on your linux machine this can prevent communication between the syslog daemon and the omsagent.\"", ")", "print", "(", "\"Checking if firewall has exception for omsagent port.[\"", "+", "agent_port", "+", "\"]\"", ")", "if", "red_hat_firewall_d_exception_for_omsagent", "(", ")", ":", "print_ok", "(", "\"Found exception in the firewalld for the omsagent port.[\"", "+", "agent_port", "+", "\"]\"", ")", "restart_red_hat_firewall_d", "(", ")", "else", ":", "print_warning", "(", "\"Warning: no exception found for omsagent in the firewall\"", ")", "print_warning", "(", "\"You can add exception for the agent port[\"", "+", "agent_port", "+", "\"] by using the following commands:\"", ")", "print_warning", "(", "\"Add exception:\"", ")", "print_notice", "(", "\"sudo firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport \"", "+", "agent_port", "+", "\" -j ACCEPT\"", ")", "print_warning", "(", "\"Validate the exception was added in the configuration:\"", ")", "print_notice", "(", "\"sudo firewall-cmd --direct --get-rules ipv4 filter INPUT\"", ")", "print_warning", "(", "\"Reload the firewall:\"", ")", "print_notice", "(", "\"sudo firewall-cmd --reload\"", ")", "print_warning", "(", "\"You can disable your firewall by using this command - not recommended:\"", ")", "print_notice", "(", "\"sudo systemctl stop firewalld\"", ")" ]
[ 93, 0 ]
[ 126, 61 ]
python
en
['en', 'ja', 'th']
False
red_hat_firewall_d_exception_for_omsagent
()
Check that the firewall_d has an exception for the omsagent :return:
Check that the firewall_d has an exception for the omsagent :return:
def red_hat_firewall_d_exception_for_omsagent(): ''' Check that the firewall_d has an exception for the omsagent :return: ''' print("Checking for exception for omsagent") print_notice(firewall_d_exception_configuration_file) firewall_status = subprocess.Popen(["sudo", "cat", firewall_d_exception_configuration_file], stdout=subprocess.PIPE) o, e = firewall_status.communicate() if e is not None: print_error("Error: could not get /etc/firewalld/zones/public.xml file holding firewall exceptions") print_command_response(str(o)) return agent_port in str(o)
[ "def", "red_hat_firewall_d_exception_for_omsagent", "(", ")", ":", "print", "(", "\"Checking for exception for omsagent\"", ")", "print_notice", "(", "firewall_d_exception_configuration_file", ")", "firewall_status", "=", "subprocess", ".", "Popen", "(", "[", "\"sudo\"", ",", "\"cat\"", ",", "firewall_d_exception_configuration_file", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "firewall_status", ".", "communicate", "(", ")", "if", "e", "is", "not", "None", ":", "print_error", "(", "\"Error: could not get /etc/firewalld/zones/public.xml file holding firewall exceptions\"", ")", "print_command_response", "(", "str", "(", "o", ")", ")", "return", "agent_port", "in", "str", "(", "o", ")" ]
[ 129, 0 ]
[ 141, 31 ]
python
en
['en', 'ja', 'th']
False
restart_red_hat_firewall_d
()
Method for restarting the firewall_d :return:
Method for restarting the firewall_d :return:
def restart_red_hat_firewall_d(): ''' Method for restarting the firewall_d :return: ''' print("Trying to restart firewall_d") print_notice("sudo firewall-cmd --reload") restart = subprocess.Popen(["sudo", "firewall-cmd", "--reload"], stdout=subprocess.PIPE) o, e = restart.communicate() time.sleep(2) if e is not None: print_error("Error: could not get /etc/firewalld/zones/public.xml file holding firewall exceptions.") else: print_ok("Restarted firewalld.")
[ "def", "restart_red_hat_firewall_d", "(", ")", ":", "print", "(", "\"Trying to restart firewall_d\"", ")", "print_notice", "(", "\"sudo firewall-cmd --reload\"", ")", "restart", "=", "subprocess", ".", "Popen", "(", "[", "\"sudo\"", ",", "\"firewall-cmd\"", ",", "\"--reload\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "restart", ".", "communicate", "(", ")", "time", ".", "sleep", "(", "2", ")", "if", "e", "is", "not", "None", ":", "print_error", "(", "\"Error: could not get /etc/firewalld/zones/public.xml file holding firewall exceptions.\"", ")", "else", ":", "print_ok", "(", "\"Restarted firewalld.\"", ")" ]
[ 144, 0 ]
[ 157, 40 ]
python
en
['en', 'ja', 'th']
False
rsyslog_get_cef_log_counter
()
Count using tac and wc -l the amount of CEF messages arrived and see it is in increasing count :return:
Count using tac and wc -l the amount of CEF messages arrived and see it is in increasing count :return:
def rsyslog_get_cef_log_counter(): ''' Count using tac and wc -l the amount of CEF messages arrived and see it is in increasing count :return: ''' print("Validating the CEF\\ASA logs are received and are in the correct format when received by syslog daemon") print_notice("sudo tac /var/log/syslog") tac = subprocess.Popen(["sudo", "tac", syslog_log_dir[0]], stdout=subprocess.PIPE) grep = subprocess.Popen(["grep", "-E", "CEF\|ASA"], stdin=tac.stdout, stdout=subprocess.PIPE) count_lines = subprocess.Popen(["wc", "-l"], stdin=grep.stdout, stdout=subprocess.PIPE) o, e = count_lines.communicate() output = o.decode(encoding='UTF-8') if e is None: print("Located " + str(output) + " CEF\\ASA messages") return int(output) elif "No such file or directory" in output: print("Validating the CEF\\ASA logs are received and are in the correct format when received by syslog daemon") print_notice("sudo tac /var/log/messages") tac = subprocess.Popen(["sudo", "tac", syslog_log_dir[1]], stdout=subprocess.PIPE) grep = subprocess.Popen(["grep", "-E", "CEF\|ASA"], stdin=tac.stdout, stdout=subprocess.PIPE) count_lines = subprocess.Popen(["wc", "-l"], stdin=grep.stdout, stdout=subprocess.PIPE) o, e = count_lines.communicate() output = o.decode(encoding='UTF-8') if e is None: print("Located " + str(output) + " CEF messages") return int(output) print_error("Error: could not find CEF\\ASA logs.") print_notice("Notice: execute \"sudo tac /var/log/syslog or /var/log/messages | grep -E \"CEF|ASA\" -m 10\" manually.") return 0
[ "def", "rsyslog_get_cef_log_counter", "(", ")", ":", "print", "(", "\"Validating the CEF\\\\ASA logs are received and are in the correct format when received by syslog daemon\"", ")", "print_notice", "(", "\"sudo tac /var/log/syslog\"", ")", "tac", "=", "subprocess", ".", "Popen", "(", "[", "\"sudo\"", ",", "\"tac\"", ",", "syslog_log_dir", "[", "0", "]", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "grep", "=", "subprocess", ".", "Popen", "(", "[", "\"grep\"", ",", "\"-E\"", ",", "\"CEF\\|ASA\"", "]", ",", "stdin", "=", "tac", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "count_lines", "=", "subprocess", ".", "Popen", "(", "[", "\"wc\"", ",", "\"-l\"", "]", ",", "stdin", "=", "grep", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "count_lines", ".", "communicate", "(", ")", "output", "=", "o", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", "if", "e", "is", "None", ":", "print", "(", "\"Located \"", "+", "str", "(", "output", ")", "+", "\" CEF\\\\ASA messages\"", ")", "return", "int", "(", "output", ")", "elif", "\"No such file or directory\"", "in", "output", ":", "print", "(", "\"Validating the CEF\\\\ASA logs are received and are in the correct format when received by syslog daemon\"", ")", "print_notice", "(", "\"sudo tac /var/log/messages\"", ")", "tac", "=", "subprocess", ".", "Popen", "(", "[", "\"sudo\"", ",", "\"tac\"", ",", "syslog_log_dir", "[", "1", "]", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "grep", "=", "subprocess", ".", "Popen", "(", "[", "\"grep\"", ",", "\"-E\"", ",", "\"CEF\\|ASA\"", "]", ",", "stdin", "=", "tac", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "count_lines", "=", "subprocess", ".", "Popen", "(", "[", "\"wc\"", ",", "\"-l\"", "]", ",", "stdin", "=", "grep", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "count_lines", ".", "communicate", "(", ")", "output", "=", "o", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", "if", "e", "is", "None", ":", "print", "(", "\"Located \"", "+", "str", "(", "output", ")", "+", "\" CEF messages\"", ")", "return", "int", "(", "output", ")", "print_error", "(", "\"Error: could not find CEF\\\\ASA logs.\"", ")", "print_notice", "(", "\"Notice: execute \\\"sudo tac /var/log/syslog or /var/log/messages | grep -E \\\"CEF|ASA\\\" -m 10\\\" manually.\"", ")", "return", "0" ]
[ 189, 0 ]
[ 218, 12 ]
python
en
['en', 'ja', 'th']
False
incoming_logs_validations
(incoming_port, ok_message, mock_message=False)
Validate that there is incoming traffic of CEF messages to the given port :param mock_message: Tells if to mock messages into the tcpdump :param mock_messages: Tels if to send mock messages to the pipe to validate it :param incoming_port: port to validate :param ok_message: message printed if found CEF messages :return:
Validate that there is incoming traffic of CEF messages to the given port :param mock_message: Tells if to mock messages into the tcpdump :param mock_messages: Tels if to send mock messages to the pipe to validate it :param incoming_port: port to validate :param ok_message: message printed if found CEF messages :return:
def incoming_logs_validations(incoming_port, ok_message, mock_message=False): ''' Validate that there is incoming traffic of CEF messages to the given port :param mock_message: Tells if to mock messages into the tcpdump :param mock_messages: Tels if to send mock messages to the pipe to validate it :param incoming_port: port to validate :param ok_message: message printed if found CEF messages :return: ''' start_seconds = int(round(time.time())) end_seconds = int(round(time.time())) print("This will take " + str(tcpdump_time_restriction) + " seconds.") command_tokens = ["sudo", "tcpdump", "-A", "-ni", "any", "port", incoming_port, "-vv"] print_notice(" ".join(command_tokens)) tcp_dump = subprocess.Popen(command_tokens, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) poll_obj = select.poll() poll_obj.register(tcp_dump.stdout, select.POLLIN) while (end_seconds - start_seconds) < tcpdump_time_restriction: if mock_message is True: # Sending mock messages send_cef_message_local(daemon_port, 1) poll_result = poll_obj.poll(0) if poll_result: line = str(tcp_dump.stdout.readline()) if handle_tcpdump_line(line, incoming_port, ok_message): return True end_seconds = int(round(time.time())) print_error("Could not locate \"CEF\" message in tcpdump") return False
[ "def", "incoming_logs_validations", "(", "incoming_port", ",", "ok_message", ",", "mock_message", "=", "False", ")", ":", "start_seconds", "=", "int", "(", "round", "(", "time", ".", "time", "(", ")", ")", ")", "end_seconds", "=", "int", "(", "round", "(", "time", ".", "time", "(", ")", ")", ")", "print", "(", "\"This will take \"", "+", "str", "(", "tcpdump_time_restriction", ")", "+", "\" seconds.\"", ")", "command_tokens", "=", "[", "\"sudo\"", ",", "\"tcpdump\"", ",", "\"-A\"", ",", "\"-ni\"", ",", "\"any\"", ",", "\"port\"", ",", "incoming_port", ",", "\"-vv\"", "]", "print_notice", "(", "\" \"", ".", "join", "(", "command_tokens", ")", ")", "tcp_dump", "=", "subprocess", ".", "Popen", "(", "command_tokens", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "poll_obj", "=", "select", ".", "poll", "(", ")", "poll_obj", ".", "register", "(", "tcp_dump", ".", "stdout", ",", "select", ".", "POLLIN", ")", "while", "(", "end_seconds", "-", "start_seconds", ")", "<", "tcpdump_time_restriction", ":", "if", "mock_message", "is", "True", ":", "# Sending mock messages\r", "send_cef_message_local", "(", "daemon_port", ",", "1", ")", "poll_result", "=", "poll_obj", ".", "poll", "(", "0", ")", "if", "poll_result", ":", "line", "=", "str", "(", "tcp_dump", ".", "stdout", ".", "readline", "(", ")", ")", "if", "handle_tcpdump_line", "(", "line", ",", "incoming_port", ",", "ok_message", ")", ":", "return", "True", "end_seconds", "=", "int", "(", "round", "(", "time", ".", "time", "(", ")", ")", ")", "print_error", "(", "\"Could not locate \\\"CEF\\\" message in tcpdump\"", ")", "return", "False" ]
[ 253, 0 ]
[ 281, 16 ]
python
en
['en', 'ja', 'th']
False
check_file_in_directory
(file_name, path)
Check if the given file is found in the current directory. :param path: :param file_name: :return: return True if it is found elsewhere False
Check if the given file is found in the current directory. :param path: :param file_name: :return: return True if it is found elsewhere False
def check_file_in_directory(file_name, path): ''' Check if the given file is found in the current directory. :param path: :param file_name: :return: return True if it is found elsewhere False ''' current_dir = subprocess.Popen(["ls", "-ltrh", path], stdout=subprocess.PIPE) grep = subprocess.Popen(["grep", "-i", file_name], stdin=current_dir.stdout, stdout=subprocess.PIPE) o, e = grep.communicate() output = o.decode(encoding='UTF-8') if e is None and file_name in output: return True return False
[ "def", "check_file_in_directory", "(", "file_name", ",", "path", ")", ":", "current_dir", "=", "subprocess", ".", "Popen", "(", "[", "\"ls\"", ",", "\"-ltrh\"", ",", "path", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "grep", "=", "subprocess", ".", "Popen", "(", "[", "\"grep\"", ",", "\"-i\"", ",", "file_name", "]", ",", "stdin", "=", "current_dir", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "grep", ".", "communicate", "(", ")", "output", "=", "o", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", "if", "e", "is", "None", "and", "file_name", "in", "output", ":", "return", "True", "return", "False" ]
[ 298, 0 ]
[ 311, 16 ]
python
en
['en', 'ja', 'th']
False
locate_check
(process_name)
Check if the process_name is installed using the locate command :param process_name:onfiguration under the nam :return: True if locate has returned a valid value else False
Check if the process_name is installed using the locate command :param process_name:onfiguration under the nam :return: True if locate has returned a valid value else False
def locate_check(process_name): ''' Check if the process_name is installed using the locate command :param process_name:onfiguration under the nam :return: True if locate has returned a valid value else False ''' try: print("Trying to use the \'locate\' command to locate " + process_name) locate = subprocess.Popen(["locate", process_name], stdout=subprocess.PIPE) o, e = locate.communicate() response = o.decode(encoding='UTF-8') if e is not None: print_warning("Warning: Could not execute \'locate\' command.") print_notice( "Notice: To install locate command - \"sudo yum install mlocate[On CentOS/RHEL]\" or \"sudo apt" " install mlocate[On Debian/Ubuntu] \"") elif response == "": print_error("Error: Could not locate \'omsagent\' trying to validate by checking the process.\n") return False else: print_ok("Located \'omsagent\'") return True except OSError: print_warning("Warning: Could not execute \'locate\' command.") print_notice("Notice: To install locate command - \"sudo yum install mlocate[On CentOS/RHEL]\" or \"sudo apt" " install mlocate[On Debian/Ubuntu] \"")
[ "def", "locate_check", "(", "process_name", ")", ":", "try", ":", "print", "(", "\"Trying to use the \\'locate\\' command to locate \"", "+", "process_name", ")", "locate", "=", "subprocess", ".", "Popen", "(", "[", "\"locate\"", ",", "process_name", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "locate", ".", "communicate", "(", ")", "response", "=", "o", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", "if", "e", "is", "not", "None", ":", "print_warning", "(", "\"Warning: Could not execute \\'locate\\' command.\"", ")", "print_notice", "(", "\"Notice: To install locate command - \\\"sudo yum install mlocate[On CentOS/RHEL]\\\" or \\\"sudo apt\"", "\" install mlocate[On Debian/Ubuntu] \\\"\"", ")", "elif", "response", "==", "\"\"", ":", "print_error", "(", "\"Error: Could not locate \\'omsagent\\' trying to validate by checking the process.\\n\"", ")", "return", "False", "else", ":", "print_ok", "(", "\"Located \\'omsagent\\'\"", ")", "return", "True", "except", "OSError", ":", "print_warning", "(", "\"Warning: Could not execute \\'locate\\' command.\"", ")", "print_notice", "(", "\"Notice: To install locate command - \\\"sudo yum install mlocate[On CentOS/RHEL]\\\" or \\\"sudo apt\"", "\" install mlocate[On Debian/Ubuntu] \\\"\"", ")" ]
[ 314, 0 ]
[ 339, 61 ]
python
en
['en', 'ja', 'th']
False
process_check
(process_name)
function who check using the ps -ef command if the 'process_name' is running :param process_name: :return: True if the process is running else False
function who check using the ps -ef command if the 'process_name' is running :param process_name: :return: True if the process is running else False
def process_check(process_name): ''' function who check using the ps -ef command if the 'process_name' is running :param process_name: :return: True if the process is running else False ''' p1 = subprocess.Popen(["ps", "-ef"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["grep", "-i", process_name], stdin=p1.stdout, stdout=subprocess.PIPE) o, e = p2.communicate() tokens = o.decode(encoding='UTF-8').split('\n') tokens.remove('') return tokens
[ "def", "process_check", "(", "process_name", ")", ":", "p1", "=", "subprocess", ".", "Popen", "(", "[", "\"ps\"", ",", "\"-ef\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "p2", "=", "subprocess", ".", "Popen", "(", "[", "\"grep\"", ",", "\"-i\"", ",", "process_name", "]", ",", "stdin", "=", "p1", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "o", ",", "e", "=", "p2", ".", "communicate", "(", ")", "tokens", "=", "o", ".", "decode", "(", "encoding", "=", "'UTF-8'", ")", ".", "split", "(", "'\\n'", ")", "tokens", ".", "remove", "(", "''", ")", "return", "tokens" ]
[ 353, 0 ]
[ 364, 17 ]
python
en
['en', 'ja', 'th']
False
check_oms_agent_status
()
Checking if the OMS agent is installed and running this is done by: 1. using the locate command if one is installed 2. using pe -ef - will check if the agent is running :return: True if the process is installed and/or running false elsewhere
Checking if the OMS agent is installed and running this is done by: 1. using the locate command if one is installed 2. using pe -ef - will check if the agent is running :return: True if the process is installed and/or running false elsewhere
def check_oms_agent_status(): ''' Checking if the OMS agent is installed and running this is done by: 1. using the locate command if one is installed 2. using pe -ef - will check if the agent is running :return: True if the process is installed and/or running false elsewhere ''' agent_name = "omsagent" is_located = locate_check(agent_name) is_process_running = process_check(agent_name) if not is_located and not is_process_running: print_error("Error: Oms agent is not installed or running on this machine") return False else: return True
[ "def", "check_oms_agent_status", "(", ")", ":", "agent_name", "=", "\"omsagent\"", "is_located", "=", "locate_check", "(", "agent_name", ")", "is_process_running", "=", "process_check", "(", "agent_name", ")", "if", "not", "is_located", "and", "not", "is_process_running", ":", "print_error", "(", "\"Error: Oms agent is not installed or running on this machine\"", ")", "return", "False", "else", ":", "return", "True" ]
[ 367, 0 ]
[ 383, 19 ]
python
en
['en', 'ja', 'th']
False
test_daemon_configuration
(daemon_name)
Checking if the daemon configuration file and folder exists :param daemon_name: :return: True if exists
Checking if the daemon configuration file and folder exists :param daemon_name: :return: True if exists
def test_daemon_configuration(daemon_name): ''' Checking if the daemon configuration file and folder exists :param daemon_name: :return: True if exists ''' print("Testing if the daemon configuration folder exists") is_daemon_dir_exists = check_file_in_directory(daemon_name, "/etc/") if not is_daemon_dir_exists: print_error("Could not locate " + daemon_name + " directory.[under \'/etc/\']") return False print_ok("Located /etc/" + daemon_name + " directory.") print("Checking omsagent configuration under the name of: \'security-config-omsagent.conf\'") config_exists = check_file_in_directory("security-config-omsagent.conf", rsyslog_daemon_forwarding_configuration_dir_path if daemon_name == rsyslog_daemon_name else syslog_ng_daemon_forwarding_configuration_dir_path) if not config_exists: print_error("security-config-omsagent.conf does not exists in " + daemon_name + " directory") return False else: print_ok("Located security-config-omsagent.conf") return True
[ "def", "test_daemon_configuration", "(", "daemon_name", ")", ":", "print", "(", "\"Testing if the daemon configuration folder exists\"", ")", "is_daemon_dir_exists", "=", "check_file_in_directory", "(", "daemon_name", ",", "\"/etc/\"", ")", "if", "not", "is_daemon_dir_exists", ":", "print_error", "(", "\"Could not locate \"", "+", "daemon_name", "+", "\" directory.[under \\'/etc/\\']\"", ")", "return", "False", "print_ok", "(", "\"Located /etc/\"", "+", "daemon_name", "+", "\" directory.\"", ")", "print", "(", "\"Checking omsagent configuration under the name of: \\'security-config-omsagent.conf\\'\"", ")", "config_exists", "=", "check_file_in_directory", "(", "\"security-config-omsagent.conf\"", ",", "rsyslog_daemon_forwarding_configuration_dir_path", "if", "daemon_name", "==", "rsyslog_daemon_name", "else", "syslog_ng_daemon_forwarding_configuration_dir_path", ")", "if", "not", "config_exists", ":", "print_error", "(", "\"security-config-omsagent.conf does not exists in \"", "+", "daemon_name", "+", "\" directory\"", ")", "return", "False", "else", ":", "print_ok", "(", "\"Located security-config-omsagent.conf\"", ")", "return", "True" ]
[ 410, 0 ]
[ 430, 19 ]
python
en
['en', 'ja', 'th']
False
SessionInterface.make_null_session
(self, app)
Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of :attr:`null_session_class` by default.
Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed.
def make_null_session(self, app): """Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of :attr:`null_session_class` by default. """ return self.null_session_class()
[ "def", "make_null_session", "(", "self", ",", "app", ")", ":", "return", "self", ".", "null_session_class", "(", ")" ]
[ 180, 4 ]
[ 190, 40 ]
python
en
['en', 'en', 'en']
True
SessionInterface.is_null_session
(self, obj)
Checks if a given object is a null session. Null sessions are not asked to be saved. This checks if the object is an instance of :attr:`null_session_class` by default.
Checks if a given object is a null session. Null sessions are not asked to be saved.
def is_null_session(self, obj): """Checks if a given object is a null session. Null sessions are not asked to be saved. This checks if the object is an instance of :attr:`null_session_class` by default. """ return isinstance(obj, self.null_session_class)
[ "def", "is_null_session", "(", "self", ",", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "self", ".", "null_session_class", ")" ]
[ 192, 4 ]
[ 199, 55 ]
python
en
['en', 'en', 'en']
True
SessionInterface.get_cookie_domain
(self, app)
Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used.
Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used.
def get_cookie_domain(self, app): """Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used. """ if app.config['SESSION_COOKIE_DOMAIN'] is not None: return app.config['SESSION_COOKIE_DOMAIN'] if app.config['SERVER_NAME'] is not None: # chop off the port which is usually not supported by browsers rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] # Google chrome does not like cookies set to .localhost, so # we just go with no domain then. Flask documents anyways that # cross domain cookies need a fully qualified domain name if rv == '.localhost': rv = None # If we infer the cookie domain from the server name we need # to check if we are in a subpath. In that case we can't # set a cross domain cookie. if rv is not None: path = self.get_cookie_path(app) if path != '/': rv = rv.lstrip('.') return rv
[ "def", "get_cookie_domain", "(", "self", ",", "app", ")", ":", "if", "app", ".", "config", "[", "'SESSION_COOKIE_DOMAIN'", "]", "is", "not", "None", ":", "return", "app", ".", "config", "[", "'SESSION_COOKIE_DOMAIN'", "]", "if", "app", ".", "config", "[", "'SERVER_NAME'", "]", "is", "not", "None", ":", "# chop off the port which is usually not supported by browsers", "rv", "=", "'.'", "+", "app", ".", "config", "[", "'SERVER_NAME'", "]", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "0", "]", "# Google chrome does not like cookies set to .localhost, so", "# we just go with no domain then. Flask documents anyways that", "# cross domain cookies need a fully qualified domain name", "if", "rv", "==", "'.localhost'", ":", "rv", "=", "None", "# If we infer the cookie domain from the server name we need", "# to check if we are in a subpath. In that case we can't", "# set a cross domain cookie.", "if", "rv", "is", "not", "None", ":", "path", "=", "self", ".", "get_cookie_path", "(", "app", ")", "if", "path", "!=", "'/'", ":", "rv", "=", "rv", ".", "lstrip", "(", "'.'", ")", "return", "rv" ]
[ 201, 4 ]
[ 225, 21 ]
python
en
['en', 'en', 'en']
True
SessionInterface.get_cookie_path
(self, app)
Returns the path for which the cookie should be valid. The default implementation uses the value from the ``SESSION_COOKIE_PATH`` config var if it's set, and falls back to ``APPLICATION_ROOT`` or uses ``/`` if it's ``None``.
Returns the path for which the cookie should be valid. The default implementation uses the value from the ``SESSION_COOKIE_PATH`` config var if it's set, and falls back to ``APPLICATION_ROOT`` or uses ``/`` if it's ``None``.
def get_cookie_path(self, app): """Returns the path for which the cookie should be valid. The default implementation uses the value from the ``SESSION_COOKIE_PATH`` config var if it's set, and falls back to ``APPLICATION_ROOT`` or uses ``/`` if it's ``None``. """ return app.config['SESSION_COOKIE_PATH'] or \ app.config['APPLICATION_ROOT'] or '/'
[ "def", "get_cookie_path", "(", "self", ",", "app", ")", ":", "return", "app", ".", "config", "[", "'SESSION_COOKIE_PATH'", "]", "or", "app", ".", "config", "[", "'APPLICATION_ROOT'", "]", "or", "'/'" ]
[ 227, 4 ]
[ 234, 52 ]
python
en
['en', 'en', 'en']
True
SessionInterface.get_cookie_httponly
(self, app)
Returns True if the session cookie should be httponly. This currently just returns the value of the ``SESSION_COOKIE_HTTPONLY`` config var.
Returns True if the session cookie should be httponly. This currently just returns the value of the ``SESSION_COOKIE_HTTPONLY`` config var.
def get_cookie_httponly(self, app): """Returns True if the session cookie should be httponly. This currently just returns the value of the ``SESSION_COOKIE_HTTPONLY`` config var. """ return app.config['SESSION_COOKIE_HTTPONLY']
[ "def", "get_cookie_httponly", "(", "self", ",", "app", ")", ":", "return", "app", ".", "config", "[", "'SESSION_COOKIE_HTTPONLY'", "]" ]
[ 236, 4 ]
[ 241, 52 ]
python
en
['en', 'en', 'en']
True
SessionInterface.get_cookie_secure
(self, app)
Returns True if the cookie should be secure. This currently just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
Returns True if the cookie should be secure. This currently just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
def get_cookie_secure(self, app): """Returns True if the cookie should be secure. This currently just returns the value of the ``SESSION_COOKIE_SECURE`` setting. """ return app.config['SESSION_COOKIE_SECURE']
[ "def", "get_cookie_secure", "(", "self", ",", "app", ")", ":", "return", "app", ".", "config", "[", "'SESSION_COOKIE_SECURE'", "]" ]
[ 243, 4 ]
[ 247, 50 ]
python
en
['en', 'en', 'en']
True
SessionInterface.get_expiration_time
(self, app, session)
A helper method that returns an expiration date for the session or ``None`` if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.
A helper method that returns an expiration date for the session or ``None`` if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.
def get_expiration_time(self, app, session): """A helper method that returns an expiration date for the session or ``None`` if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application. """ if session.permanent: return datetime.utcnow() + app.permanent_session_lifetime
[ "def", "get_expiration_time", "(", "self", ",", "app", ",", "session", ")", ":", "if", "session", ".", "permanent", ":", "return", "datetime", ".", "utcnow", "(", ")", "+", "app", ".", "permanent_session_lifetime" ]
[ 249, 4 ]
[ 256, 69 ]
python
en
['en', 'en', 'en']
True
SessionInterface.should_set_cookie
(self, app, session)
Indicates whether a cookie should be set now or not. This is used by session backends to figure out if they should emit a set-cookie header or not. The default behavior is controlled by the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If it's set to ``False`` then a cookie is only set if the session is modified, if set to ``True`` it's always set if the session is permanent. This check is usually skipped if sessions get deleted. .. versionadded:: 0.11
Indicates whether a cookie should be set now or not. This is used by session backends to figure out if they should emit a set-cookie header or not. The default behavior is controlled by the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If it's set to ``False`` then a cookie is only set if the session is modified, if set to ``True`` it's always set if the session is permanent.
def should_set_cookie(self, app, session): """Indicates whether a cookie should be set now or not. This is used by session backends to figure out if they should emit a set-cookie header or not. The default behavior is controlled by the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If it's set to ``False`` then a cookie is only set if the session is modified, if set to ``True`` it's always set if the session is permanent. This check is usually skipped if sessions get deleted. .. versionadded:: 0.11 """ if session.modified: return True save_each = app.config['SESSION_REFRESH_EACH_REQUEST'] return save_each and session.permanent
[ "def", "should_set_cookie", "(", "self", ",", "app", ",", "session", ")", ":", "if", "session", ".", "modified", ":", "return", "True", "save_each", "=", "app", ".", "config", "[", "'SESSION_REFRESH_EACH_REQUEST'", "]", "return", "save_each", "and", "session", ".", "permanent" ]
[ 258, 4 ]
[ 274, 46 ]
python
en
['en', 'en', 'en']
True
SessionInterface.open_session
(self, app, request)
This method has to be implemented and must either return ``None`` in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on :class:`SessionMixin`.
This method has to be implemented and must either return ``None`` in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on :class:`SessionMixin`.
def open_session(self, app, request): """This method has to be implemented and must either return ``None`` in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on :class:`SessionMixin`. """ raise NotImplementedError()
[ "def", "open_session", "(", "self", ",", "app", ",", "request", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 276, 4 ]
[ 282, 35 ]
python
en
['en', 'en', 'en']
True
SessionInterface.save_session
(self, app, session, response)
This is called for actual sessions returned by :meth:`open_session` at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
This is called for actual sessions returned by :meth:`open_session` at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
def save_session(self, app, session, response): """This is called for actual sessions returned by :meth:`open_session` at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that. """ raise NotImplementedError()
[ "def", "save_session", "(", "self", ",", "app", ",", "session", ",", "response", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 284, 4 ]
[ 290, 35 ]
python
en
['en', 'en', 'en']
True