docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Get a texture by label
Args:
label (str): The label for the texture to fetch
Returns:
Texture instance | def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray,
moderngl.Texture3D, moderngl.TextureCube]:
return self._get_resource(label, self._textures, "texture") | 529,387 |
Get a data resource by label
Args:
label (str): The labvel for the data resource to fetch
Returns:
The requeted data object | def get_data(self, label: str) -> Any:
return self._get_resource(label, self._data, "data") | 529,388 |
Generic resoure fetcher handling errors.
Args:
label (str): The label to fetch
source (dict): The dictionary to look up the label
resource_type str: The display name of the resource type (used in errors) | def _get_resource(self, label: str, source: dict, resource_type: str):
try:
return source[label]
except KeyError:
raise ValueError("Cannot find {0} with label '{1}'.\nExisting {0} labels: {2}".format(
resource_type, label, list(source.keys()))) | 529,389 |
Return features corresponding to segment as list of (value,
feature) tuples
Args:
segment (unicode): segment for which features are to be returned as
Unicode string
Returns:
list: None if `segment` cannot be parsed; otherwise, a list of th... | def fts(self, segment):
match = self.seg_regex.match(segment)
if match:
pre, base, post = match.group('pre'), match.group('base'), match.group('post')
seg = copy.deepcopy(self.bases[base])
for m in reversed(pre):
seg = update_ft_set(seg, self.... | 530,920 |
Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (consonant or
vowel)
Returns:
... | def fts_match(self, fts_mask, segment):
fts_mask = set(fts_mask)
fts_seg = self.fts(segment)
if fts_seg:
return fts_seg <= fts_mask
else:
return None | 530,921 |
Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word` | def longest_one_seg_prefix(self, word):
match = self.seg_regex.match(word)
if match:
return match.group(0)
else:
return '' | 530,922 |
Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
... | def filter_segs(self, segs):
def whole_seg(seg):
m = self.seg_regex.match(seg)
if m and m.group(0) == seg:
return True
else:
return False
return list(filter(whole_seg, segs)) | 530,923 |
Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segments in the input text | def segment_text(text, seg_regex=SEG_REGEX):
for m in seg_regex.finditer(text):
yield m.group(0) | 530,931 |
Given a string `p` with feature matrices (features grouped with square
brackets into segments, return a list of sets of (value, feature) tuples.
Args:
p (str): list of feature matrices as strings
Return:
list: list of sets of (value, feature) tuples | def pat(p):
pattern = []
for matrix in [m.group(0) for m in MT_REGEX.finditer(p)]:
segment = set([m.groups() for m in FT_REGEX.finditer(matrix)])
pattern.append(segment)
return pattern | 530,932 |
Construct a FeatureTable object
Args:
feature_set (str): the feature set that the FeatureTable will use;
currently, there is only one of these ("spe+") | def __init__(self, feature_set='spe+'):
filename = filenames[feature_set]
self.segments, self.seg_dict, self.names = self._read_table(filename)
self.seg_seq = {seg[0]: i for (i, seg) in enumerate(self.segments)}
self.weights = self._read_weights()
self.seg_regex = self._... | 530,934 |
Return longest Unicode IPA prefix of a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
unicode: longest single-segment prefix of `word` in database | def longest_one_seg_prefix(self, word):
for i in range(self.longest_seg, 0, -1):
if word[:i] in self.seg_dict:
return word[:i]
return '' | 530,938 |
Returns True if `word` consists exhaustively of valid IPA segments
Args:
word (unicode): input word as Unicode IPA string
Returns:
bool: True if `word` can be divided exhaustively into IPA segments
that exist in the database | def validate_word(self, word):
while word:
match = self.seg_regex.match(word)
if match:
word = word[len(match.group(0)):]
else:
# print('{}\t->\t{}\t'.format(orig, word).encode('utf-8'), file=sys.stderr)
return False
... | 530,939 |
Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word` | def segs(self, word):
return [m.group('all') for m in self.seg_regex.finditer(word)] | 530,940 |
Return featural analysis of `word`
Args:
word (unicode): one or more IPA segments
Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word` | def word_fts(self, word):
return list(map(self.fts, self.segs(word))) | 530,941 |
Return a list of segments (as strings) from a word
Characters that are not valid segments are included in the list as
individual characters.
Args:
word (unicode): word as an IPA string
Returns:
list: list of Unicode IPA strings corresponding to segments in
... | def segs_safe(self, word):
segs = []
while word:
m = self.seg_regex.match(word)
if m:
segs.append(m.group(1))
word = word[len(m.group(1)):]
else:
segs.append(word[0])
word = word[1:]
retu... | 530,942 |
Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent | def filter_string(self, word):
segs = [m.group(0) for m in self.seg_regex.finditer(word)]
return ''.join(segs) | 530,943 |
Return the features shared by `segs`
Args:
segs (list): list of Unicode IPA segments
Returns:
set: set of (value, feature) tuples shared by the valid segments in
`segs` | def fts_intersection(self, segs):
fts_vecs = [self.fts(s) for s in self.filter_segs(segs)]
return reduce(lambda a, b: a & b, fts_vecs) | 530,944 |
Return `True` if any segment in `inv` matches the features in `fts`
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if any segment in `inv... | def fts_match_any(self, fts, inv):
return any([self.fts_match(fts, s) for s in inv]) | 530,945 |
Return `True` if all segments in `inv` matches the features in fts
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if all segments in `inv... | def fts_match_all(self, fts, inv):
return all([self.fts_match(fts, s) for s in inv]) | 530,946 |
Return `True` if there is a segment in `inv` that contrasts in feature
`ft_name`.
Args:
fs (list): feature specifications used to filter `inv`.
ft_name (str): name of the feature where contrast must be present.
inv (list): collection of segments represented as Unicod... | def fts_contrast2(self, fs, ft_name, inv):
inv_fts = [self.fts(x) for x in inv if set(fs) <= self.fts(x)]
for a in inv_fts:
for b in inv_fts:
if a != b:
diff = a ^ b
if len(diff) == 2:
if all([nm == ft_n... | 530,947 |
Return the count of segments in an inventory matching a given
feature mask.
Args:
fts (set): feature mask given as a set of (value, feature) tuples
inv (set): inventory of segments (as Unicode IPA strings)
Returns:
int: number of segments in `inv` that match... | def fts_count(self, fts, inv):
return len(list(filter(lambda s: self.fts_match(fts, s), inv))) | 530,948 |
Return segments matching a feature mask, both as (value, feature)
tuples (sorted in reverse order by length).
Args:
fts (list): feature mask as (value, feature) tuples.
Returns:
list: segments matching `fts`, sorted in reverse order by length | def all_segs_matching_fts(self, fts):
matching_segs = []
for seg, pairs in self.segments:
if set(fts) <= set(pairs):
matching_segs.append(seg)
return sorted(matching_segs, key=lambda x: len(x), reverse=True) | 530,951 |
Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited by any standard delimiter.
Returns:
... | def compile_regex_from_str(self, ft_str):
sequence = []
for m in re.finditer(r'\[([^]]+)\]', ft_str):
ft_mask = fts(m.group(1))
segs = self.all_segs_matching_fts(ft_mask)
sub_pat = '({})'.format('|'.join(segs))
sequence.append(sub_pat)
pa... | 530,952 |
Given a Unicode IPA segment, return a list of feature specificiations
in cannonical order.
Args:
seg (unicode): IPA consonant or vowel
Returns:
list: feature specifications ('+'/'-'/'0') in the order from
`FeatureTable.names` | def segment_to_vector(self, seg):
ft_dict = {ft: val for (val, ft) in self.fts(seg)}
return [ft_dict[name] for name in self.names] | 530,953 |
Return a list of feature vectors, given a Unicode IPA word.
Args:
word (unicode): string in IPA
numeric (bool): if True, return features as numeric values instead
of strings
Returns:
list: a list of lists of '+'/'-'/'0' or 1/-1/0 | def word_to_vector_list(self, word, numeric=False, xsampa=False):
if xsampa:
word = self.xsampa.convert(word)
tensor = list(map(self.segment_to_vector, self.segs(word)))
if numeric:
return self.tensor_to_numeric(tensor)
else:
return tensor | 530,955 |
Performs Clown Strike lookup on an IoC.
Args:
ioc - An IoC. | def clown_strike_ioc(self, ioc):
r = requests.get('http://threatbutt.io/api', data='ioc={0}'.format(ioc))
self._output(r.text) | 530,957 |
Performs Bespoke MD5 lookup on an MD5.
Args:
md5 - A hash. | def bespoke_md5(self, md5):
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text) | 530,958 |
Construct Segment objectself.
Args:
form (string): the segment as ipa
features (list): the segment as feature_names | def __init__(self, form, features):
self.form = form
self.features = features | 530,965 |
Construct a BoolTree object
Args:
test (bool): test for whether to traverse the true-node or the
false-node (`BoolTree.t_node` or `BoolTree.f_node`)
t_node (BoolTree/Int): node to follow if test is `True`
f_node (BoolTree/Int): node to follow if test... | def __init__(self, test=None, t_node=None, f_node=None):
self.test = test
self.t_node = t_node
self.f_node = f_node | 530,971 |
Construct a Sonority object
Args:
feature_set (str): features set to be used by `FeatureTable`
feature_model (str): 'strict' or 'permissive' feature model | def __init__(self, feature_set='spe+', feature_model='strict'):
fm = {'strict': _panphon.FeatureTable,
'permissive': permissive.PermissiveFeatureTable}
self.fm = fm[feature_model](feature_set=feature_set) | 530,973 |
Given a segment as features, returns the sonority on a scale of 1
to 9.
Args:
seg (list): collection of (value, feature) pairs representing
a segment (vowel or consonant)
Returns:
int: sonority of `seg` between 1 and 9 | def sonority_from_fts(self, seg):
def match(m):
return self.fm.match(fts(m), seg)
minusHi = BoolTree(match('-hi'), 9, 8)
minusNas = BoolTree(match('-nas'), 6, 5)
plusVoi1 = BoolTree(match('+voi'), 4, 3)
plusVoi2 = BoolTree(match('+voi'), 2, 1)
plusC... | 530,974 |
Initialize the datastore with given root directory `root`.
Args:
root: A path at which to mount this filesystem datastore. | def __init__(self, root, case_sensitive=True):
root = os.path.normpath(root)
if not root:
errstr = 'root path must not be empty (\'.\' for current directory)'
raise ValueError(errstr)
ensure_directory_exists(root)
self.root_path = root
self.case_sensitive = bool(case_sensitive) | 531,076 |
Return the object named by key or None if it does not exist.
Args:
key: Key naming the object to retrieve
Returns:
object or None | def get(self, key):
path = self.object_path(key)
return self._read_object(path) | 531,082 |
Stores the object `value` named by `key`.
Args:
key: Key naming `value`
value: the object to store. | def put(self, key, value):
path = self.object_path(key)
self._write_object(path, value) | 531,083 |
Removes the object named by `key`.
Args:
key: Key naming the object to remove. | def delete(self, key):
path = self.object_path(key)
if os.path.exists(path):
os.remove(path) | 531,084 |
Returns an iterable of objects matching criteria expressed in `query`
FSDatastore.query queries all the `.obj` files within the directory
specified by the query.key.
Args:
query: Query object describing the objects to return.
Raturns:
Cursor with all objects matching criteria | def query(self, query):
path = self.path(query.key)
if os.path.exists(path):
filenames = os.listdir(path)
filenames = list(set(filenames) - set(self.ignore_list))
filenames = map(lambda f: os.path.join(path, f), filenames)
iterable = self._read_object_gen(filenames)
else:
... | 531,085 |
Returns whether the object named by `key` exists.
Optimized to only check whether the file object exists.
Args:
key: Key naming the object to check.
Returns:
boalean whether the object exists | def contains(self, key):
path = self.object_path(key)
return os.path.exists(path) and os.path.isfile(path) | 531,086 |
Stores the object `value` named by `key`.
Stores the object in the collection corresponding to ``key.path``.
Args:
key: Key naming `value`
value: the object to store. | def put(self, key, value):
if value is None:
self.delete(key)
else:
self._collection(key)[key] = value | 531,088 |
Removes the object named by `key`.
Removes the object from the collection corresponding to ``key.path``.
Args:
key: Key naming the object to remove. | def delete(self, key):
try:
del self._collection(key)[key]
if len(self._collection(key)) == 0:
del self._items[str(key.path)]
except KeyError, e:
pass | 531,089 |
Returns an iterable of objects matching criteria expressed in `query`
Naively applies the query operations on the objects within the namespaced
collection corresponding to ``query.key.path``.
Args:
query: Query object describing the objects to return.
Raturns:
iterable cursor with all obj... | def query(self, query):
# entire dataset already in memory, so ok to apply query naively
if str(query.key) in self._items:
return query(self._items[str(query.key)].values())
else:
return query([]) | 531,090 |
Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None | def get(self, key):
key = self._service_key(key)
return self._service_ops['get'](key) | 531,092 |
Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store. | def put(self, key, value):
key = self._service_key(key)
self._service_ops['put'](key, value) | 531,093 |
Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove. | def delete(self, key):
key = self._service_key(key)
self._service_ops['delete'](key) | 531,094 |
Initializes internals and tests the serializer.
Args:
datastore: a child datastore for the ShimDatastore superclass.
serializer: a serializer object (responds to loads and dumps). | def __init__(self, datastore, serializer=None):
super(SerializerShimDatastore, self).__init__(datastore)
if serializer:
self.serializer = serializer
# ensure serializer works
test = { 'value': repr(self) }
errstr = 'Serializer error: serialized value does not match original'
assert ... | 531,144 |
Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None | def get(self, key):
value = self.child_datastore.get(key)
return self.deserializedValue(value) | 531,145 |
Stores the object `value` named by `key`.
Serializes values on the way in, and stores the serialized data into the
``child_datastore``.
Args:
key: Key naming `value`
value: the object to store. | def put(self, key, value):
value = self.serializedValue(value)
self.child_datastore.put(key, value) | 531,146 |
Returns an iterable of objects matching criteria expressed in `query`
De-serializes values on the way out, using a :ref:`deserialized_gen` to
avoid incurring the cost of de-serializing all data at once, or ever, if
iteration over results does not finish (subject to order generator
constraint).
Args... | def query(self, query):
# run the query on the child datastore
cursor = self.child_datastore.query(query)
# chain the deserializing generator to the cursor's result set iterable
cursor._iterable = deserialized_gen(self.serializer, cursor._iterable)
return cursor | 531,147 |
Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home') | def order(self, order):
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self | 531,162 |
Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female') | def filter(self, *args):
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return sel... | 531,163 |
Test multiple choice exercise.
Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages
are passed to this function.
Args:
correct (int): the index of the correct answer (should be an instruction). Starts at 1.
msgs (list(str)): a list containing all feed... | def has_chosen(state, correct, msgs):
if not issubclass(type(correct), int):
raise InstructorError(
"Inside `has_chosen()`, the argument `correct` should be an integer."
)
student_process = state.student_process
if not isDefinedInProcess(MC_VAR_NAME, student_process):
... | 535,238 |
Centre and normalize a given array.
Parameters:
----------
img: np.ndarray | def min_max_normalize(img):
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | 536,914 |
Abstract base class for scores.
Args:
score (int, float, bool): A raw value to wrap in a Score class.
related_data (dict, optional): Artifacts to store with the score. | def __init__(self, score, related_data=None):
self.check_score(score)
if related_data is None:
related_data = {}
self.score, self.related_data = score, related_data
if isinstance(score, Exception):
# Set to error score to use its summarize().
... | 537,146 |
Initialization is identical to HighlightingDataCursor except for the
following:
Parameters:
-----------
paired_artists: a sequence of tuples of matplotlib artists
Pairs of matplotlib artists to be highlighted.
Additional keyword arguments are passed on to Hi... | def __init__(self, paired_artists, **kwargs):
# Two-way lookup table
self.artist_map = dict(paired_artists)
self.artist_map.update([pair[::-1] for pair in self.artist_map.items()])
kwargs['display'] = 'single'
artists = self.artist_map.values()
mpldatacursor.Hig... | 537,308 |
Initialize speaker instance, for a set of AST nodes.
Arguments:
nodes: dictionary of node names, and their human friendly names.
Each entry for a node may also be a dictionary containing
name: human friendly name, fields: a dictionary to override
... | def __init__(self, **cfg):
self.node_names = cfg["nodes"]
self.field_names = cfg.get("fields", {}) | 537,351 |
Decodes json into a conjure bean type (a plain bean, not enum
or union).
Args:
obj: the json object to decode
conjure_type: a class object which is the bean type
we're decoding into
Returns:
A instance of a bean of type conjure_type. | def decode_conjure_bean_type(cls, obj, conjure_type):
deserialized = {} # type: Dict[str, Any]
for (python_arg_name, field_definition) \
in conjure_type._fields().items():
field_identifier = field_definition.identifier
if field_identifier not in obj or ... | 539,014 |
Decodes json into a conjure union type.
Args:
obj: the json object to decode
conjure_type: a class object which is the union type
we're decoding into
Returns:
An instance of type conjure_type. | def decode_conjure_union_type(cls, obj, conjure_type):
type_of_union = obj["type"] # type: str
for attr, conjure_field in conjure_type._options().items():
if conjure_field.identifier == type_of_union:
attribute = attr
conjure_field_definition = conju... | 539,016 |
Decodes json into a conjure enum type.
Args:
obj: the json object to decode
conjure_type: a class object which is the enum type
we're decoding into.
Returns:
An instance of enum of type conjure_type. | def decode_conjure_enum_type(cls, obj, conjure_type):
if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"):
raise Exception(
'Expected to find str type but found {} instead'.format(
type(obj)))
if obj in conjure_type.__members__:... | 539,017 |
Decodes json into a list, handling conversion of the elements.
Args:
obj: the json object to decode
element_type: a class object which is the conjure type of
the elements in this list.
Returns:
A python list where the elements are instances of type
... | def decode_list(cls, obj, element_type):
# type: (List[Any], ConjureTypeType) -> List[Any]
if not isinstance(obj, list):
raise Exception("expected a python list")
return list(map(lambda x: cls.do_decode(x, element_type), obj)) | 539,019 |
Decodes json into the specified type
Args:
obj: the json object to decode
element_type: a class object which is the type we're decoding into. | def do_decode(cls, obj, obj_type):
# type: (Any, ConjureTypeType) -> Any
if inspect.isclass(obj_type) and issubclass( # type: ignore
obj_type, ConjureBeanType
):
return cls.decode_conjure_bean_type(obj, obj_type) # type: ignore
elif inspect.isclass... | 539,021 |
Print user-facing information
Arguments:
message (str): Text message for the user | def info(self, message):
info = self.findChild(QtWidgets.QLabel, "Info")
info.setText(message)
# Include message in terminal
self.data["models"]["terminal"].append({
"label": message,
"type": "info"
})
animation = self.data["animation"]... | 539,305 |
Automatically scroll to bottom on each new item added
Arguments:
parent (QtCore.QModelIndex): The model itself, since this is a list
start (int): Start index of item
end (int): End index of item | def rowsInserted(self, parent, start, end):
super(LogView, self).rowsInserted(parent, start, end)
# IMPORTANT: This must be done *after* the superclass to get
# an accurate value of the delegate's height.
self.scrollToBottom() | 539,311 |
Produce `result` from `plugin` and `instance`
:func:`process` shares state with :func:`_iterator` such that
an instance/plugin pair can be fetched and processed in isolation.
Arguments:
plugin (pyblish.api.Plugin): Produce result using plug-in
instance (optional, pyblis... | def _process(self, plugin, instance=None):
self.processing["nextOrder"] = plugin.order
try:
result = pyblish.plugin.process(plugin, self.context, instance)
except Exception as e:
raise Exception("Unknown error: %s" % e)
else:
# Make note o... | 539,321 |
Process current pair and store next pair for next process
Arguments:
until (pyblish.api.Order, optional): Keep fetching next()
until this order, default value is infinity.
on_finished (callable, optional): What to do when finishing,
defaults to doing noth... | def _run(self, until=float("inf"), on_finished=lambda: None):
def on_next():
if self.current_pair == (None, None):
return util.defer(100, on_finished_)
# The magic number 0.5 is the range between
# the various CVEI processing stages;
# e... | 539,322 |
Yield next plug-in and instance to process.
Arguments:
plugins (list): Plug-ins to process
context (pyblish.api.Context): Context to process | def _iterator(self, plugins, context):
test = pyblish.logic.registered_test()
for plug, instance in pyblish.logic.Iterator(plugins, context):
if not plug.active:
continue
if instance is not None and instance.data.get("publish") is False:
... | 539,323 |
Build a new Gourde.
Args:
Either a flask.Flask or the name of the calling module. | def __init__(self, app_or_name, registry=None):
if isinstance(app_or_name, flask.Flask):
self.app = app_or_name
else:
# Convenience constructor.
self.app = flask.Flask(app_or_name)
# Most small applications will work behind a reverse proxy and wil... | 539,942 |
Add a new url route.
Args:
See flask.Flask.add_url_route(). | def add_url_rule(self, route, endpoint, handler):
self.app.add_url_rule(route, endpoint, handler) | 539,950 |
Creates a Emphasized Text Text object
Args:
String message, a string to add to the message
Returns:
None
Raises:
Errors are propagated
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
... | def __init__(self, uri, text=None, **kwargs):
super(Link, self).__init__(**kwargs)
self.uri = uri
self.text = text | 540,450 |
Render as html
Args:
None
Returns:
Str the html representation
Raises:
Errors are propagated | def to_html(self):
text = self.text
if text is None:
text = self.uri
return '<a href="%s"%s>%s</a>' % (
self.uri, self.html_attributes(), text) | 540,451 |
Render a Text MessageElement as html
Args:
None
Returns:
Str the html representation of the Text MessageElement
Raises:
Errors are propagated | def to_html(self):
if self.items is None:
return
else:
html = '<ol%s>\n' % self.html_attributes()
for item in self.items:
html += '<li>%s</li>\n' % item.to_html()
html += '</ol>'
return html | 540,463 |
Render a Text MessageElement as plain text
Args:
None
Returns:
Str the plain text representation of the Text MessageElement
Raises:
Errors are propagated | def to_text(self):
if self.items is None:
return
else:
text = ''
for i, item in enumerate(self.items):
text += ' %s. %s\n' % (i + 1, item.to_text())
return text | 540,464 |
Render as html
Args:
None
Returns:
Str the html representation
Raises:
Errors are propagated
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
http://stackoverflow.com/questions... | def to_html(self, **kwargs):
super(LineBreak, self).__init__(**kwargs)
return '<br%s/>\n' % self.html_attributes() | 540,473 |
Creates an important paragraph object.
Args:
String text, a string to add to the message
Returns:
None
Raises:
Errors are propagated
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
... | def __init__(self, *args, **kwargs):
if 'style_class' in kwargs:
my_class = '%s alert alert-success' % kwargs['style_class']
kwargs['style_class'] = my_class
super(SuccessParagraph, self).__init__(**kwargs)
self.text = Text(*args) | 540,793 |
Render as html
Args:
None
Returns:
Str the html representation
Raises:
Errors are propagated | def to_html(self):
icon = self.html_icon()
attributes = self.html_attributes()
# Deal with long file names that prevent wrapping
wrappable_text = self.to_text().replace(os.sep, '<wbr>' + os.sep)
if icon is not '' and attributes is not '':
return '<span%s>%s%s... | 540,809 |
Creates a Emphasized Text Text object
Args:
String message, a string to add to the message
Returns:
None
Raises:
Errors are propagated
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
... | def __init__(self, text, **kwargs):
super(EmphasizedText, self).__init__(**kwargs)
self.text = text | 541,497 |
Create a Message version of this ErrorMessage
Args:
none
Returns:
the Message instance of this ErrorMessage
Raises:
Errors are propagated | def _render(self):
message = Message()
message.add(Heading(tr('Problem'), **ORANGE_LEVEL_4_STYLE))
message.add(Paragraph(tr(
'The following problem(s) were encountered whilst running the '
'analysis.')))
items = BulletedList()
for p in reversed(se... | 541,613 |
Initialize Class Properties.
Args:
name (str): The value for this security label.
description (str): A description for this security label.
color (str): A color (hex value) for this security label. | def __init__(self, name, description=None, color=None):
self._label_data = {'name': name}
# add description if provided
if description is not None:
self._label_data['description'] = description
if color is not None:
self._label_data['color'] = color | 541,728 |
Initialize Class properties.
Args:
_args (namespace): The argparser args Namespace. | def __init__(self, _args):
super(TcExInit, self).__init__(_args)
# properties
self.base_url = (
'https://raw.githubusercontent.com/ThreatConnect-Inc/tcex/{}/app_init/'
).format(self.args.branch) | 541,729 |
Print the download results.
Args:
file (str): The filename.
status (str): The file download status. | def _print_results(file, status):
file_color = c.Fore.GREEN
status_color = c.Fore.RED
if status == 'Success':
status_color = c.Fore.GREEN
elif status == 'Skipped':
status_color = c.Fore.YELLOW
print(
'{}{!s:<13}{}{!s:<35}{}{!s:<8}{}{}... | 541,730 |
Confirm overwrite of template files.
Make sure the user would like to continue downloading a file which will overwrite a file
in the current directory.
Args:
filename (str): The name of the file to overwrite.
Returns:
bool: True if the user specifies a "yes" re... | def _confirm_overwrite(filename):
message = '{}Would you like to overwrite the contents of {} (y/[n])? '.format(
c.Fore.MAGENTA, filename
)
# 2to3 fixes this for py3
response = raw_input(message) # noqa: F821, pylint: disable=E0602
response = response.lower... | 541,731 |
Download file from github.
Args:
remote_filename (str): The name of the file as defined in git repository.
local_filename (str, optional): Defaults to None. The name of the file as it should be
be written to local filesystem. | def download_file(self, remote_filename, local_filename=None):
status = 'Failed'
if local_filename is None:
local_filename = remote_filename
if not self.args.force and os.access(local_filename, os.F_OK):
if not self._confirm_overwrite(local_filename):
... | 541,733 |
Initialize class properties.
Args:
tcex ([type]): [description]
domain (str): A value of “system”, “organization”, or “local”.
data_type (str): A free form type name for the data.
mapping (dict, optional): Defaults to None. Elasticsearch mappings data.
R... | def __init__(self, tcex, domain, data_type, mapping=None):
self.tcex = tcex
self.domain = domain
self.data_type = data_type
self.mapping = mapping or {'dynamic': False}
# properties
# This module requires a token.
if self.tcex.default_args.tc_token is N... | 541,738 |
Write data to the DataStore. Alias for post() method.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | def add(self, rid, data, raise_on_error=True):
return self.post(rid, data, raise_on_error) | 541,742 |
Update the data for the provided Id.
Args:
rid (str): The record identifier.
data (dict): A search query
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | def put(self, rid, data, raise_on_error=True):
response_data = None
headers = {'Content-Type': 'application/json', 'DB-Method': 'PUT'}
url = '/v2/exchange/db/{}/{}/{}'.format(self.domain, self.data_type, rid)
r = self.tcex.session.post(url, json=data, headers=headers)
se... | 541,743 |
Update the for the provided Id. Alias for put() method.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | def update(self, rid, data, raise_on_error=True):
return self.put(rid, data, raise_on_error) | 541,744 |
Initialize Class properties.
Args:
_args (namespace): The argparser args Namespace. | def __init__(self, _args):
super(TcExRun, self).__init__(_args)
# properties
self._signal_handler_init()
self._config = None
self._profile = {}
self._staging_data = None
self.container = None
self.reports = Reports()
self.tcex = None
... | 541,745 |
Load included configuration files.
Args:
include_directory (str): The name of the config include directory.
Returns:
list: A list of all profiles for the current App. | def _load_config_include(self, include_directory):
include_directory = os.path.join(self.app_path, include_directory)
if not os.path.isdir(include_directory):
msg = 'Provided include directory does not exist ({}).'.format(include_directory)
sys.exit(msg)
profile... | 541,747 |
Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description] | def _signal_handler(self, signal_interupt, frame): # pylint: disable=W0613
if self.container is not None:
print('{}{}Stopping docker container.'.format(c.Style.BRIGHT, c.Fore.YELLOW))
self.container.stop()
print('{}{}Interrupt signal received.'.format(c.Style.BRIGHT, c.... | 541,750 |
Delete Redis data for provided variable.
Args:
variable (str): The Redis variable to delete.
clear_type (str): The type of clear action. | def clear_redis(self, variable, clear_type):
if variable is None:
return
if variable in self._clear_redis_tracker:
return
if not re.match(self._vars_match, variable):
return
self.log.info('[{}] Deleting redis variable: {}.'.format(clear_type, ... | 541,754 |
Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action. | def clear_tc(self, owner, data, clear_type):
batch = self.tcex.batch(owner, action='Delete')
tc_type = data.get('type')
path = data.get('path')
if tc_type in self.tcex.group_types:
name = self.tcex.playbook.read(data.get('name'))
name = self.path_data(nam... | 541,755 |
Validate db data in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation. | def data_in_db(db_data, user_data):
if isinstance(user_data, list):
if db_data in user_data:
return True
return False | 541,756 |
Validate data is type.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | def data_it(db_data, user_type):
data_type = {
'array': (list),
# 'binary': (string_types),
# 'bytes': (string_types),
'dict': (dict),
'entity': (dict),
'list': (list),
'str': (string_types),
'string': (stri... | 541,757 |
Validate key/value data in KeyValueArray.
Args:
db_data (list): The data store in Redis.
user_data (dict): The user provided data.
Returns:
bool: True if the data passed validation. | def data_kva_compare(db_data, user_data):
for kv_data in db_data:
if kv_data.get('key') == user_data.get('key'):
if kv_data.get('value') == user_data.get('value'):
return True
return False | 541,758 |
Validate data not in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation. | def data_not_in(db_data, user_data):
if isinstance(user_data, list):
if db_data not in user_data:
return True
return False | 541,759 |
Validate string removing all white space before comparison.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | def data_string_compare(db_data, user_data):
db_data = ''.join(db_data.split())
user_data = ''.join(user_data.split())
if operator.eq(db_data, user_data):
return True
return False | 541,760 |
Validate data in user data.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (dict|str|list): The user provided data.
Returns:
bool: True if the data passed validation. | def deep_diff(self, db_data, user_data):
# NOTE: tcex does include the deepdiff library as a dependencies since it is only
# required for local testing.
try:
from deepdiff import DeepDiff
except ImportError:
print('Could not import DeepDiff module (try "p... | 541,761 |
Validate data in user data.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | def json_compare(self, db_data, user_data):
if isinstance(db_data, (string_types)):
db_data = json.loads(db_data)
if isinstance(user_data, (string_types)):
user_data = json.loads(user_data)
return self.deep_diff(db_data, user_data) | 541,763 |
Return JMESPath data.
Args:
variable_data (str): The JSON data to run path expression.
path (str): The JMESPath expression.
Returns:
dict: The resulting data from JMESPath. | def path_data(self, variable_data, path):
# NOTE: tcex does include the jmespath library as a dependencies since it is only
# required for local testing.
try:
import jmespath
except ImportError:
print('Could not import jmespath module (try "pip install jm... | 541,766 |
Set the current profile.
Args:
profile (dict): The profile data. | def profile(self, profile):
# clear staging data
self._staging_data = None
# retrieve language from install.json or assume Python
lang = profile.get('install_json', {}).get('programLanguage', 'PYTHON')
# load instance of ArgBuilder
profile_args = ArgBuilder(lang,... | 541,767 |
Return args for v1, v2, or v3 structure.
Args:
_args (dict): The args section from the profile.
Returns:
dict: A collapsed version of the args dict. | def profile_args(_args):
# TODO: clean this up in a way that works for both py2/3
if (
_args.get('app', {}).get('optional') is not None
or _args.get('app', {}).get('required') is not None
):
# detect v3 schema
app_args_optional = _args.get... | 541,768 |
Return the run Print Command.
Args:
program_language (str): The language of the current App/Project.
program_main (str): The executable name.
Returns:
dict: A dictionary containing the run command and a printable version of the command. | def run_commands(self, program_language, program_main):
# build the command
if program_language == 'python':
python_exe = sys.executable
ptvsd_host = 'localhost'
if self.args.docker:
# use the default python command in the container
... | 541,772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.