Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def to_str(data):
if isinstance(data, bytes):
return codecs.decode(data, aws_encryption_sdk.internal.defaults.ENCODING)
return data | [
"Takes an input str or bytes object and returns an equivalent str object.\n\n :param data: Input data\n :type data: str or bytes\n :returns: Data normalized to str\n :rtype: str\n "
] |
Please provide a description of the function:def to_bytes(data):
if isinstance(data, six.string_types) and not isinstance(data, bytes):
return codecs.encode(data, aws_encryption_sdk.internal.defaults.ENCODING)
return data | [
"Takes an input str or bytes object and returns an equivalent bytes object.\n\n :param data: Input data\n :type data: str or bytes\n :returns: Data normalized to bytes\n :rtype: bytes\n "
] |
Please provide a description of the function:def _master_key_provider() -> KMSMasterKeyProvider:
master_key_provider = KMSMasterKeyProvider()
master_key_provider.add_master_key_provider(NullMasterKey())
master_key_provider.add_master_key_provider(CountingMasterKey())
return master_key_provider | [
"Build the V0 master key provider."
] |
Please provide a description of the function:def basic_decrypt() -> Response:
APP.log.debug("Request:")
APP.log.debug(json.dumps(APP.current_request.to_dict()))
APP.log.debug("Ciphertext:")
APP.log.debug(APP.current_request.raw_body)
try:
ciphertext = APP.current_request.raw_body
... | [
"Basic decrypt handler for decrypt oracle v0.\n\n **Request**\n\n * **Method**: POST\n * **Body**: Raw ciphertext bytes\n * **Headers**:\n\n * **Content-Type**: ``application/octet-stream``\n * **Accept**: ``application/octet-stream``\n\n **Response**\n\n * 200 response code with the raw... |
Please provide a description of the function:def read(self, b=None):
data = self.__wrapped__.read(b)
self.__tee.write(data)
return data | [
"Reads data from source, copying it into ``tee`` before returning.\n\n :param int b: number of bytes to read\n "
] |
Please provide a description of the function:def read(self, b=-1):
remaining_bytes = b
data = io.BytesIO()
while True:
try:
chunk = to_bytes(self.__wrapped__.read(remaining_bytes))
except ValueError:
if self.__wrapped__.closed:
... | [
"Keep reading from source stream until either the source stream is done\n or the requested number of bytes have been obtained.\n\n :param int b: number of bytes to read\n :return: All bytes read from wrapped stream\n :rtype: bytes\n "
] |
Please provide a description of the function:def _ecc_static_length_signature(key, algorithm, digest):
pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type()))
signature = b""
while len(signature) != algorithm.signature_len:
_LOGGER.debug(
"Signature length %d is no... | [
"Calculates an elliptic curve signature with a static length using pre-calculated hash.\n\n :param key: Elliptic curve private key\n :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey\n :param algorithm: Master algorithm to use\n :type algorithm: aws_encryption_sdk.identifie... |
Please provide a description of the function:def _ecc_encode_compressed_point(private_key):
# key_size is in bits. Convert to bytes and round up
byte_length = (private_key.curve.key_size + 7) // 8
public_numbers = private_key.public_key().public_numbers()
y_map = [b"\x02", b"\x03"]
# If curve i... | [
"Encodes a compressed elliptic curve point\n as described in SEC-1 v2 section 2.3.3\n http://www.secg.org/sec1-v2.pdf\n\n :param private_key: Private key from which to extract point data\n :type private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey\n :returns: Enco... |
Please provide a description of the function:def _ecc_decode_compressed_point(curve, compressed_point):
if not compressed_point:
raise NotSupportedError("Points at infinity are not allowed")
y_order_map = {b"\x02": 0, b"\x03": 1}
raw_x = compressed_point[1:]
raw_x = to_bytes(raw_x)
x = ... | [
"Decodes a compressed elliptic curve point\n as described in SEC-1 v2 section 2.3.4\n http://www.secg.org/sec1-v2.pdf\n\n :param curve: Elliptic curve type to generate\n :type curve: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve\n :param bytes compressed_point: Encoded compressed... |
Please provide a description of the function:def _ecc_public_numbers_from_compressed_point(curve, compressed_point):
x, y = _ecc_decode_compressed_point(curve, compressed_point)
return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve) | [
"Decodes a compressed elliptic curve point\n as described in SEC-1 v2 section 2.3.3\n and returns a PublicNumbers instance\n based on the decoded point.\n http://www.secg.org/sec1-v2.pdf\n\n :param curve: Elliptic curve type to generate\n :type curve: cryptography.hazmat.primitives... |
Please provide a description of the function:def generate_ecc_signing_key(algorithm):
try:
verify_interface(ec.EllipticCurve, algorithm.signing_algorithm_info)
return ec.generate_private_key(curve=algorithm.signing_algorithm_info(), backend=default_backend())
except InterfaceNotImplemented:... | [
"Returns an ECC signing key.\n\n :param algorithm: Algorithm object which determines what signature to generate\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :returns: Generated signing key\n :raises NotSupportedError: if signing algorithm is not supported on this platform\n "
] |
Please provide a description of the function:def derive_data_encryption_key(source_key, algorithm, message_id):
key = source_key
if algorithm.kdf_type is not None:
key = algorithm.kdf_type(
algorithm=algorithm.kdf_hash_type(),
length=algorithm.data_key_len,
salt=... | [
"Derives the data encryption key using the defined algorithm.\n\n :param bytes source_key: Raw source key\n :param algorithm: Algorithm used to encrypt this body\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param bytes message_id: Message ID\n :returns: Derived data encryption key\n... |
Please provide a description of the function:def encrypt(**kwargs):
with StreamEncryptor(**kwargs) as encryptor:
ciphertext = encryptor.read()
return ciphertext, encryptor.header | [
"Encrypts and serializes provided plaintext.\n\n .. note::\n When using this function, the entire ciphertext message is encrypted into memory before returning\n any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.\n\n .. code:: python\n\n >>> import aws_encryption_s... |
Please provide a description of the function:def decrypt(**kwargs):
with StreamDecryptor(**kwargs) as decryptor:
plaintext = decryptor.read()
return plaintext, decryptor.header | [
"Deserializes and decrypts provided ciphertext.\n\n .. note::\n When using this function, the entire ciphertext message is decrypted into memory before returning\n any data. If streaming is desired, see :class:`aws_encryption_sdk.stream`.\n\n .. code:: python\n\n >>> import aws_encryptio... |
Please provide a description of the function:def stream(**kwargs):
mode = kwargs.pop("mode")
_stream_map = {"e": StreamEncryptor, "encrypt": StreamEncryptor, "d": StreamDecryptor, "decrypt": StreamDecryptor}
try:
return _stream_map[mode.lower()](**kwargs)
except KeyError:
raise Valu... | [
"Provides an :py:func:`open`-like interface to the streaming encryptor/decryptor classes.\n\n .. warning::\n Take care when decrypting framed messages with large frame length and large non-framed\n messages. In order to protect the authenticity of the encrypted data, no plaintext\n is return... |
Please provide a description of the function:def cycle_file(key_arn, source_plaintext_filename, botocore_session=None):
# "Cycled" means encrypted and then decrypted
ciphertext_filename = source_plaintext_filename + ".encrypted"
cycled_kms_plaintext_filename = source_plaintext_filename + ".kms.decrypte... | [
"Encrypts and then decrypts a file using a KMS master key provider and a custom static master\n key provider. Both master key providers are used to encrypt the plaintext file, so either one alone\n can decrypt it.\n\n :param str key_arn: Amazon Resource Name (ARN) of the KMS Customer Master Key (CMK)\n ... |
Please provide a description of the function:def _get_raw_key(self, key_id):
try:
static_key = self._static_keys[key_id]
except KeyError:
private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())
static_key = priv... | [
"Retrieves a static, randomly generated, RSA key for the specified key id.\n\n :param str key_id: User-defined ID for the static key\n :returns: Wrapping key that contains the specified static key\n :rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`\n "
] |
Please provide a description of the function:def timeslot_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time s... | [] |
Please provide a description of the function:def timeslot_offset_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of... | [] |
Please provide a description of the function:def month_boundaries(dt=None):
'''
Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference.
'''
dt = dt or date.today()
wkday, ndays = calendar.monthrange(dt.year, dt.month)
... | [] |
Please provide a description of the function:def css_class_cycler():
'''
Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names.
'''
FMT = 'evt-{0}-{1}'.format
return defaultdict(default_css_class_cycler, (
(e.abbr, itertools.c... | [] |
Please provide a description of the function:def create_timeslot_table(
dt=None,
items=None,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_time_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
time_delta=swingtime_settings.TIMESLOT_INTERVAL,
min_columns=swingtime_settings.TIMESLOT_M... | [] |
Please provide a description of the function:def create_event(
title,
event_type,
description='',
start_time=None,
end_time=None,
note=None,
**rrule_params
):
'''
Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Oc... | [] |
Please provide a description of the function:def add_occurrences(self, start_time, end_time, **rrule_params):
'''
Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rru... | [] |
Please provide a description of the function:def daily_occurrences(self, dt=None):
'''
Convenience method wrapping ``Occurrence.objects.daily_occurrences``.
'''
return Occurrence.objects.daily_occurrences(dt=dt, event=self) | [] |
Please provide a description of the function:def daily_occurrences(self, dt=None, event=None):
'''
Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, defau... | [] |
Please provide a description of the function:def event_listing(
request,
template='swingtime/event_list.html',
events=None,
**extra_context
):
'''
View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
... | [] |
Please provide a description of the function:def event_view(
request,
pk,
template='swingtime/event_detail.html',
event_form_class=forms.EventForm,
recurrence_form_class=forms.MultipleOccurrenceForm
):
'''
View an ``Event`` instance and optionally update either the event or its
occurrenc... | [] |
Please provide a description of the function:def occurrence_view(
request,
event_pk,
pk,
template='swingtime/occurrence_detail.html',
form_class=forms.SingleOccurrenceForm
):
'''
View a specific occurrence and optionally handle any updates.
Context parameters:
``occurrence``
... | [] |
Please provide a description of the function:def add_event(
request,
template='swingtime/add_event.html',
event_form_class=forms.EventForm,
recurrence_form_class=forms.MultipleOccurrenceForm
):
'''
Add a new ``Event`` instance and 1 or more associated ``Occurrence``s.
Context parameters:
... | [] |
Please provide a description of the function:def _datetime_view(
request,
template,
dt,
timeslot_factory=None,
items=None,
params=None
):
'''
Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
... | [] |
Please provide a description of the function:def day_view(request, year, month, day, template='swingtime/daily_view.html', **params):
'''
See documentation for function``_datetime_view``.
'''
dt = datetime(int(year), int(month), int(day))
return _datetime_view(request, template, dt, **params) | [] |
Please provide a description of the function:def today_view(request, template='swingtime/daily_view.html', **params):
'''
See documentation for function``_datetime_view``.
'''
return _datetime_view(request, template, datetime.now(), **params) | [] |
Please provide a description of the function:def month_view(
request,
year,
month,
template='swingtime/monthly_view.html',
queryset=None
):
'''
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datet... | [] |
Please provide a description of the function:def cast(self, value, custom_formatters=None, strict=True):
if value is None:
if not self.nullable:
raise InvalidSchemaValue("Null value for non-nullable schema", value, self.type)
return self.default
cast_map... | [
"Cast value to schema type"
] |
Please provide a description of the function:def unmarshal(self, value, custom_formatters=None, strict=True):
if self.deprecated:
warnings.warn("The schema is deprecated", DeprecationWarning)
casted = self.cast(value, custom_formatters=custom_formatters, strict=strict)
if ... | [
"Unmarshal parameter from the value."
] |
Please provide a description of the function:def get_operation_pattern(server_url, request_url_pattern):
if server_url[-1] == "/":
# operations have to start with a slash, so do not remove it
server_url = server_url[:-1]
if is_absolute(server_url):
return request_url_pattern.replace... | [
"Return an updated request URL pattern with the server URL removed."
] |
Please provide a description of the function:def shift(self, amount):
if self.left is not None:
self.left += amount
if self.left is not None:
self.right += amount | [
" shifts position "
] |
Please provide a description of the function:def valid_sequences(self):
valid_sets = [[x] for x in self.possible_items if x['left'] == 0]
change = True
niter = 200
while change and niter > 0:
change = False
niter -=1
for possible in sorted(sel... | [
"Returns list"
] |
Please provide a description of the function:def check(definition, data, *args, **kwargs):
checker = checker_factory(definition)
return checker(data, *args, **kwargs) | [
"Checks if the input follows the definition"
] |
Please provide a description of the function:def formatchecker_factory(**checkerdict):
fc = FormatChecker()
for format_name, checker in checkerdict.items():
fc.checks(format_name)(checker)
return fc | [
"Converts a dictionary of strings:checkers into a formatchecker object"
] |
Please provide a description of the function:def check(self, data):
if isinstance(data, Iterable):
data = "".join(str(x) for x in data)
try:
data = str(data)
except UnicodeDecodeError:
return False
return bool(data and self.__regexp.match(data... | [
"returns True if any match any regexp"
] |
Please provide a description of the function:def _build_item_closure(itemset, productionset):
#For every item inside current itemset, if we have the following rule:
# xxx <cursor><nonterminalSymbol> xxx append every rule from self._productionruleset that begins with that NonTerminalSymbol
if not isin... | [
"Build input itemset closure "
] |
Please provide a description of the function:def item_set_goto(itemset, inputsymbol, productionset):
resultset = LR0ItemSet()
for item in itemset.itemlist:
if item.next_symbol() == inputsymbol:
newitem = LR0Item(item.rule, item.position + 1)
resultset.append_item(newitem)
... | [
"returns an itemset\n locate inside itemset every element with inputsymbol following cursor\n for every located item, append its itemclosure"
] |
Please provide a description of the function:def _slr_build_parser_table(productionset):
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(statesset):
LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset))
for symbo... | [
"SLR method to build parser table"
] |
Please provide a description of the function:def append(self, state, symbol, action, destinationstate, production = None):
if action not in (None, "Accept", "Shift", "Reduce"):
raise TypeError
rule = {"action":action, "dest":destinationstate}
if action == "Reduce":
... | [
"Appends a new rule"
] |
Please provide a description of the function:def insert(self, state, token):
if token == EndSymbol():
return self[state][EndSymbol()]
from pydsl.check import check
symbol_list = [x for x in self[state] if isinstance(x, TerminalSymbol) and check(x.gd, [token])]
if not... | [
"change internal state, return action"
] |
Please provide a description of the function:def append_item(self, item):
if not isinstance(item, LR0Item):
raise TypeError
self.itemlist.append(item) | [
"Append new item to set"
] |
Please provide a description of the function:def append_transition(self, symbol, targetset):
if symbol in self.transitions:
return
self.transitions[symbol] = targetset | [
"Appends a transition"
] |
Please provide a description of the function:def __parse(self, tokenlist):
#empty stack
#iterate over symbollist
tokenlist = [x for x in tokenlist]
if not isinstance(tokenlist, list):
raise TypeError("Expected list, got %s" % tokenlist.__class__.__name__)
LOG... | [
"see parent docstring"
] |
Please provide a description of the function:def graph_from_alphabet(alphabet, base):
if not isinstance(alphabet, Choice):
raise TypeError(alphabet.__class__.__name__)
if not isinstance(base, Choice):
raise TypeError(base.__class__.__name__)
import networkx
result = net... | [
"Creates a graph that connects the base with the target through alphabets\n If every target is connected to any inputs, create the independent paths"
] |
Please provide a description of the function:def is_subset(a, b):
return b.left <= a.left and b.right > a.right or b.left < a.left and b.right >= a.right | [
"Excluding same size"
] |
Please provide a description of the function:def digraph_walker_backwards(graph, element, call_back):
call_back(graph, element)
for predecessor in graph.predecessors(element):
call_back(graph, predecessor)
for predecessor in graph.predecessors(element):
digraph_walker_backwards(graph, p... | [
"Visits every element guaranteeing that the previous elements have been visited before"
] |
Please provide a description of the function:def first_lookup(self, symbol, size=1):
if isinstance(symbol, (TerminalSymbol, NullSymbol)):
return [symbol.gd]
result = []
for production in self.productions:
if production.leftside[0] != symbol:
conti... | [
"\n Returns a Grammar Definition with the first n terminal symbols\n produced by the input symbol\n "
] |
Please provide a description of the function:def next_lookup(self, symbol):
result = []
if symbol == self.initialsymbol:
result.append(EndSymbol())
for production in self.productions:
if symbol in production.rightside:
nextindex = production.right... | [
"Returns the next TerminalSymbols produced by the input symbol within this grammar definition"
] |
Please provide a description of the function:def main_production(self):
for rule in self.productions:
if rule.leftside[0] == self._initialsymbol:
return rule
raise IndexError | [
"Returns main rule"
] |
Please provide a description of the function:def getSymbols(self):
symbollist = []
for rule in self.productions:
for symbol in rule.leftside + rule.rightside:
if symbol not in symbollist:
symbollist.append(symbol)
symbollist += self.termin... | [
"Returns every symbol"
] |
Please provide a description of the function:def t_NUMBER(t):
r'\d+'
try:
t.value = int(t.value)
except ValueError:
print("Integer value too large %d", t.value)
t.value = 0
return t | [] |
Please provide a description of the function:def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression'''
if t[2] == '+' : t[0] = t[1] + t[3]
elif t[2... | [] |
Please provide a description of the function:def extract_alphabet(alphabet, inputdata, fixed_start = False):
if not inputdata:
return []
base_alphabet = alphabet.alphabet
lexer = lexer_factory(alphabet, base_alphabet)
totallen = len(inputdata)
maxl = totallen
minl = 1
if fixed_... | [
"\n Receives a sequence and an alphabet, \n returns a list of PositionTokens with all of the parts of the sequence that \n are a subset of the alphabet\n "
] |
Please provide a description of the function:def extract(grammar, inputdata, fixed_start = False, return_first=False):
if not inputdata:
return []
checker = checker_factory(grammar)
totallen = len(inputdata)
from pydsl.grammar.PEG import Choice
try:
maxl = grammar.maxsize or to... | [
"\n Receives a sequence and a grammar, \n returns a list of PositionTokens with all of the parts of the sequence that \n are recognized by the grammar\n "
] |
Please provide a description of the function:def get_trees(self, data, showerrors = False): # -> list:
if showerrors:
raise NotImplementedError("This parser doesn't implement errors")
self.data = data
self.index = 0
try:
return [self.__aux_parser(self._pr... | [
" returns a list of trees with valid guesses "
] |
Please provide a description of the function:def append_position_to_token_list(token_list):
return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)] | [
"Converts a list of Token into a list of Token, asuming size == 1"
] |
Please provide a description of the function:def load_python_file(moduleobject):
if isinstance(moduleobject, str):
moduleobject = load_module(moduleobject)
if not hasattr(moduleobject, "iclass"):
raise KeyError("Element" + str(moduleobject))
iclass = getattr(moduleobject, "iclass")
... | [
" Try to create an indexable instance from a module"
] |
Please provide a description of the function:def load_bnf_file(filepath, repository = None):
linelist = []
with open(filepath,'r') as mlfile:
for line in mlfile:
linelist.append(line)
return strlist_to_production_set(linelist, repository) | [
"Converts a bnf file into a BNFGrammar instance"
] |
Please provide a description of the function:def get_trees(self, data, showerrors = False): # -> list:
if not all(check(self._productionset.alphabet, [x]) for x in data):
raise ValueError("Unknown element in {}, alphabet:{}".format(str(data), self.productionset.alphabet))
result = s... | [
" returns a list of trees with valid guesses "
] |
Please provide a description of the function:def __recursive_parser(self, onlysymbol, data, production, showerrors = False):
LOG.debug("__recursive_parser: Begin ")
if not data:
return []
from pydsl.grammar.symbol import TerminalSymbol, NullSymbol, NonTerminalSymbol
... | [
" Aux function. helps check_word"
] |
Please provide a description of the function:def load_re_from_file(filepath):
regexp = None
with open(filepath,'r') as mlfile:
flagstr = ""
for line in mlfile:
cleanline = re.sub("//.*$", "", line)
if re.search("^\s*$", cleanline):
continue
... | [
"Converts a re file to Regular Grammar instance"
] |
Please provide a description of the function:def url_for(context, __route_name, **parts):
app = context['app']
query = None
if 'query_' in parts:
query = parts.pop('query_')
for key in parts:
val = parts[key]
if isinstance(val, str):
# if type is inherited from... | [
"Filter for generating urls.\n\n Usage: {{ url('the-view-name') }} might become \"/path/to/view\" or\n {{ url('item-details', id=123, query={'active': 'true'}) }}\n might become \"/items/1?active=true\".\n "
] |
Please provide a description of the function:def static_url(context, static_file_path):
app = context['app']
try:
static_url = app['static_root_url']
except KeyError:
raise RuntimeError(
"app does not define a static root url "
"'static_root_url', you need to set... | [
"Filter for generating urls for static files.\n\n NOTE: you'll need\n to set app['static_root_url'] to be used as the root for the urls returned.\n\n Usage: {{ static('styles.css') }} might become\n \"/static/styles.css\" or \"http://mycdn.example.com/styles.css\"\n "
] |
Please provide a description of the function:def send_message(self, *args, **kwargs):
'''Wrapped method would accept new `queued` and `isgroup`
OPTIONAL arguments'''
return super(MQBot, self).send_message(*args, **kwargs) | [] |
Please provide a description of the function:def edit_message_text(self, *args, **kwargs):
'''Wrapped method would accept new `queued` and `isgroup`
OPTIONAL arguments'''
return super(MQBot, self).edit_message_text(*args, **kwargs) | [] |
Please provide a description of the function:def init_gl(self):
"allocate OpenGL resources"
self.vr_system = openvr.init(openvr.VRApplication_Scene)
w, h = self.vr_system.getRecommendedRenderTargetSize()
self.left_fb = OpenVrFramebuffer(w, h, multisample=self.multisample)
self.ri... | [] |
Please provide a description of the function:def display(self):
"Renders the scene once every refresh"
self.compositor.waitGetPoses(self.poses, openvr.k_unMaxTrackedDeviceCount, None, 0)
hmd_pose0 = self.poses[openvr.k_unTrackedDeviceIndex_Hmd]
if not hmd_pose0.bPoseIsValid:
... | [] |
Please provide a description of the function:def key_press(self, key, x, y):
"Close the application when the player presses ESCAPE"
if ord(key) == 27:
# print "Escape!"
if bool(glutLeaveMainLoop):
glutLeaveMainLoop()
else:
raise ... | [] |
Please provide a description of the function:def render_scene(self):
"render scene one time"
self.init_gl()
glfw.MakeContextCurrent(self.window)
self.renderer.render_scene()
glfw.SwapBuffers(self.window)
glfw.PollEvents() | [] |
Please provide a description of the function:def key_callback(self, window, key, scancode, action, mods):
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.SetWindowShouldClose(self.window, True) | [
"press ESCAPE to quite the application"
] |
Please provide a description of the function:def render_scene(self):
"render scene one time"
self.init_gl() # should be a no-op after the first frame is rendered
SDL_GL_MakeCurrent ( self.window, self.context )
self.renderer.render_scene()
# Done rendering
# SDL_GL_SwapWindow(self.window)
glFlush() | [] |
Please provide a description of the function:def on_sdl_keydown ( self, event ):
"press ESCAPE to quit the application"
key = event.key.keysym.sym
if key == SDLK_ESCAPE:
self.running = False | [] |
Please provide a description of the function:def run_loop(self):
"keep rendering until the user says quit"
self.running = True
event = SDL_Event()
try:
while self.running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
f = self._sdl_event_handlers.get(event.type)
if f is not None:
... | [] |
Please provide a description of the function:def scale(self, x, y=None, z=None):
"Uniform scale, if only sx argument is specified"
if y is None:
y = x
if z is None:
z = x
m = self
for col in range(4):
# Only the top three rows
... | [] |
Please provide a description of the function:def bInit( self, vrModel, vrDiffuseTexture ):
"Purpose: Allocates and populates the GL resources for a render model"
# create and bind a VAO to hold state for this model
self.m_glVertArray = glGenVertexArrays(1)
glBindVertexArray( self.m_g... | [] |
Please provide a description of the function:def cleanup(self):
"Purpose: Frees the GL resources for a render model"
if self.m_glVertBuffer != 0:
glDeleteBuffers(1, (self.m_glIndexBuffer,))
glDeleteVertexArrays( 1, (self.m_glVertArray,) )
glDeleteBuffers(1, (self... | [] |
Please provide a description of the function:def draw(self):
"Purpose: Draws the render model"
glBindVertexArray( self.m_glVertArray )
glActiveTexture( GL_TEXTURE0 )
glBindTexture( GL_TEXTURE_2D, self.m_glTexture )
glDrawElements( GL_TRIANGLES, self.m_unVertexCount, GL_UNSIG... | [] |
Please provide a description of the function:def setupRenderModels(self):
"Purpose: Create/destroy GL Render Models"
self.m_rTrackedDeviceToRenderModel = [None] * openvr.k_unMaxTrackedDeviceCount
if self.m_pHMD is None:
return
for unTrackedDevice in range(openvr.k_unTrac... | [] |
Please provide a description of the function:def processVREvent(self, event):
"Purpose: Processes a single VR event"
et = event.eventType
if et == openvr.VREvent_TrackedDeviceActivated:
self.setupRenderModelForTrackedDevice( event.trackedDeviceIndex )
dprintf( "Devic... | [] |
Please provide a description of the function:def setupScene(self):
"Purpose: create a sea of cubes"
if self.m_pHMD is None:
return
vertdataarray = list()
matScale = Matrix4()
matScale.scale( self.m_fScale, self.m_fScale, self.m_fScale )
matTransform = M... | [] |
Please provide a description of the function:def drawControllers(self):
"Purpose: Draw all of the controllers as X/Y/Z lines"
# don't draw controllers if somebody else has input focus
if self.m_pHMD.isInputFocusCapturedByAnotherProcess():
return
vertdataarray = list()
... | [] |
Please provide a description of the function:def convertSteamVRMatrixToMatrix4(self, matPose):
"Purpose: Converts a SteamVR matrix to our local matrix class"
matrixObj = Matrix4( [
[matPose.m[0][0], matPose.m[1][0], matPose.m[2][0], 0.0],
[matPose.m[0][1], matPose.m[1][1], matPose.m[... | [] |
Please provide a description of the function:def compileGLShader(self, pchShaderName, pchVertexShader, pchFragmentShader):
unProgramID = glCreateProgram()
nSceneVertexShader = glCreateShader(GL_VERTEX_SHADER)
glShaderSource( nSceneVertexShader, pchVertexShader)
glCompileSha... | [
"\r\n Purpose: Compiles a GL shader program and returns the handle. Returns 0 if\r\n the shader couldn't be compiled for some reason.\r\n "
] |
Please provide a description of the function:def createAllShaders(self):
"Purpose: Creates all the shaders used by HelloVR SDL"
self.m_unSceneProgramID = self.compileGLShader(
"Scene",
# Vertex Shader
dedent(),
# Fragment Shader
dedent(... | [
"\\\r\n #version 410\r\n uniform mat4 matrix;\r\n layout(location = 0) in vec4 position;\r\n layout(location = 1) in vec2 v2UVcoordsIn;\r\n layout(location = 2) in vec3 v3NormalIn;\r\n out vec2 v2UVcoords;\r\n void main()\r\n {\... |
Please provide a description of the function:def setupRenderModelForTrackedDevice(self, unTrackedDeviceIndex):
"Purpose: Create/destroy GL a Render Model for a single tracked device"
if unTrackedDeviceIndex >= openvr.k_unMaxTrackedDeviceCount:
return
# try to find a model we've a... | [] |
Please provide a description of the function:def findOrLoadRenderModel(self, pchRenderModelName):
"Purpose: Finds a render model we've already loaded or loads a new one"
pRenderModel = None
for model in self.m_vecRenderModels:
if model.getName() == pchRenderModelName:
... | [] |
Please provide a description of the function:def render_scene(self):
"render scene one time"
self.init_gl() # should be a no-op after the first frame is rendered
glfw.make_context_current(self.window)
self.renderer.render_scene()
# Done rendering
# glfw.swap_buffers(self.... | [] |
Please provide a description of the function:def shader_string(body, glsl_version='450 core'):
line_count = len(body.split('\n'))
line_number = inspect.currentframe().f_back.f_lineno + 1 - line_count
return % (glsl_version, shader_substring(body, stack_frame=2)) | [
"\r\n Call this method from a function that defines a literal shader string as the \"body\" argument.\r\n Dresses up a shader string in three ways:\r\n 1) Insert #version at the top\r\n 2) Insert #line number declaration\r\n 3) un-indents\r\n The line number information can help debug ... |
Please provide a description of the function:def shader_substring(body, stack_frame=1):
line_count = len(body.splitlines(True))
line_number = inspect.stack()[stack_frame][2] + 1 - line_count
return % (line_number, textwrap.dedent(body)) | [
"\r\n Call this method from a function that defines a literal shader string as the \"body\" argument.\r\n Dresses up a shader string in two ways:\r\n 1) Insert #line number declaration\r\n 2) un-indents\r\n The line number information can help debug glsl compile errors.\r\n The unindenting... |
Please provide a description of the function:def _check_devices(self):
"Enumerate OpenVR tracked devices and check whether any need to be initialized"
for i in range(1, len(self.poses)):
pose = self.poses[i]
if not pose.bDeviceIsConnected:
continue
if ... | [] |
Please provide a description of the function:def keyPressEvent(self, event):
"press ESCAPE to quit the application"
key = event.key()
if key == Qt.Key_Escape:
self.app.quit() | [] |
Please provide a description of the function:def getGenericInterface(interfaceVersion):
error = EVRInitError()
result = _openvr.VR_GetGenericInterface(interfaceVersion, byref(error))
_checkInitError(error.value)
return result | [
"\n Returns the interface of the specified version. This method must be called after VR_Init. The\r\n pointer returned is valid until VR_Shutdown is called.\n "
] |
Please provide a description of the function:def getRecommendedRenderTargetSize(self):
fn = self.function_table.getRecommendedRenderTargetSize
pnWidth = c_uint32()
pnHeight = c_uint32()
fn(byref(pnWidth), byref(pnHeight))
return pnWidth.value, pnHeight.value | [
"Suggested size for the intermediate render target that the distortion pulls from."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.