code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def _speak_header_once_inherit(self, element):
header_elements = self.html_parser.find(element).find_descendants(
'['
+ AccessibleDisplayImplementation.DATA_ATTRIBUTE_HEADERS_OF
+ ']'
).list_results()
for header_element in header_elements:
header_element.remove_node() | The cells headers will be spoken one time for element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement |
def commonprefix(m):
u"Given a list of pathnames, returns the longest common leading component"
if not m:
return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i + 1].lower() != item[:i + 1].lower():
prefix = prefix[:i]
if i == 0:
return u''
break
return prefif commonprefix(m):
u"Given a list of pathnames, returns the longest common leading component"
if not m:
return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i + 1].lower() != item[:i + 1].lower():
prefix = prefix[:i]
if i == 0:
return u''
break
return prefix | u"Given a list of pathnames, returns the longest common leading component |
def _init_incremental_search(self, searchfun, init_event):
u
log("init_incremental_search")
self.subsearch_query = u''
self.subsearch_fun = searchfun
self.subsearch_old_line = self.l_buffer.get_line_text()
queue = self.process_keyevent_queue
queue.append(self._process_incremental_search_keyevent)
self.subsearch_oldprompt = self.prompt
if (self.previous_func != self.reverse_search_history and
self.previous_func != self.forward_search_history):
self.subsearch_query = self.l_buffer[0:Point].get_line_text()
if self.subsearch_fun == self.reverse_search_history:
self.subsearch_prompt = u"reverse-i-search%d`%s': "
else:
self.subsearch_prompt = u"forward-i-search%d`%s': "
self.prompt = self.subsearch_prompt%(self._history.history_cursor, "")
if self.subsearch_query:
self.line = self._process_incremental_search_keyevent(init_event)
else:
self.line = u"" | u"""Initialize search prompt |
def _init_digit_argument(self, keyinfo):
c = self.console
line = self.l_buffer.get_line_text()
self._digit_argument_oldprompt = self.prompt
queue = self.process_keyevent_queue
queue = self.process_keyevent_queue
queue.append(self._process_digit_argument_keyevent)
if keyinfo.char == "-":
self.argument = -1
elif keyinfo.char in u"0123456789":
self.argument = int(keyinfo.char)
log(u"<%s> %s"%(self.argument, type(self.argument)))
self.prompt = u"(arg: %s) "%self.argument
log(u"arg-init %s %s"%(self.argument, keyinfo.char)) | Initialize search prompt |
def _process_keyevent(self, keyinfo):
u
#Process exit keys. Only exit on empty line
log(u"_process_keyevent <%s>"%keyinfo)
def nop(e):
pass
if self.next_meta:
self.next_meta = False
keyinfo.meta = True
keytuple = keyinfo.tuple()
if self._insert_verbatim:
self.insert_text(keyinfo)
self._insert_verbatim = False
self.argument = 0
return False
if keytuple in self.exit_dispatch:
pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer))
log(u"exit_dispatch:<%s, %s>"%pars)
if lineobj.EndOfLine(self.l_buffer) == 0:
raise EOFError
if keyinfo.keyname or keyinfo.control or keyinfo.meta:
default = nop
else:
default = self.self_insert
dispatch_func = self.key_dispatch.get(keytuple, default)
log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func))
r = None
if dispatch_func:
r = dispatch_func(keyinfo)
self._keylog(dispatch_func, self.l_buffer)
self.l_buffer.push_undo()
self.previous_func = dispatch_func
return r | u"""return True when line is final |
def previous_history(self, e): # (C-p)
u'''Move back through the history list, fetching the previous
command. '''
self._history.previous_history(self.l_buffer)
self.l_buffer.point = lineobj.EndOfLine
self.finalize(f previous_history(self, e): # (C-p)
u'''Move back through the history list, fetching the previous
command. '''
self._history.previous_history(self.l_buffer)
self.l_buffer.point = lineobj.EndOfLine
self.finalize() | u'''Move back through the history list, fetching the previous
command. |
def next_history(self, e): # (C-n)
u'''Move forward through the history list, fetching the next
command. '''
self._history.next_history(self.l_buffer)
self.finalize(f next_history(self, e): # (C-n)
u'''Move forward through the history list, fetching the next
command. '''
self._history.next_history(self.l_buffer)
self.finalize() | u'''Move forward through the history list, fetching the next
command. |
def end_of_history(self, e): # (M->)
u'''Move to the end of the input history, i.e., the line currently
being entered.'''
self._history.end_of_history(self.l_buffer)
self.finalize(f end_of_history(self, e): # (M->)
u'''Move to the end of the input history, i.e., the line currently
being entered.'''
self._history.end_of_history(self.l_buffer)
self.finalize() | u'''Move to the end of the input history, i.e., the line currently
being entered. |
def reverse_search_history(self, e): # (C-r)
u'''Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search.'''
log("rev_search_history")
self._init_incremental_search(self._history.reverse_search_history, e)
self.finalize(f reverse_search_history(self, e): # (C-r)
u'''Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search.'''
log("rev_search_history")
self._init_incremental_search(self._history.reverse_search_history, e)
self.finalize() | u'''Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search. |
def forward_search_history(self, e): # (C-s)
u'''Search forward starting at the current line and moving down
through the the history as necessary. This is an incremental
search.'''
log("fwd_search_history")
self._init_incremental_search(self._history.forward_search_history, e)
self.finalize(f forward_search_history(self, e): # (C-s)
u'''Search forward starting at the current line and moving down
through the the history as necessary. This is an incremental
search.'''
log("fwd_search_history")
self._init_incremental_search(self._history.forward_search_history, e)
self.finalize() | u'''Search forward starting at the current line and moving down
through the the history as necessary. This is an incremental
search. |
def history_search_forward(self, e): # ()
u'''Search forward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound.'''
if (self.previous_func and
hasattr(self._history, self.previous_func.__name__)):
self._history.lastcommand = getattr(self._history,
self.previous_func.__name__)
else:
self._history.lastcommand = None
q = self._history.history_search_forward(self.l_buffer)
self.l_buffer = q
self.l_buffer.point = q.point
self.finalize(f history_search_forward(self, e): # ()
u'''Search forward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound.'''
if (self.previous_func and
hasattr(self._history, self.previous_func.__name__)):
self._history.lastcommand = getattr(self._history,
self.previous_func.__name__)
else:
self._history.lastcommand = None
q = self._history.history_search_forward(self.l_buffer)
self.l_buffer = q
self.l_buffer.point = q.point
self.finalize() | u'''Search forward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound. |
def tab_insert(self, e): # (M-TAB)
u'''Insert a tab character. '''
cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
ws = ' ' * (self.tabstop - (cursor % self.tabstop))
self.insert_text(ws)
self.finalize(f tab_insert(self, e): # (M-TAB)
u'''Insert a tab character. '''
cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
ws = ' ' * (self.tabstop - (cursor % self.tabstop))
self.insert_text(ws)
self.finalize() | u'''Insert a tab character. |
def create(filename, task, alias):
metadata = ET.Element('metadata', {'xml:lang': 'en'})
tool = ET.SubElement(metadata, 'tool', name=task.name,
displayname=task.display_name,
toolboxalias=alias)
summary = ET.SubElement(tool, 'summary')
summary.text = ''.join((HTML_BEGIN, task.description, HTML_END))
parameters = ET.SubElement(tool, 'parameters')
for task_param in task.parameters:
param = ET.SubElement(parameters, 'param',
name=task_param['name'],
displayname=task_param['display_name']
)
dialog_ref = ET.SubElement(param, 'dialogReference')
dialog_ref.text = ''.join((HTML_BEGIN, task_param['description'], HTML_END))
python_ref = ET.SubElement(param, 'pythonReference')
python_ref.text = ''.join((HTML_BEGIN, task_param['description'], HTML_END))
dataIdInfo = ET.SubElement(metadata, 'dataIdInfo')
searchKeys = ET.SubElement(dataIdInfo, 'searchKeys')
keyword1 = ET.SubElement(searchKeys, 'keyword')
keyword1.text = 'ENVI'
keyword2 = ET.SubElement(searchKeys, 'keyword')
keyword2.text = task.name
idCitation = ET.SubElement(dataIdInfo, 'idCitation')
resTitle = ET.SubElement(idCitation, 'resTitle')
resTitle.text = task.name
idAbs = ET.SubElement(dataIdInfo, 'idAbs')
idAbs.text = ''.join((HTML_BEGIN, task.description, HTML_END))
idCredit = ET.SubElement(dataIdInfo, 'idCredit')
idCredit.text = '(c) 2017 Exelis Visual Information Solutions, Inc.'
resTitle.text = task.name
tree = ET.ElementTree(metadata)
tree.write(filename) | Creates a gptool help xml file. |
def load_filesystem_plugins(self):
self.logger.info('Loading filesystem plugins')
search_path = self.__get_fs_plugin_search_path()
fs_plugins = []
PluginManagerSingleton.setBehaviour([
VersionedPluginManager,
])
# Load the plugins from the plugin directory.
plugin_manager = PluginManagerSingleton.get()
plugin_manager.setPluginPlaces(search_path)
plugin_manager.setCategoriesFilter({
"Filesystem": IFilesystemPlugin,
})
# Load plugins
plugin_manager.collectPlugins()
for pluginInfo in plugin_manager.getPluginsOfCategory("Filesystem"):
fs_plugins.append(pluginInfo)
return fs_plugins | Looks for *.yapsy-plugin files, loads them and returns a list
of :class:`VersionedPluginInfo \
<yapsy.VersionedPluginManager.VersionedPluginInfo>` objects
Note:
Plugin search locations:
* $(rawdisk package location)/plugins/filesystems
* $(home dir)/.local/share/rawdisk/plugins/filesystems
* /usr/local/share/rawdisk/plugins/filesystems
* /usr/share/rawdisk/plugins/filesystems |
def parse_params(self, params):
for (key, value) in params.items():
if not isinstance(value, str):
string_params = self.to_string(value)
params[key] = string_params
return params | Parsing params, params is a dict
and the dict value can be a string
or an iterable, namely a list, we
need to process those iterables |
def to_string(self, obj):
try:
converted = [str(element) for element in obj]
string = ','.join(converted)
except TypeError:
# for now this is ok for booleans
string = str(obj)
return string | Picks up an object and transforms it
into a string, by coercing each element
in an iterable to a string and then joining
them, or by trying to coerce the object directly |
def filter(self, endpoint, params):
params = self.parse_params(params)
params = urlencode(params)
path = '{0}?{1}'.format(endpoint, params)
return self.get(path) | Makes a get request by construction
the path from an endpoint and a dict
with filter query params
e.g.
params = {'category__in': [1,2]}
response = self.client.filter('/experiences/', params) |
def is_domain_class_terminal_attribute(ent, attr_name):
attr = get_domain_class_attribute(ent, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL | Checks if the given attribute name is a terminal attribute of the given
registered resource. |
def is_domain_class_member_attribute(ent, attr_name):
attr = get_domain_class_attribute(ent, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER | Checks if the given attribute name is a entity attribute of the given
registered resource. |
def is_domain_class_collection_attribute(ent, attr_name):
attr = get_domain_class_attribute(ent, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION | Checks if the given attribute name is a aggregate attribute of the given
registered resource. |
def is_domain_class_domain_attribute(ent, attr_name):
attr = get_domain_class_attribute(ent, attr_name)
return attr != RESOURCE_ATTRIBUTE_KINDS.TERMINAL | Checks if the given attribute name is a resource attribute (i.e., either
a member or a aggregate attribute) of the given registered resource. |
def get_domain_class_terminal_attribute_iterator(ent):
for attr in itervalues_(ent.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
yield attr | Returns an iterator over all terminal attributes in the given registered
resource. |
def get_domain_class_relationship_attribute_iterator(ent):
for attr in itervalues_(ent.__everest_attributes__):
if attr.kind != RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
yield attr | Returns an iterator over all terminal attributes in the given registered
resource. |
def get_domain_class_member_attribute_iterator(ent):
for attr in itervalues_(ent.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER:
yield attr | Returns an iterator over all terminal attributes in the given registered
resource. |
def get_domain_class_collection_attribute_iterator(ent):
for attr in itervalues_(ent.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
yield attr | Returns an iterator over all terminal attributes in the given registered
resource. |
def set_password(self, password):
self.password = Security.hash(password)
self.save() | Set user password with hash |
def create_password_reset(cls, email, valid_for=3600) -> str:
user = cls.where_email(email)
if user is None:
return None
PasswordResetModel.delete_where_user_id(user.id)
token = JWT().create_token({
'code': Security.random_string(5), # make unique
'user_id': user.id},
token_valid_for=valid_for)
code = Security.generate_uuid(1) + "-" + Security.random_string(5)
password_reset_model = PasswordResetModel()
password_reset_model.token = token
password_reset_model.code = code
password_reset_model.user_id = user.id
password_reset_model.save()
return code | Create a password reset request in the user_password_resets
database table. Hashed code gets stored in the database.
Returns unhashed reset code |
def validate_password_reset(cls, code, new_password):
password_reset_model = \
PasswordResetModel.where_code(code)
if password_reset_model is None:
return None
jwt = JWT()
if jwt.verify_token(password_reset_model.token):
user = cls.where_id(jwt.data['data']['user_id'])
if user is not None:
user.set_password(new_password)
PasswordResetModel.delete_where_user_id(user.id)
return user
password_reset_model.delete() # delete expired/invalid token
return None | Validates an unhashed code against a hashed code.
Once the code has been validated and confirmed
new_password will replace the old users password |
def by_current_session(cls):
session = Session.current_session()
if session is None:
return None
return cls.where_id(session.user_id) | Returns current user session |
def AdvancedJsonify(data, status_code):
response = jsonify(data)
response.status_code = status_code
return response | Advanced Jsonify Response Maker
:param data: Data
:param status_code: Status_code
:return: Response |
def response(self, callback=None):
if not callback:
callback = type(self).AdvancedJsonify
resp = {
"status": "error",
"message": self.message
}
if self.step:
resp["step"] = self.step
self.LOGGER.error(self.message, extra={"step": self.step, "context": self.context})
return callback(resp, status_code=self.code) | View representation of the object
:param callback: Function to represent the error in view. Default : flask.jsonify
:type callback: function
:return: View |
def dict(self):
params = {
prop: getattr(self, prop)
for prop in [
"logs", "date", "author", "sha", "path"
]
}
params["author"] = params["author"].dict()
return params | Builds a dictionary representation of the object (eg: for JSON)
:return: Dictionary representation of the object |
def __json(self):
if self.exclude_list is None:
self.exclude_list = []
fields = {}
for key, item in vars(self).items():
if hasattr(self, '_sa_instance_state'):
# load only deferred objects
if len(orm.attributes.instance_state(self).unloaded) > 0:
mapper = inspect(self)
for column in mapper.attrs:
column.key
column.value
if str(key).startswith('_') or key in self.exclude_list:
continue
fields[key] = item
obj = Json.safe_object(fields)
return str(obj) | Using the exclude lists, convert fields to a string. |
def manage(cls, entity, unit_of_work):
if hasattr(entity, '__everest__'):
if not unit_of_work is entity.__everest__.unit_of_work:
raise ValueError('Trying to register an entity that has been '
'registered with another session!')
else:
entity.__everest__ = cls(entity, unit_of_work) | Manages the given entity under the given Unit Of Work.
If `entity` is already managed by the given Unit Of Work, nothing
is done.
:raises ValueError: If the given entity is already under management
by a different Unit Of Work. |
def release(cls, entity, unit_of_work):
if not hasattr(entity, '__everest__'):
raise ValueError('Trying to unregister an entity that has not '
'been registered yet!')
elif not unit_of_work is entity.__everest__.unit_of_work:
raise ValueError('Trying to unregister an entity that has been '
'registered with another session!')
delattr(entity, '__everest__') | Releases the given entity from management under the given Unit Of
Work.
:raises ValueError: If `entity` is not managed at all or is not
managed by the given Unit Of Work. |
def get_state_data(cls, entity):
attrs = get_domain_class_attribute_iterator(type(entity))
return dict([(attr,
get_nested_attribute(entity, attr.entity_attr))
for attr in attrs
if not attr.entity_attr is None]) | Returns the state data for the given entity.
This also works for unmanaged entities. |
def set_state_data(cls, entity, data):
attr_names = get_domain_class_attribute_names(type(entity))
nested_items = []
for attr, new_attr_value in iteritems_(data):
if not attr.entity_attr in attr_names:
raise ValueError('Can not set attribute "%s" for entity '
'"%s".' % (attr.entity_attr, entity))
if '.' in attr.entity_attr:
nested_items.append((attr, new_attr_value))
continue
else:
setattr(entity, attr.entity_attr, new_attr_value)
for attr, new_attr_value in nested_items:
try:
set_nested_attribute(entity, attr.entity_attr, new_attr_value)
except AttributeError as exc:
if not new_attr_value is None:
raise exc | Sets the state data for the given entity to the given data.
This also works for unmanaged entities. |
def transfer_state_data(cls, source_entity, target_entity):
state_data = cls.get_state_data(source_entity)
cls.set_state_data(target_entity, state_data) | Transfers instance state data from the given source entity to the
given target entity. |
def __set_data(self, data):
ent = self.__entity_ref()
self.set_state_data(ent, data) | Sets the given state data on the given entity of the given class.
:param data: State data to set.
:type data: Dictionary mapping attributes to attribute values.
:param entity: Entity to receive the state data. |
def pretty_print(self, carrot=True):
output = ['\n']
output.extend([line.pretty_print() for line in
self.partpyobj.get_surrounding_lines(1, 0)])
if carrot:
output.append('\n' +
(' ' * (self.partpyobj.col + 5)) + '^' + '\n')
if self.partpymsg:
output.append(self.partpymsg)
return ''.join(output) | Print the previous and current line with line numbers and
a carret under the current character position.
Will also print a message if one is given to this exception. |
def serialise_to_rsh(params: dict) -> str:
out = "// Generated at %s\n\n" % (datetime.now())
def add_val(field, value):
"""Add value to multiple line in rsh format."""
if isinstance(value, bytes):
value = value.decode("cp1251")
val = ''.join('%s, ' % (v) for v in value) if isinstance(value, list) \
else value
if isinstance(val, str) and val.endswith(', '):
val = val[:-2]
return '%s -- %s\n' % (val, field)
for param in params:
if param == "channel":
for i, channel in enumerate(params[param]):
for ch_par in channel:
val = "%s_%s[%s]" % (param, ch_par, i)
if ch_par == "params":
val = "%ss_%s[%s]" % (param, ch_par, i)
out += add_val(val, channel[ch_par])
elif param == "synchro_channel":
for sync_ch_par in params[param]:
if sync_ch_par == "type":
out += add_val(param, params[param][sync_ch_par])
else:
out += add_val("%s_%s" % (param, sync_ch_par),
params[param][sync_ch_par])
else:
out += add_val(param, params[param])
return out | Преобразование конфигурационного файла в формате JSON в текстовый хедер.
rsh. Хедер можно использовать как конфигурационный файл для lan10-12base
@params -- параметры в формате JSON (dfparser.def_values.DEF_RSH_PARAMS)
@return -- текстовый хедер |
def get_event(self, num):
if num < 0 or num >= self.params["events_num"]:
raise IndexError("Index out of range [0:%s]" %
(self.params["events_num"]))
ch_num = self.params['channel_number']
ev_size = self.params['b_size']
event = {}
self.file.seek(7168 + num * (96 + 2 * ch_num * ev_size))
event["text_hdr"] = self.file.read(64)
event["ev_num"] = struct.unpack('I', self.file.read(4))[0]
self.file.read(4)
start_time = struct.unpack('Q', self.file.read(8))[0]
event["start_time"] = datetime.fromtimestamp(start_time)
ns_since_epoch = struct.unpack('Q', self.file.read(8))[0]
if ns_since_epoch:
event['ns_since_epoch'] = ns_since_epoch
self.file.read(8)
event_data = self.file.read(2 * ev_size * ch_num)
event["data"] = np.fromstring(event_data, np.short)
return event | Extract event from dataset. |
def update_event_data(self, num, data):
if num < 0 or num >= self.params["events_num"]:
raise IndexError("Index out of range [0:%s]" %
(self.params["events_num"]))
if isinstance(data, np.ndarray):
raise TypeError("data should be np.ndarray")
if data.dtype != np.short:
raise TypeError("data array dtype should be dtype('int16')")
ch_num = self.params['channel_number']
ev_size = self.params['b_size']
if data.shape != (ch_num * ev_size,):
raise Exception("data should contain same number of elements "
"(%s)" % (ch_num * ev_size))
self.file.seek(7168 + num * (96 + 2 * ch_num * ev_size) + 96)
self.file.write(data.tostring())
self.file.flush() | Update event data in dataset. |
def create_examples_all():
remove_examples_all()
examples_all_dir().mkdir()
for lib in libraries():
maindir = examples_all_dir() / lib.upper()[0:1] / lib
# libraries_dir() /
maindir.makedirs_p()
for ex in lib_examples(lib):
d = lib_example_dir(lib, ex)
if hasattr(os, 'symlink'):
d.symlink(maindir / ex)
else:
d.copytree(maindir / ex) | create arduino/examples/all directory.
:rtype: None |
def str_to_pool(upstream):
name = re.search('upstream +(.*?) +{', upstream).group(1)
nodes = re.findall('server +(.*?);', upstream)
return name, nodes | Given a string containing an nginx upstream section, return the pool name
and list of nodes. |
def calculate_vss(self, method=None):
if self.variance == float(0):
return self.vss
else:
# Calculate gausian distribution and return
if method == "gaussian" or method is None:
return gauss(self.vss, self.variance)
elif method == "random":
return uniform(self.vss - self.variance, self.vss + self.variance)
else:
raise ValueError("Method of vss calculation not recognized, please use 'gaussian' or 'random'") | Calculate the vertical swimming speed of this behavior.
Takes into account the vertical swimming speed and the
variance.
Parameters:
method: "gaussian" (default) or "random"
"random" (vss - variance) < X < (vss + variance) |
def _check_experiment(self, name):
with h5py.File(name=self.path, mode="r") as h5:
sigpath = "/Experiments/{}/metadata/Signal".format(name)
signal_type = h5[sigpath].attrs["signal_type"]
if signal_type != "hologram":
msg = "Signal type '{}' not supported: {}[{}]".format(signal_type,
self.path,
name)
warnings.warn(msg, WrongSignalTypeWarnging)
return signal_type == "hologram" | Check the signal type of the experiment
Returns
-------
True, if the signal type is supported, False otherwise
Raises
------
Warning if the signal type is not supported |
def _get_experiments(self):
explist = []
with h5py.File(name=self.path, mode="r") as h5:
if "Experiments" not in h5:
msg = "Group 'Experiments' not found in {}.".format(self.path)
raise HyperSpyNoDataFoundError(msg)
for name in h5["Experiments"]:
# check experiment
if self._check_experiment(name):
explist.append(name)
explist.sort()
if not explist:
# if this error is raised, the signal_type is probably not
# set to "hologram".
msg = "No supported data found: {}".format(self.path)
raise HyperSpyNoDataFoundError(msg)
return explist | Get all experiments from the hdf5 file |
def get_qpimage_raw(self, idx=0):
name = self._get_experiments()[idx]
with h5py.File(name=self.path, mode="r") as h5:
exp = h5["Experiments"][name]
# hologram data
data = exp["data"][:]
# resolution
rx = exp["axis-0"].attrs["scale"]
ry = exp["axis-1"].attrs["scale"]
if rx != ry:
raise NotImplementedError("Only square pixels supported!")
runit = exp["axis-0"].attrs["units"]
if runit == "nm":
pixel_size = rx * 1e-9
else:
raise NotImplementedError("Units '{}' not implemented!")
meta_data = {"pixel size": pixel_size}
meta_data.update(self.meta_data)
qpi = qpimage.QPImage(data=data,
which_data="hologram",
meta_data=meta_data,
holo_kw=self.holo_kw,
h5dtype=self.as_type)
# set identifier
qpi["identifier"] = self.get_identifier(idx)
return qpi | Return QPImage without background correction |
def verify(path):
valid = False
try:
h5 = h5py.File(path, mode="r")
except (OSError, IsADirectoryError):
pass
else:
if ("file_format" in h5.attrs and
h5.attrs["file_format"].lower() == "hyperspy" and
"Experiments" in h5):
valid = True
return valid | Verify that `path` has the HyperSpy file format |
def transform(self, df):
for name, function in self.outputs:
df[name] = function(df) | Transforms a DataFrame in place. Computes all outputs of the DataFrame.
Args:
df (pandas.DataFrame): DataFrame to transform. |
def get_dataframe(self, force_computation=False):
# returns df if it was already computed
if self.df is not None and not force_computation: return self.df
self.df = self.fetch(self.context)
# compute df = transform(preprocess(df)
self.df = self.preprocess(self.df)
self.transform(self.df)
return self.df | Preprocesses then transforms the return of fetch().
Args:
force_computation (bool, optional) : Defaults to False. If set to True, forces the computation of DataFrame at each call.
Returns:
pandas.DataFrame: Preprocessed and transformed DataFrame. |
def push(self, proxy, key, attribute, relation_operation):
node = TraversalPathNode(proxy, key, attribute, relation_operation)
self.nodes.append(node)
self.__keys.add(key) | Adds a new :class:`TraversalPathNode` constructed from the given
arguments to this traversal path. |
def pop(self):
node = self.nodes.pop()
self.__keys.remove(node.key) | Removes the last traversal path node from this traversal path. |
def parent(self):
if len(self.nodes) > 0:
parent = self.nodes[-1].proxy
else:
parent = None
return parent | Returns the proxy from the last node visited on the path, or `None`,
if no node has been visited yet. |
def relation_operation(self):
if len(self.nodes) > 0:
rel_op = self.nodes[-1].relation_operation
else:
rel_op = None
return rel_op | Returns the relation operation from the last node visited on the
path, or `None`, if no node has been visited yet. |
def score_meaning(text):
#all_characters = re.findall('[ -~]', text) # match 32-126 in ASCII table
all_characters = re.findall('[a-zA-Z ]', text) # match 32-126 in ASCII table
if len(all_characters) == 0:
return 0
repetition_count = Counter(all_characters)
score = (len(all_characters)) ** 2 / (len(repetition_count) + len(text) / 26)
return score | Returns a score in [0,1] range if the text makes any sense in English. |
def get_top_n_meanings(strings, n):
scored_strings = [(s, score_meaning(s)) for s in strings]
scored_strings.sort(key=lambda tup: -tup[1])
return scored_strings[:n] | Returns (text, score) for top n strings |
def ensure_unicode(text):
u
if isinstance(text, str):
try:
return text.decode(pyreadline_codepage, u"replace")
except (LookupError, TypeError):
return text.decode(u"ascii", u"replace")
return text | u"""helper to ensure that text passed to WriteConsoleW is unicode |
def ensure_str(text):
u
if isinstance(text, unicode):
try:
return text.encode(pyreadline_codepage, u"replace")
except (LookupError, TypeError):
return text.encode(u"ascii", u"replace")
return text | u"""Convert unicode to str using pyreadline_codepage |
def reload(self, regexes=None, **kwargs):
combined = re.compile("(" + ")|(".join(regexes) + ")", re.I)
pending_files = os.listdir(self.src_path) or []
pending_files.sort()
for filename in pending_files:
if re.match(combined, filename):
self.put(os.path.join(self.src_path, filename)) | Reloads /path/to/filenames into the queue
that match the regexes. |
def unwrap_raw(content):
starting_symbol = get_start_symbol(content)
ending_symbol = ']' if starting_symbol == '[' else '}'
start = content.find(starting_symbol, 0)
end = content.rfind(ending_symbol)
return content[start:end+1] | unwraps the callback and returns the raw content |
def combine_word_list(word_list):
bag_of_words = collections.defaultdict(int)
for word in word_list:
bag_of_words[word] += 1
return bag_of_words | Combine word list into a bag-of-words.
Input: - word_list: This is a python list of strings.
Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. |
def reduce_list_of_bags_of_words(list_of_keyword_sets):
bag_of_words = dict()
get_bag_of_words_keys = bag_of_words.keys
for keyword_set in list_of_keyword_sets:
for keyword in keyword_set:
if keyword in get_bag_of_words_keys():
bag_of_words[keyword] += 1
else:
bag_of_words[keyword] = 1
return bag_of_words | Reduces a number of keyword sets to a bag-of-words.
Input: - list_of_keyword_sets: This is a python list of sets of strings.
Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. |
def query_list_of_words(target_word, list_of_words, edit_distance=1):
# Initialize lists
new_list_of_words = list()
found_list_of_words = list()
append_left_keyword = new_list_of_words.append
append_found_keyword = found_list_of_words.append
# Iterate over the list of words
for word in list_of_words:
if len(word) > 6:
effective_edit_distance = edit_distance
else:
effective_edit_distance = 0 # No edit distance for small words.
if abs(len(word)-len(target_word)) <= effective_edit_distance:
if nltk.edit_distance(word, target_word) <= effective_edit_distance:
append_found_keyword(word)
else:
append_left_keyword(word)
else:
append_left_keyword(word)
return new_list_of_words, found_list_of_words | Checks whether a target word is within editing distance of any one in a set of keywords.
Inputs: - target_word: A string containing the word we want to search in a list.
- list_of_words: A python list of words.
- edit_distance: For larger words, we also check for similar words based on edit_distance.
Outputs: - new_list_of_words: This is the input list of words minus any found keywords.
- found_list_of_words: This is the list of words that are within edit distance of the target word. |
def fixup_instance(sender, **kwargs):
instance = kwargs['instance']
for model_field in instance._meta.fields:
if not isinstance(model_field, JSONAttributeField):
continue
if hasattr(instance, '_attr_field'):
raise FieldError('multiple JSONAttributeField fields: '
'only one is allowed per model!')
field_name = model_field.name
attrs = getattr(instance, field_name)
# ensure JSONAttributeField's data is of JSONAttributes type
if not isinstance(attrs, JSONAttributes):
setattr(instance, field_name, JSONAttributes(attrs))
attrs = getattr(instance, field_name)
# Cache model instance on JSONAttributes instance and vice-versa
attrs._instance = instance
attrs._get_from_instance = functools.partial(
getattr, instance, field_name)
instance._attr_field = attrs
if not hasattr(instance, '_attr_field'):
raise FieldError('missing JSONAttributeField field in '
'fixup_instance decorator') | Cache JSONAttributes data on instance and vice versa for convenience. |
def get_setting(context, key, default_val="", as_key=None):
if ("%s" % default_val).startswith('$.'):
default_val = getattr(settings, default_val[2:])
val = getattr(settings, key, default_val)
if not as_key:
return val
context[as_key] = val
return '' | get val form settings and set to context
{% load lbutils %}
{% get_setting "key" default_val "as_key" %}
{{ as_key }}
if as_key is None, this tag will return val |
async def get_data(self):
try:
with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(self.url)
_LOGGER.debug(
"Response from Volkszaehler API: %s", response.status)
self.data = await response.json()
_LOGGER.debug(self.data)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Can not load data from Volkszaehler API")
self.data = None
raise exceptions.VolkszaehlerApiConnectionError()
self.average = self.data['data']['average']
self.max = self.data['data']['max'][1]
self.min = self.data['data']['min'][1]
self.consumption = self.data['data']['consumption']
self.tuples = self.data['data']['tuples'] | Retrieve the data. |
def get_clipboard_text_and_convert(paste_list=False):
u
txt = GetClipboardText()
if txt:
if paste_list and u"\t" in txt:
array, flag = make_list_of_list(txt)
if flag:
txt = repr(array)
else:
txt = u"array(%s)"%repr(array)
txt = u"".join([c for c in txt if c not in u" \t\r\n"])
return txt | u"""Get txt from clipboard. if paste_list==True the convert tab separated
data to list of lists. Enclose list of list in array() if all elements are
numeric |
def hdfFromKwargs(hdf=None, **kwargs):
if not hdf:
hdf = HDF()
for key, value in kwargs.iteritems():
if isinstance(value, dict):
#print "dict:",value
for k,v in value.iteritems():
dkey = "%s.%s"%(key,k)
#print "k,v,dkey:",k,v,dkey
args = {dkey:v}
hdfFromKwargs(hdf=hdf, **args)
elif isinstance(value, (list, tuple)):
#print "list:",value
for i, item in enumerate(value):
ikey = "%s.%s"%(key,i)
#print "i,item:",i,item, ikey
if isinstance(item, (list, tuple)):
args = {ikey:item}
hdfFromKwargs(hdf=hdf, **args)
elif isinstance(item, dict):
args = {ikey:item}
hdfFromKwargs(hdf=hdf, **args)
elif getattr(item, "HDF_ATTRIBUTES", False):
attrs = {}
for attr in item.HDF_ATTRIBUTES:
attrs[attr] = getattr(item, attr, "")
hdfFromKwargs(hdf=hdf, **{ikey:attrs})
else:
hdf.setValue(ikey, str(item))
elif getattr(value, "HDF_ATTRIBUTES", False):
attrs = {}
for attr in value.HDF_ATTRIBUTES:
attrs[attr] = getattr(value, attr, "")
hdfFromKwargs(hdf=hdf, **{key:attrs})
else:
hdf.setValue(key, str(value))
#print "HDF:",hdf.dump()
return hdf | If given an instance that has toHDF() method that method is invoked to get that object's HDF representation |
def size(self):
if self is NULL:
return 0
return 1 + self.left.size() + self.right.size() | Recursively find size of a tree. Slow. |
def find_prekeyed(self, value, key):
while self is not NULL:
direction = cmp(value, key(self.value))
if direction < 0:
self = self.left
elif direction > 0:
self = self.right
elif direction == 0:
return self.value | Find a value in a node, using a key function. The value is already a
key. |
def rotate_left(self):
right = self.right
new = self._replace(right=self.right.left, red=True)
top = right._replace(left=new, red=self.red)
return top | Rotate the node to the left. |
def flip(self):
left = self.left._replace(red=not self.left.red)
right = self.right._replace(red=not self.right.red)
top = self._replace(left=left, right=right, red=not self.red)
return top | Flip colors of a node and its children. |
def balance(self):
# Always lean left with red nodes.
if self.right.red:
self = self.rotate_left()
# Never permit red nodes to have red children. Note that if the left-hand
# node is NULL, it will short-circuit and fail this test, so we don't have
# to worry about a dereference here.
if self.left.red and self.left.left.red:
self = self.rotate_right()
# Finally, move red children on both sides up to the next level, reducing
# the total redness.
if self.left.red and self.right.red:
self = self.flip()
return self | Balance a node.
The balance is inductive and relies on all subtrees being balanced
recursively or by construction. If the subtrees are not balanced, then
this will not fix them. |
def insert(self, value, key):
# Base case: Insertion into the empty tree is just creating a new node
# with no children.
if self is NULL:
return Node(value, NULL, NULL, True), True
# Recursive case: Insertion into a non-empty tree is insertion into
# whichever of the two sides is correctly compared.
direction = cmp(key(value), key(self.value))
if direction < 0:
left, insertion = self.left.insert(value, key)
self = self._replace(left=left)
elif direction > 0:
right, insertion = self.right.insert(value, key)
self = self._replace(right=right)
elif direction == 0:
# Exact hit on an existing node (this node, in fact). In this
# case, perform an update.
self = self._replace(value=value)
insertion = False
# And balance on the way back up.
return self.balance(), insertion | Insert a value into a tree rooted at the given node, and return
whether this was an insertion or update.
Balances the tree during insertion.
An update is performed instead of an insertion if a value in the tree
compares equal to the new value. |
def move_red_left(self):
self = self.flip()
if self.right is not NULL and self.right.left.red:
self = self._replace(right=self.right.rotate_right())
self = self.rotate_left().flip()
return self | Shuffle red to the left of a tree. |
def move_red_right(self):
self = self.flip()
if self.left is not NULL and self.left.left.red:
self = self.rotate_right().flip()
return self | Shuffle red to the right of a tree. |
def delete_min(self):
# Base case: If there are no nodes lesser than this node, then this is the
# node to delete.
if self.left is NULL:
return NULL, self.value
# Acquire more reds if necessary to continue the traversal. The
# double-deep check is fine because NULL is red.
if not self.left.red and not self.left.left.red:
self = self.move_red_left()
# Recursive case: Delete the minimum node of all nodes lesser than this
# node.
left, value = self.left.delete_min()
self = self._replace(left=left)
return self.balance(), value | Delete the left-most value from a tree. |
def delete_max(self):
# Attempt to rotate left-leaning reds to the right.
if self.left.red:
self = self.rotate_right()
# Base case: If there are no selfs greater than this self, then this is
# the self to delete.
if self.right is NULL:
return NULL, self.value
# Acquire more reds if necessary to continue the traversal. NULL is
# red so this check doesn't need to check for NULL.
if not self.right.red and not self.right.left.red:
self = self.move_red_right()
# Recursive case: Delete the maximum self of all selfs greater than this
# self.
right, value = self.right.delete_max()
self = self._replace(right=right)
return self.balance(), value | Delete the right-most value from a tree. |
def pop_max(self):
if self.root is NULL:
raise KeyError("pop from an empty blackjack")
self.root, value = self.root.delete_max()
self._len -= 1
return value | Remove the maximum value and return it. |
def pop_min(self):
if self.root is NULL:
raise KeyError("pop from an empty blackjack")
self.root, value = self.root.delete_min()
self._len -= 1
return value | Remove the minimum value and return it. |
def hook_wrapper_23(stdin, stdout, prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
raise TypeError, u'readline must return a string.'
except KeyboardInterrupt:
# GNU readline returns 0 on keyboard interrupt
return 0
except EOFError:
# It returns an empty string on EOF
res = u''
except:
print >>sys.stderr, u'Readline internal error'
traceback.print_exc()
res = u'\n'
# we have to make a copy because the caller expects to free the result
n = len(res)
p = Console.PyMem_Malloc(n + 1)
_strncpy(cast(p, c_char_p), res, n + 1)
return f hook_wrapper_23(stdin, stdout, prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
raise TypeError, u'readline must return a string.'
except KeyboardInterrupt:
# GNU readline returns 0 on keyboard interrupt
return 0
except EOFError:
# It returns an empty string on EOF
res = u''
except:
print >>sys.stderr, u'Readline internal error'
traceback.print_exc()
res = u'\n'
# we have to make a copy because the caller expects to free the result
n = len(res)
p = Console.PyMem_Malloc(n + 1)
_strncpy(cast(p, c_char_p), res, n + 1)
return p | u'''Wrap a Python readline so it behaves like GNU readline. |
def hook_wrapper(prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
raise TypeError, u'readline must return a string.'
except KeyboardInterrupt:
# GNU readline returns 0 on keyboard interrupt
return 0
except EOFError:
# It returns an empty string on EOF
res = u''
except:
print >>sys.stderr, u'Readline internal error'
traceback.print_exc()
res = u'\n'
# we have to make a copy because the caller expects to free the result
p = _strdup(res)
return f hook_wrapper(prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
raise TypeError, u'readline must return a string.'
except KeyboardInterrupt:
# GNU readline returns 0 on keyboard interrupt
return 0
except EOFError:
# It returns an empty string on EOF
res = u''
except:
print >>sys.stderr, u'Readline internal error'
traceback.print_exc()
res = u'\n'
# we have to make a copy because the caller expects to free the result
p = _strdup(res)
return p | u'''Wrap a Python readline so it behaves like GNU readline. |
def install_readline(hook):
'''Set up things for the interpreter to call
our function like GNU readline.'''
global readline_hook, readline_ref
# save the hook so the wrapper can call it
readline_hook = hook
# get the address of PyOS_ReadlineFunctionPointer so we can update it
PyOS_RFP = c_void_p.from_address(Console.GetProcAddress(sys.dllhandle,
"PyOS_ReadlineFunctionPointer"))
# save a reference to the generated C-callable so it doesn't go away
if sys.version < '2.3':
readline_ref = HOOKFUNC22(hook_wrapper)
else:
readline_ref = HOOKFUNC23(hook_wrapper_23)
# get the address of the function
func_start = c_void_p.from_address(addressof(readline_ref)).value
# write the function address into PyOS_ReadlineFunctionPointer
PyOS_RFP.value = func_starf install_readline(hook):
'''Set up things for the interpreter to call
our function like GNU readline.'''
global readline_hook, readline_ref
# save the hook so the wrapper can call it
readline_hook = hook
# get the address of PyOS_ReadlineFunctionPointer so we can update it
PyOS_RFP = c_void_p.from_address(Console.GetProcAddress(sys.dllhandle,
"PyOS_ReadlineFunctionPointer"))
# save a reference to the generated C-callable so it doesn't go away
if sys.version < '2.3':
readline_ref = HOOKFUNC22(hook_wrapper)
else:
readline_ref = HOOKFUNC23(hook_wrapper_23)
# get the address of the function
func_start = c_void_p.from_address(addressof(readline_ref)).value
# write the function address into PyOS_ReadlineFunctionPointer
PyOS_RFP.value = func_start | Set up things for the interpreter to call
our function like GNU readline. |
def fixcoord(self, x, y):
u'''Return a long with x and y packed inside,
also handle negative x and y.'''
if x < 0 or y < 0:
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if x < 0:
x = info.srWindow.Right - x
y = info.srWindow.Bottom + y
# this is a hack! ctypes won't pass structures but COORD is
# just like a long, so this works.
return c_int(y << 16 | xf fixcoord(self, x, y):
u'''Return a long with x and y packed inside,
also handle negative x and y.'''
if x < 0 or y < 0:
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if x < 0:
x = info.srWindow.Right - x
y = info.srWindow.Bottom + y
# this is a hack! ctypes won't pass structures but COORD is
# just like a long, so this works.
return c_int(y << 16 | x) | u'''Return a long with x and y packed inside,
also handle negative x and y. |
def pos(self, x=None, y=None):
u'''Move or query the window cursor.'''
if x is None:
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
else:
return self.SetConsoleCursorPosition(self.hout,
self.fixcoord(x, y)f pos(self, x=None, y=None):
u'''Move or query the window cursor.'''
if x is None:
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
else:
return self.SetConsoleCursorPosition(self.hout,
self.fixcoord(x, y)) | u'''Move or query the window cursor. |
def write_plain(self, text, attr=None):
u'''write text at current cursor position.'''
text = ensure_unicode(text)
log(u'write("%s", %s)' %(text, attr))
if attr is None:
attr = self.attr
junk = DWORD(0)
self.SetConsoleTextAttribute(self.hout, attr)
for short_chunk in split_block(chunk):
self.WriteConsoleW(self.hout, ensure_unicode(short_chunk),
len(short_chunk), byref(junk), None)
return len(textf write_plain(self, text, attr=None):
u'''write text at current cursor position.'''
text = ensure_unicode(text)
log(u'write("%s", %s)' %(text, attr))
if attr is None:
attr = self.attr
junk = DWORD(0)
self.SetConsoleTextAttribute(self.hout, attr)
for short_chunk in split_block(chunk):
self.WriteConsoleW(self.hout, ensure_unicode(short_chunk),
len(short_chunk), byref(junk), None)
return len(text) | u'''write text at current cursor position. |
def page(self, attr=None, fill=u' '):
u'''Fill the entire screen.'''
if attr is None:
attr = self.attr
if len(fill) != 1:
raise ValueError
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))
w = info.dwSize.X
n = DWORD(0)
for y in range(info.dwSize.Y):
self.FillConsoleOutputAttribute(self.hout, attr,
w, self.fixcoord(0, y), byref(n))
self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]),
w, self.fixcoord(0, y), byref(n))
self.attr = attf page(self, attr=None, fill=u' '):
u'''Fill the entire screen.'''
if attr is None:
attr = self.attr
if len(fill) != 1:
raise ValueError
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))
w = info.dwSize.X
n = DWORD(0)
for y in range(info.dwSize.Y):
self.FillConsoleOutputAttribute(self.hout, attr,
w, self.fixcoord(0, y), byref(n))
self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]),
w, self.fixcoord(0, y), byref(n))
self.attr = attr | u'''Fill the entire screen. |
def text(self, x, y, text, attr=None):
u'''Write text at the given position.'''
if attr is None:
attr = self.attr
pos = self.fixcoord(x, y)
n = DWORD(0)
self.WriteConsoleOutputCharacterW(self.hout, text,
len(text), pos, byref(n))
self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n)f text(self, x, y, text, attr=None):
u'''Write text at the given position.'''
if attr is None:
attr = self.attr
pos = self.fixcoord(x, y)
n = DWORD(0)
self.WriteConsoleOutputCharacterW(self.hout, text,
len(text), pos, byref(n))
self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n)) | u'''Write text at the given position. |
def rectangle(self, rect, attr=None, fill=u' '):
u'''Fill Rectangle.'''
x0, y0, x1, y1 = rect
n = DWORD(0)
if attr is None:
attr = self.attr
for y in range(y0, y1):
pos = self.fixcoord(x0, y)
self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0,
pos, byref(n))
self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), x1 - x0,
pos, byref(n)f rectangle(self, rect, attr=None, fill=u' '):
u'''Fill Rectangle.'''
x0, y0, x1, y1 = rect
n = DWORD(0)
if attr is None:
attr = self.attr
for y in range(y0, y1):
pos = self.fixcoord(x0, y)
self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0,
pos, byref(n))
self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), x1 - x0,
pos, byref(n)) | u'''Fill Rectangle. |
def scroll(self, rect, dx, dy, attr=None, fill=' '):
u'''Scroll a rectangle.'''
if attr is None:
attr = self.attr
x0, y0, x1, y1 = rect
source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
dest = self.fixcoord(x0 + dx, y0 + dy)
style = CHAR_INFO()
style.Char.AsciiChar = ensure_str(fill[0])
style.Attributes = attr
return self.ScrollConsoleScreenBufferW(self.hout, byref(source),
byref(source), dest, byref(style)f scroll(self, rect, dx, dy, attr=None, fill=' '):
u'''Scroll a rectangle.'''
if attr is None:
attr = self.attr
x0, y0, x1, y1 = rect
source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
dest = self.fixcoord(x0 + dx, y0 + dy)
style = CHAR_INFO()
style.Char.AsciiChar = ensure_str(fill[0])
style.Attributes = attr
return self.ScrollConsoleScreenBufferW(self.hout, byref(source),
byref(source), dest, byref(style)) | u'''Scroll a rectangle. |
def scroll_window(self, lines):
u'''Scroll the window by the indicated number of lines.'''
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
rect = info.srWindow
log(u'sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
top = rect.Top + lines
bot = rect.Bottom + lines
h = bot - top
maxbot = info.dwSize.Y-1
if top < 0:
top = 0
bot = h
if bot > maxbot:
bot = maxbot
top = bot - h
nrect = SMALL_RECT()
nrect.Top = top
nrect.Bottom = bot
nrect.Left = rect.Left
nrect.Right = rect.Right
log(u'sn: top=%d bot=%d' % (top, bot))
r=self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
log(u'r=%d' % rf scroll_window(self, lines):
u'''Scroll the window by the indicated number of lines.'''
info = CONSOLE_SCREEN_BUFFER_INFO()
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
rect = info.srWindow
log(u'sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))
top = rect.Top + lines
bot = rect.Bottom + lines
h = bot - top
maxbot = info.dwSize.Y-1
if top < 0:
top = 0
bot = h
if bot > maxbot:
bot = maxbot
top = bot - h
nrect = SMALL_RECT()
nrect.Top = top
nrect.Bottom = bot
nrect.Left = rect.Left
nrect.Right = rect.Right
log(u'sn: top=%d bot=%d' % (top, bot))
r=self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
log(u'r=%d' % r) | u'''Scroll the window by the indicated number of lines. |
def get(self):
u'''Get next event from queue.'''
inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
if inputHookFunc:
call_function(inputHookFunc, ())
status = self.ReadConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if status and count.value == 1:
e = event(self, Cevent)
return f get(self):
u'''Get next event from queue.'''
inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
if inputHookFunc:
call_function(inputHookFunc, ())
status = self.ReadConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if status and count.value == 1:
e = event(self, Cevent)
return e | u'''Get next event from queue. |
def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
while 1:
e = self.get()
if e.type == u'KeyPress' and e.keycode not in key_modifiers:
log(u"console.getkeypress %s"%e)
if e.keyinfo.keyname == u'next':
self.scroll_window(12)
elif e.keyinfo.keyname == u'prior':
self.scroll_window(-12)
else:
return e
elif ((e.type == u'KeyRelease') and
(e.keyinfo == KeyPress('S', False, True, False, 'S'))):
log(u"getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type))
return f getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
while 1:
e = self.get()
if e.type == u'KeyPress' and e.keycode not in key_modifiers:
log(u"console.getkeypress %s"%e)
if e.keyinfo.keyname == u'next':
self.scroll_window(12)
elif e.keyinfo.keyname == u'prior':
self.scroll_window(-12)
else:
return e
elif ((e.type == u'KeyRelease') and
(e.keyinfo == KeyPress('S', False, True, False, 'S'))):
log(u"getKeypress:%s,%s,%s"%(e.keyinfo, e.keycode, e.type))
return e | u'''Return next key press event from the queue, ignoring others. |
def getchar(self):
u'''Get next character from queue.'''
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
status = self.ReadConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if (status and
(count.value == 1) and
(Cevent.EventType == 1) and
Cevent.Event.KeyEvent.bKeyDown):
sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
if len(sym) == 0:
sym = Cevent.Event.KeyEvent.uChar.AsciiChar
return syf getchar(self):
u'''Get next character from queue.'''
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
status = self.ReadConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if (status and
(count.value == 1) and
(Cevent.EventType == 1) and
Cevent.Event.KeyEvent.bKeyDown):
sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
if len(sym) == 0:
sym = Cevent.Event.KeyEvent.uChar.AsciiChar
return sym | u'''Get next character from queue. |
def peek(self):
u'''Check event queue.'''
Cevent = INPUT_RECORD()
count = DWORD(0)
status = self.PeekConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if status and count == 1:
return event(self, Ceventf peek(self):
u'''Check event queue.'''
Cevent = INPUT_RECORD()
count = DWORD(0)
status = self.PeekConsoleInputW(self.hin,
byref(Cevent), 1, byref(count))
if status and count == 1:
return event(self, Cevent) | u'''Check event queue. |
def title(self, txt=None):
u'''Set/get title.'''
if txt:
self.SetConsoleTitleW(txt)
else:
buffer = create_unicode_buffer(200)
n = self.GetConsoleTitleW(buffer, 200)
if n > 0:
return buffer.value[:nf title(self, txt=None):
u'''Set/get title.'''
if txt:
self.SetConsoleTitleW(txt)
else:
buffer = create_unicode_buffer(200)
n = self.GetConsoleTitleW(buffer, 200)
if n > 0:
return buffer.value[:n] | u'''Set/get title. |
def size(self, width=None, height=None):
u'''Set/get window size.'''
info = CONSOLE_SCREEN_BUFFER_INFO()
status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if not status:
return None
if width is not None and height is not None:
wmin = info.srWindow.Right - info.srWindow.Left + 1
hmin = info.srWindow.Bottom - info.srWindow.Top + 1
#print wmin, hmin
width = max(width, wmin)
height = max(height, hmin)
#print width, height
self.SetConsoleScreenBufferSize(self.hout,
self.fixcoord(width, height))
else:
return (info.dwSize.X, info.dwSize.Yf size(self, width=None, height=None):
u'''Set/get window size.'''
info = CONSOLE_SCREEN_BUFFER_INFO()
status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
if not status:
return None
if width is not None and height is not None:
wmin = info.srWindow.Right - info.srWindow.Left + 1
hmin = info.srWindow.Bottom - info.srWindow.Top + 1
#print wmin, hmin
width = max(width, wmin)
height = max(height, hmin)
#print width, height
self.SetConsoleScreenBufferSize(self.hout,
self.fixcoord(width, height))
else:
return (info.dwSize.X, info.dwSize.Y) | u'''Set/get window size. |
def cursor(self, visible=None, size=None):
u'''Set cursor on or off.'''
info = CONSOLE_CURSOR_INFO()
if self.GetConsoleCursorInfo(self.hout, byref(info)):
if visible is not None:
info.bVisible = visible
if size is not None:
info.dwSize = size
self.SetConsoleCursorInfo(self.hout, byref(info)f cursor(self, visible=None, size=None):
u'''Set cursor on or off.'''
info = CONSOLE_CURSOR_INFO()
if self.GetConsoleCursorInfo(self.hout, byref(info)):
if visible is not None:
info.bVisible = visible
if size is not None:
info.dwSize = size
self.SetConsoleCursorInfo(self.hout, byref(info)) | u'''Set cursor on or off. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.