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:
... | 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]
... | 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(... | 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_ke... | 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.tupl... | 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... | 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
comma... | 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 c... | 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)
s... | 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,... | 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
hasatt... | 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 ... | 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.tex... | 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 di... | 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
... |
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... | 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.whe... | 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={... | 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_sta... | 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:... | 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(... | 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 '... | 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')
... | 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)... | Преобразование конфигурационного файла в формате 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 = {}
... | 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")... | 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)
... | 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 == "... | 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: {}[... | 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["Experim... | 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"]
... | 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
"Experi... | 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)
... | 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)... | 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.pat... | 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
... | 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 i... | 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... |
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: '
... | 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()
... | 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)
... | 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
... | 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... | 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 worr... | 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
# whiche... | 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 beca... | 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 NU... | 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):
r... | 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'... | 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_RF... | 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.s... | 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:
... | 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)
... | 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.d... | 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), p... | 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, a... | 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... | 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 = re... | 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.Rea... | 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':
... | 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
... | 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. |
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. |
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 = ... | 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.dwSi... | 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.