body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def Update(self, request, context):
'Update an existing organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | 7,422,785,294,231,557,000 | Update an existing organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | Update | GaiaFL/chirpstack-api | python | def Update(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def Delete(self, request, context):
'Delete an organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | 6,167,222,203,331,012,000 | Delete an organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | Delete | GaiaFL/chirpstack-api | python | def Delete(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def ListUsers(self, request, context):
"Get organization's user list.\n "
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -307,360,098,556,259,500 | Get organization's user list. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | ListUsers | GaiaFL/chirpstack-api | python | def ListUsers(self, request, context):
"\n "
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def GetUser(self, request, context):
'Get data for a particular organization user.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -4,923,811,219,087,573,000 | Get data for a particular organization user. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | GetUser | GaiaFL/chirpstack-api | python | def GetUser(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def AddUser(self, request, context):
'Add a new user to an organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -4,596,004,449,455,495,700 | Add a new user to an organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | AddUser | GaiaFL/chirpstack-api | python | def AddUser(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def UpdateUser(self, request, context):
'Update a user in an organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | 4,537,644,656,659,038,000 | Update a user in an organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | UpdateUser | GaiaFL/chirpstack-api | python | def UpdateUser(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def DeleteUser(self, request, context):
'Delete a user from an organization.\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | -8,003,106,685,235,128,000 | Delete a user from an organization. | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | DeleteUser | GaiaFL/chirpstack-api | python | def DeleteUser(self, request, context):
'\n '
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') |
def has_pywin32():
"\n Does this environment have pywin32?\n Should return False even when Mercurial's Demand Import allowed import of\n win32cred.\n "
with ExceptionRaisedContext() as exc:
win32cred.__name__
return (not bool(exc)) | -7,351,007,536,469,651,000 | Does this environment have pywin32?
Should return False even when Mercurial's Demand Import allowed import of
win32cred. | src/site-packages/keyrings/alt/Windows.py | has_pywin32 | nficano/alexa-find-my-iphone | python | def has_pywin32():
"\n Does this environment have pywin32?\n Should return False even when Mercurial's Demand Import allowed import of\n win32cred.\n "
with ExceptionRaisedContext() as exc:
win32cred.__name__
return (not bool(exc)) |
def has_wincrypto():
"\n Does this environment have wincrypto?\n Should return False even when Mercurial's Demand Import allowed import of\n _win_crypto, so accesses an attribute of the module.\n "
with ExceptionRaisedContext() as exc:
_win_crypto.__name__
return (not bool(exc)) | -6,387,045,016,494,770,000 | Does this environment have wincrypto?
Should return False even when Mercurial's Demand Import allowed import of
_win_crypto, so accesses an attribute of the module. | src/site-packages/keyrings/alt/Windows.py | has_wincrypto | nficano/alexa-find-my-iphone | python | def has_wincrypto():
"\n Does this environment have wincrypto?\n Should return False even when Mercurial's Demand Import allowed import of\n _win_crypto, so accesses an attribute of the module.\n "
with ExceptionRaisedContext() as exc:
_win_crypto.__name__
return (not bool(exc)) |
@properties.ClassProperty
@classmethod
def priority(self):
'\n Preferred over file.EncryptedKeyring but not other, more sophisticated\n Windows backends.\n '
if (not (platform.system() == 'Windows')):
raise RuntimeError('Requires Windows')
return 0.8 | 1,551,983,717,609,327,600 | Preferred over file.EncryptedKeyring but not other, more sophisticated
Windows backends. | src/site-packages/keyrings/alt/Windows.py | priority | nficano/alexa-find-my-iphone | python | @properties.ClassProperty
@classmethod
def priority(self):
'\n Preferred over file.EncryptedKeyring but not other, more sophisticated\n Windows backends.\n '
if (not (platform.system() == 'Windows')):
raise RuntimeError('Requires Windows')
return 0.8 |
def encrypt(self, password):
'Encrypt the password using the CryptAPI.\n '
return _win_crypto.encrypt(password) | -5,918,730,288,420,528,000 | Encrypt the password using the CryptAPI. | src/site-packages/keyrings/alt/Windows.py | encrypt | nficano/alexa-find-my-iphone | python | def encrypt(self, password):
'\n '
return _win_crypto.encrypt(password) |
def decrypt(self, password_encrypted):
'Decrypt the password using the CryptAPI.\n '
return _win_crypto.decrypt(password_encrypted) | -1,593,266,222,747,378,200 | Decrypt the password using the CryptAPI. | src/site-packages/keyrings/alt/Windows.py | decrypt | nficano/alexa-find-my-iphone | python | def decrypt(self, password_encrypted):
'\n '
return _win_crypto.decrypt(password_encrypted) |
@properties.ClassProperty
@classmethod
def priority(self):
"\n Preferred on Windows when pywin32 isn't installed\n "
if (platform.system() != 'Windows'):
raise RuntimeError('Requires Windows')
if (not has_wincrypto()):
raise RuntimeError('Requires ctypes')
return 2 | 1,881,900,591,926,196,200 | Preferred on Windows when pywin32 isn't installed | src/site-packages/keyrings/alt/Windows.py | priority | nficano/alexa-find-my-iphone | python | @properties.ClassProperty
@classmethod
def priority(self):
"\n \n "
if (platform.system() != 'Windows'):
raise RuntimeError('Requires Windows')
if (not has_wincrypto()):
raise RuntimeError('Requires ctypes')
return 2 |
def get_password(self, service, username):
'Get password of the username for the service\n '
try:
key = ('Software\\%s\\Keyring' % service)
hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
password_saved = winreg.QueryValueEx(hkey, username)[0]
password_base64 = passwo... | -6,747,333,599,557,987,000 | Get password of the username for the service | src/site-packages/keyrings/alt/Windows.py | get_password | nficano/alexa-find-my-iphone | python | def get_password(self, service, username):
'\n '
try:
key = ('Software\\%s\\Keyring' % service)
hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
password_saved = winreg.QueryValueEx(hkey, username)[0]
password_base64 = password_saved.encode('ascii')
password_en... |
def set_password(self, service, username, password):
'Write the password to the registry\n '
password_encrypted = _win_crypto.encrypt(password.encode('utf-8'))
password_base64 = base64.encodestring(password_encrypted)
password_saved = password_base64.decode('ascii')
key_name = ('Software\\%s\... | 6,056,869,806,802,730,000 | Write the password to the registry | src/site-packages/keyrings/alt/Windows.py | set_password | nficano/alexa-find-my-iphone | python | def set_password(self, service, username, password):
'\n '
password_encrypted = _win_crypto.encrypt(password.encode('utf-8'))
password_base64 = base64.encodestring(password_encrypted)
password_saved = password_base64.decode('ascii')
key_name = ('Software\\%s\\Keyring' % service)
hkey = wi... |
def delete_password(self, service, username):
'Delete the password for the username of the service.\n '
try:
key_name = ('Software\\%s\\Keyring' % service)
hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS)
winreg.DeleteValue(hkey, username)
... | -3,171,431,112,783,877,600 | Delete the password for the username of the service. | src/site-packages/keyrings/alt/Windows.py | delete_password | nficano/alexa-find-my-iphone | python | def delete_password(self, service, username):
'\n '
try:
key_name = ('Software\\%s\\Keyring' % service)
hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS)
winreg.DeleteValue(hkey, username)
winreg.CloseKey(hkey)
except WindowsError:
... |
def __contains__(self, t):
' t in this '
for (k, v) in self.__dict__.items():
if (k == t):
return True
if isinstance(v, DictToAttrDeep):
if (t in v):
return True | -3,873,695,675,860,616,700 | t in this | rulemanager.py | __contains__ | n44hernandezp/openschc | python | def __contains__(self, t):
' '
for (k, v) in self.__dict__.items():
if (k == t):
return True
if isinstance(v, DictToAttrDeep):
if (t in v):
return True |
def __getitem__(self, t):
' this[k] '
for (k, v) in self.__dict__.items():
if (k == t):
return v
if isinstance(v, DictToAttrDeep):
if (t in v):
return v[t] | 521,882,756,960,341,760 | this[k] | rulemanager.py | __getitem__ | n44hernandezp/openschc | python | def __getitem__(self, t):
' '
for (k, v) in self.__dict__.items():
if (k == t):
return v
if isinstance(v, DictToAttrDeep):
if (t in v):
return v[t] |
def get(self, k, d=None):
' this.get(k) '
if (k not in self):
return d
return self.__getitem__(k) | -6,245,523,393,949,625,000 | this.get(k) | rulemanager.py | get | n44hernandezp/openschc | python | def get(self, k, d=None):
' '
if (k not in self):
return d
return self.__getitem__(k) |
def _checkRuleValue(self, rule_id, rule_id_length):
'this function looks if bits specified in ruleID are not outside of\n rule_id_length'
if (rule_id_length > 32):
raise ValueError('Rule length should be less than 32')
r1 = rule_id
for k in range(32, rule_id_length, (- 1)):
if (((... | 7,033,565,771,389,573,000 | this function looks if bits specified in ruleID are not outside of
rule_id_length | rulemanager.py | _checkRuleValue | n44hernandezp/openschc | python | def _checkRuleValue(self, rule_id, rule_id_length):
'this function looks if bits specified in ruleID are not outside of\n rule_id_length'
if (rule_id_length > 32):
raise ValueError('Rule length should be less than 32')
r1 = rule_id
for k in range(32, rule_id_length, (- 1)):
if (((... |
def _ruleIncluded(self, r1ID, r1l, r2ID, r2l):
'check if a conflict exists between to ruleID (i.e. same first bits equals) '
r1 = (r1ID << (32 - r1l))
r2 = (r2ID << (32 - r2l))
l = min(r1l, r2l)
for k in range((32 - l), 32):
if ((r1 & (1 << k)) != (r2 & (1 << k))):
return False
... | 4,394,786,761,340,157,400 | check if a conflict exists between to ruleID (i.e. same first bits equals) | rulemanager.py | _ruleIncluded | n44hernandezp/openschc | python | def _ruleIncluded(self, r1ID, r1l, r2ID, r2l):
' '
r1 = (r1ID << (32 - r1l))
r2 = (r2ID << (32 - r2l))
l = min(r1l, r2l)
for k in range((32 - l), 32):
if ((r1 & (1 << k)) != (r2 & (1 << k))):
return False
return True |
def find_rule_bypacket(self, context, packet_bbuf):
' returns a compression rule or an fragmentation rule\n in the context matching with the field value of rule id in the packet.\n '
for k in ['fragSender', 'fragReceiver', 'fragSender2', 'fragReceiver2', 'comp']:
r = context.get(k)
... | -8,728,772,641,255,952,000 | returns a compression rule or an fragmentation rule
in the context matching with the field value of rule id in the packet. | rulemanager.py | find_rule_bypacket | n44hernandezp/openschc | python | def find_rule_bypacket(self, context, packet_bbuf):
' returns a compression rule or an fragmentation rule\n in the context matching with the field value of rule id in the packet.\n '
for k in ['fragSender', 'fragReceiver', 'fragSender2', 'fragReceiver2', 'comp']:
r = context.get(k)
... |
def find_context_bydevL2addr(self, dev_L2addr):
' find a context with dev_L2addr. '
for c in self._db:
if (c['devL2Addr'] == dev_L2addr):
return c
if (c['devL2Addr'] == '*'):
return c
return None | 6,848,620,013,530,425,000 | find a context with dev_L2addr. | rulemanager.py | find_context_bydevL2addr | n44hernandezp/openschc | python | def find_context_bydevL2addr(self, dev_L2addr):
' '
for c in self._db:
if (c['devL2Addr'] == dev_L2addr):
return c
if (c['devL2Addr'] == '*'):
return c
return None |
def find_context_bydstiid(self, dst_iid):
' find a context with dst_iid, which can be a wild card. '
for c in self._db:
if (c['dstIID'] == dst_iid):
return c
if (c['dstIID'] == '*'):
return c
return None | -5,258,360,269,052,741,000 | find a context with dst_iid, which can be a wild card. | rulemanager.py | find_context_bydstiid | n44hernandezp/openschc | python | def find_context_bydstiid(self, dst_iid):
' '
for c in self._db:
if (c['dstIID'] == dst_iid):
return c
if (c['dstIID'] == '*'):
return c
return None |
def find_context_exact(self, dev_L2addr, dst_iid):
' find a context by both devL2Addr and dstIID.\n This is mainly for internal use. '
for c in self._db:
if ((c['devL2Addr'] == dev_L2addr) and (c['dstIID'] == dst_iid)):
return c
return None | 7,843,116,249,667,408,000 | find a context by both devL2Addr and dstIID.
This is mainly for internal use. | rulemanager.py | find_context_exact | n44hernandezp/openschc | python | def find_context_exact(self, dev_L2addr, dst_iid):
' find a context by both devL2Addr and dstIID.\n This is mainly for internal use. '
for c in self._db:
if ((c['devL2Addr'] == dev_L2addr) and (c['dstIID'] == dst_iid)):
return c
return None |
def add_context(self, context, comp=None, fragSender=None, fragReceiver=None, fragSender2=None, fragReceiver2=None):
' add context into the db. '
if (self.find_context_exact(context['devL2Addr'], context['dstIID']) is not None):
raise ValueError('the context {}/{} exist.'.format(context['devL2Addr'], co... | 4,446,036,947,611,640,300 | add context into the db. | rulemanager.py | add_context | n44hernandezp/openschc | python | def add_context(self, context, comp=None, fragSender=None, fragReceiver=None, fragSender2=None, fragReceiver2=None):
' '
if (self.find_context_exact(context['devL2Addr'], context['dstIID']) is not None):
raise ValueError('the context {}/{} exist.'.format(context['devL2Addr'], context['dstIID']))
c ... |
def add_rules(self, context, comp=None, fragSender=None, fragReceiver=None, fragSender2=None, fragReceiver2=None):
' add rules into the context specified. '
if (comp is not None):
self.add_rule(context, 'comp', comp)
if (fragSender is not None):
self.add_rule(context, 'fragSender', fragSende... | 3,261,218,258,141,239,300 | add rules into the context specified. | rulemanager.py | add_rules | n44hernandezp/openschc | python | def add_rules(self, context, comp=None, fragSender=None, fragReceiver=None, fragSender2=None, fragReceiver2=None):
' '
if (comp is not None):
self.add_rule(context, 'comp', comp)
if (fragSender is not None):
self.add_rule(context, 'fragSender', fragSender)
if (fragReceiver is not None):... |
def add_rule(self, context, key, rule):
' Check rule integrity and uniqueless and add it to the db '
if (not ('ruleID' in rule)):
raise ValueError('Rule ID not defined.')
if (not ('ruleLength' in rule)):
if (rule['ruleID'] < 255):
rule['ruleLength'] = 8
else:
... | 7,021,694,655,899,434,000 | Check rule integrity and uniqueless and add it to the db | rulemanager.py | add_rule | n44hernandezp/openschc | python | def add_rule(self, context, key, rule):
' '
if (not ('ruleID' in rule)):
raise ValueError('Rule ID not defined.')
if (not ('ruleLength' in rule)):
if (rule['ruleID'] < 255):
rule['ruleLength'] = 8
else:
raise ValueError('RuleID too large for default size on a... |
def check_rule_compression(self, rule):
' compression rule check '
if ((not ('compression' in rule)) or ('fragmentation' in rule)):
raise ValueError('{} Invalid rule'.format(self._nameRule(rule)))
canon_rule_set = []
for r in rule['compression']['rule_set']:
canon_r = {}
for (k, ... | 2,203,879,224,705,384,400 | compression rule check | rulemanager.py | check_rule_compression | n44hernandezp/openschc | python | def check_rule_compression(self, rule):
' '
if ((not ('compression' in rule)) or ('fragmentation' in rule)):
raise ValueError('{} Invalid rule'.format(self._nameRule(rule)))
canon_rule_set = []
for r in rule['compression']['rule_set']:
canon_r = {}
for (k, v) in r.items():
... |
def check_rule_fragmentation(self, rule):
' fragmentation rule check '
if ((not ('fragmentation' in rule)) or ('compression' in rule)):
raise ValueError('{} Invalid rule'.format(self._nameRule(rule)))
if ('fragmentation' in rule):
fragRule = rule['fragmentation']
if (not ('FRMode' in... | -3,439,352,066,574,126,600 | fragmentation rule check | rulemanager.py | check_rule_fragmentation | n44hernandezp/openschc | python | def check_rule_fragmentation(self, rule):
' '
if ((not ('fragmentation' in rule)) or ('compression' in rule)):
raise ValueError('{} Invalid rule'.format(self._nameRule(rule)))
if ('fragmentation' in rule):
fragRule = rule['fragmentation']
if (not ('FRMode' in fragRule)):
... |
def adjust_bbox(fig, format, bbox_inches):
'\n Temporarily adjust the figure so that only the specified area\n (bbox_inches) is saved.\n\n It modifies fig.bbox, fig.bbox_inches,\n fig.transFigure._boxout, and fig.patch. While the figure size\n changes, the scale of the original figure is conserved. ... | 8,733,391,175,678,230,000 | Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifies fig.bbox, fig.bbox_inches,
fig.transFigure._boxout, and fig.patch. While the figure size
changes, the scale of the original figure is conserved. A
function which restores the original values are returned. | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | adjust_bbox | mattl1598/Project-Mochachino | python | def adjust_bbox(fig, format, bbox_inches):
'\n Temporarily adjust the figure so that only the specified area\n (bbox_inches) is saved.\n\n It modifies fig.bbox, fig.bbox_inches,\n fig.transFigure._boxout, and fig.patch. While the figure size\n changes, the scale of the original figure is conserved. ... |
def adjust_bbox_png(fig, bbox_inches):
'\n adjust_bbox for png (Agg) format\n '
tr = fig.dpi_scale_trans
_bbox = TransformedBbox(bbox_inches, tr)
(x0, y0) = (_bbox.x0, _bbox.y0)
fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height)
(x0, y0) = (_bbox.x0, _bbox.y0)
... | 3,590,841,682,367,379,000 | adjust_bbox for png (Agg) format | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | adjust_bbox_png | mattl1598/Project-Mochachino | python | def adjust_bbox_png(fig, bbox_inches):
'\n \n '
tr = fig.dpi_scale_trans
_bbox = TransformedBbox(bbox_inches, tr)
(x0, y0) = (_bbox.x0, _bbox.y0)
fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height)
(x0, y0) = (_bbox.x0, _bbox.y0)
(w1, h1) = (fig.bbox.width, ... |
def adjust_bbox_pdf(fig, bbox_inches):
'\n adjust_bbox for pdf & eps format\n '
if (fig._cachedRenderer.__class__.__name__ == 'RendererPgf'):
tr = Affine2D().scale(fig.dpi)
f = 1.0
else:
tr = Affine2D().scale(72)
f = (72.0 / fig.dpi)
_bbox = TransformedBbox(bbox_inc... | 6,674,782,105,807,579,000 | adjust_bbox for pdf & eps format | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | adjust_bbox_pdf | mattl1598/Project-Mochachino | python | def adjust_bbox_pdf(fig, bbox_inches):
'\n \n '
if (fig._cachedRenderer.__class__.__name__ == 'RendererPgf'):
tr = Affine2D().scale(fig.dpi)
f = 1.0
else:
tr = Affine2D().scale(72)
f = (72.0 / fig.dpi)
_bbox = TransformedBbox(bbox_inches, tr)
fig.bbox_inches = B... |
def process_figure_for_rasterizing(figure, bbox_inches_restore, mode):
'\n This need to be called when figure dpi changes during the drawing\n (e.g., rasterizing). It recovers the bbox and re-adjust it with\n the new dpi.\n '
(bbox_inches, restore_bbox) = bbox_inches_restore
restore_bbox()
r... | 424,844,068,388,893,500 | This need to be called when figure dpi changes during the drawing
(e.g., rasterizing). It recovers the bbox and re-adjust it with
the new dpi. | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | process_figure_for_rasterizing | mattl1598/Project-Mochachino | python | def process_figure_for_rasterizing(figure, bbox_inches_restore, mode):
'\n This need to be called when figure dpi changes during the drawing\n (e.g., rasterizing). It recovers the bbox and re-adjust it with\n the new dpi.\n '
(bbox_inches, restore_bbox) = bbox_inches_restore
restore_bbox()
r... |
def validate_authorization_request(self):
'The client constructs the request URI by adding the following\n parameters to the query component of the authorization endpoint URI\n using the "application/x-www-form-urlencoded" format.\n Per `Section 4.2.1`_.\n\n response_type\n R... | -2,264,537,786,648,840,400 | The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format.
Per `Section 4.2.1`_.
response_type
REQUIRED. Value MUST be set to "token".
client_id
REQUIRED. The client identifier as d... | authlib/oauth2/rfc6749/grants/implicit.py | validate_authorization_request | 2tunnels/authlib | python | def validate_authorization_request(self):
'The client constructs the request URI by adding the following\n parameters to the query component of the authorization endpoint URI\n using the "application/x-www-form-urlencoded" format.\n Per `Section 4.2.1`_.\n\n response_type\n R... |
def create_authorization_response(self, redirect_uri, grant_user):
'If the resource owner grants the access request, the authorization\n server issues an access token and delivers it to the client by adding\n the following parameters to the fragment component of the redirection\n URI using the ... | -206,207,470,362,243,260 | If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format.
Per `Section 4.2.2`_.
access_token
REQUIRED. The... | authlib/oauth2/rfc6749/grants/implicit.py | create_authorization_response | 2tunnels/authlib | python | def create_authorization_response(self, redirect_uri, grant_user):
'If the resource owner grants the access request, the authorization\n server issues an access token and delivers it to the client by adding\n the following parameters to the fragment component of the redirection\n URI using the ... |
def combination(n, r):
'\n :param n: the count of different items\n :param r: the number of select\n :return: combination\n n! / (r! * (n - r)!)\n '
r = min((n - r), r)
result = 1
for i in range(n, (n - r), (- 1)):
result *= i
for i in range(1, (r + 1)):
result //= i
... | -5,737,441,407,772,606,000 | :param n: the count of different items
:param r: the number of select
:return: combination
n! / (r! * (n - r)!) | lib/python-lib/combination.py | combination | ta7uw/atcoder | python | def combination(n, r):
'\n :param n: the count of different items\n :param r: the number of select\n :return: combination\n n! / (r! * (n - r)!)\n '
r = min((n - r), r)
result = 1
for i in range(n, (n - r), (- 1)):
result *= i
for i in range(1, (r + 1)):
result //= i
... |
@cell
def cdsem_straight(widths: Tuple[(float, ...)]=(0.4, 0.45, 0.5, 0.6, 0.8, 1.0), length: float=LINE_LENGTH, cross_section: CrossSectionFactory=strip, text: Optional[ComponentFactory]=text_rectangular_mini, spacing: float=3) -> Component:
'Returns straight waveguide lines width sweep.\n\n Args:\n widt... | 8,057,996,998,196,953,000 | Returns straight waveguide lines width sweep.
Args:
widths: for the sweep
length: for the line
cross_section: for the lines
text: optional text for labels
spacing: edge to edge spacing | gdsfactory/components/cdsem_straight.py | cdsem_straight | gdsfactory/gdsfactory | python | @cell
def cdsem_straight(widths: Tuple[(float, ...)]=(0.4, 0.45, 0.5, 0.6, 0.8, 1.0), length: float=LINE_LENGTH, cross_section: CrossSectionFactory=strip, text: Optional[ComponentFactory]=text_rectangular_mini, spacing: float=3) -> Component:
'Returns straight waveguide lines width sweep.\n\n Args:\n widt... |
def write(self, value: int, from_hw: bool) -> int:
'Stage the effects of writing a value (see RGReg.write)'
assert (value >= 0)
masked = (value & ((1 << self.width) - 1))
if (self.read_only and (not from_hw)):
pass
elif (self.w1c and (not from_hw)):
self.next_value &= (~ masked)
... | 981,121,838,863,917,000 | Stage the effects of writing a value (see RGReg.write) | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | write | Daasin/FOSS-fTPM | python | def write(self, value: int, from_hw: bool) -> int:
assert (value >= 0)
masked = (value & ((1 << self.width) - 1))
if (self.read_only and (not from_hw)):
pass
elif (self.w1c and (not from_hw)):
self.next_value &= (~ masked)
else:
self.next_value = masked
return self._... |
def set_bits(self, value: int) -> int:
'Like write, but |=.'
masked = (value & ((1 << self.width) - 1))
self.next_value |= masked
return self._next_sw_read() | 8,974,269,918,986,983,000 | Like write, but |=. | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | set_bits | Daasin/FOSS-fTPM | python | def set_bits(self, value: int) -> int:
masked = (value & ((1 << self.width) - 1))
self.next_value |= masked
return self._next_sw_read() |
def clear_bits(self, value: int) -> int:
'Like write, but &= ~.'
self.next_value &= (~ value)
return self._next_sw_read() | 1,797,275,488,805,924,000 | Like write, but &= ~. | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | clear_bits | Daasin/FOSS-fTPM | python | def clear_bits(self, value: int) -> int:
self.next_value &= (~ value)
return self._next_sw_read() |
def write(self, value: int, from_hw: bool) -> None:
'Stage the effects of writing a value.\n\n If from_hw is true, this write is from OTBN hardware (rather than the\n bus).\n\n '
assert (value >= 0)
now = self._apply_fields((lambda fld, fv: fld.write(fv, from_hw)), value)
trace = (s... | 1,804,722,120,910,216,000 | Stage the effects of writing a value.
If from_hw is true, this write is from OTBN hardware (rather than the
bus). | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | write | Daasin/FOSS-fTPM | python | def write(self, value: int, from_hw: bool) -> None:
'Stage the effects of writing a value.\n\n If from_hw is true, this write is from OTBN hardware (rather than the\n bus).\n\n '
assert (value >= 0)
now = self._apply_fields((lambda fld, fv: fld.write(fv, from_hw)), value)
trace = (s... |
def write(self, reg_name: str, value: int, from_hw: bool) -> None:
'Stage the effects of writing a value to a register'
assert (value >= 0)
self._get_reg(reg_name).write(value, from_hw)
self._dirty = 2 | -2,695,661,009,836,998,000 | Stage the effects of writing a value to a register | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | write | Daasin/FOSS-fTPM | python | def write(self, reg_name: str, value: int, from_hw: bool) -> None:
assert (value >= 0)
self._get_reg(reg_name).write(value, from_hw)
self._dirty = 2 |
def set_bits(self, reg_name: str, value: int) -> None:
'Set some bits of a register (HW access only)'
assert (value >= 0)
self._get_reg(reg_name).set_bits(value)
self._dirty = 2 | -3,031,869,466,492,627,000 | Set some bits of a register (HW access only) | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | set_bits | Daasin/FOSS-fTPM | python | def set_bits(self, reg_name: str, value: int) -> None:
assert (value >= 0)
self._get_reg(reg_name).set_bits(value)
self._dirty = 2 |
def increment_insn_cnt(self) -> None:
'Increment the INSN_CNT register'
reg = self._get_reg('INSN_CNT')
assert (len(reg.fields) == 1)
fld = reg.fields[0]
reg.write(min((fld.value + 1), ((1 << 32) - 1)), True)
self._dirty = 2 | 6,531,003,870,117,979,000 | Increment the INSN_CNT register | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | increment_insn_cnt | Daasin/FOSS-fTPM | python | def increment_insn_cnt(self) -> None:
reg = self._get_reg('INSN_CNT')
assert (len(reg.fields) == 1)
fld = reg.fields[0]
reg.write(min((fld.value + 1), ((1 << 32) - 1)), True)
self._dirty = 2 |
def rollout(self, **args):
" Return a list of dicts containing instr_id:'xx', path:[(viewpointId, heading_rad, elevation_rad)] "
raise NotImplementedError | 5,032,299,443,237,458,000 | Return a list of dicts containing instr_id:'xx', path:[(viewpointId, heading_rad, elevation_rad)] | r2r_src/agent.py | rollout | rcorona/R2R-EnvDrop | python | def rollout(self, **args):
" "
raise NotImplementedError |
def _sort_batch(self, obs):
' Extract instructions from a list of observations and sort by descending\n sequence length (to enable PyTorch packing). '
seq_tensor = np.array([ob['instr_encoding'] for ob in obs])
seq_lengths = np.argmax((seq_tensor == padding_idx), axis=1)
seq_lengths[(seq_leng... | 8,841,784,052,885,048,000 | Extract instructions from a list of observations and sort by descending
sequence length (to enable PyTorch packing). | r2r_src/agent.py | _sort_batch | rcorona/R2R-EnvDrop | python | def _sort_batch(self, obs):
' Extract instructions from a list of observations and sort by descending\n sequence length (to enable PyTorch packing). '
seq_tensor = np.array([ob['instr_encoding'] for ob in obs])
seq_lengths = np.argmax((seq_tensor == padding_idx), axis=1)
seq_lengths[(seq_leng... |
def _feature_variable(self, obs):
' Extract precomputed features into variable. '
features = np.empty((len(obs), args.views, (self.feature_size + args.angle_feat_size)), dtype=np.float32)
for (i, ob) in enumerate(obs):
features[i, :, :] = ob['feature']
return Variable(torch.from_numpy(features),... | -5,244,354,546,349,609,000 | Extract precomputed features into variable. | r2r_src/agent.py | _feature_variable | rcorona/R2R-EnvDrop | python | def _feature_variable(self, obs):
' '
features = np.empty((len(obs), args.views, (self.feature_size + args.angle_feat_size)), dtype=np.float32)
for (i, ob) in enumerate(obs):
features[i, :, :] = ob['feature']
return Variable(torch.from_numpy(features), requires_grad=False).cuda() |
def _teacher_action(self, obs, ended):
'\n Extract teacher actions into variable.\n :param obs: The observation.\n :param ended: Whether the action seq is ended\n :return:\n '
a = np.zeros(len(obs), dtype=np.int64)
for (i, ob) in enumerate(obs):
if ended[i]:
... | -6,105,101,396,949,073,000 | Extract teacher actions into variable.
:param obs: The observation.
:param ended: Whether the action seq is ended
:return: | r2r_src/agent.py | _teacher_action | rcorona/R2R-EnvDrop | python | def _teacher_action(self, obs, ended):
'\n Extract teacher actions into variable.\n :param obs: The observation.\n :param ended: Whether the action seq is ended\n :return:\n '
a = np.zeros(len(obs), dtype=np.int64)
for (i, ob) in enumerate(obs):
if ended[i]:
... |
def make_equiv_action(self, a_t, perm_obs, perm_idx=None, traj=None):
'\n Interface between Panoramic view and Egocentric view \n It will convert the action panoramic view action a_t to equivalent egocentric view actions for the simulator\n '
def take_action(i, idx, name):
if (type... | 1,658,864,895,377,073,200 | Interface between Panoramic view and Egocentric view
It will convert the action panoramic view action a_t to equivalent egocentric view actions for the simulator | r2r_src/agent.py | make_equiv_action | rcorona/R2R-EnvDrop | python | def make_equiv_action(self, a_t, perm_obs, perm_idx=None, traj=None):
'\n Interface between Panoramic view and Egocentric view \n It will convert the action panoramic view action a_t to equivalent egocentric view actions for the simulator\n '
def take_action(i, idx, name):
if (type... |
def rollout(self, train_ml=None, train_rl=True, reset=True, speaker=None):
'\n :param train_ml: The weight to train with maximum likelihood\n :param train_rl: whether use RL in training\n :param reset: Reset the environment\n :param speaker: Speaker used in back translati... | -5,757,432,292,980,751,000 | :param train_ml: The weight to train with maximum likelihood
:param train_rl: whether use RL in training
:param reset: Reset the environment
:param speaker: Speaker used in back translation.
If the speaker is not None, use back translation.
O.w., normal training
:... | r2r_src/agent.py | rollout | rcorona/R2R-EnvDrop | python | def rollout(self, train_ml=None, train_rl=True, reset=True, speaker=None):
'\n :param train_ml: The weight to train with maximum likelihood\n :param train_rl: whether use RL in training\n :param reset: Reset the environment\n :param speaker: Speaker used in back translati... |
def _dijkstra(self):
'\n The dijkstra algorithm.\n Was called beam search to be consistent with existing work.\n But it actually finds the Exact K paths with smallest listener log_prob.\n :return:\n [{\n "scan": XXX\n "instr_id":XXX,\n \'instr_enco... | -1,167,941,217,106,676,200 | The dijkstra algorithm.
Was called beam search to be consistent with existing work.
But it actually finds the Exact K paths with smallest listener log_prob.
:return:
[{
"scan": XXX
"instr_id":XXX,
'instr_encoding": XXX
'dijk_path': [v1, v2, ..., vn] (The path used for find all the candidates)
"... | r2r_src/agent.py | _dijkstra | rcorona/R2R-EnvDrop | python | def _dijkstra(self):
'\n The dijkstra algorithm.\n Was called beam search to be consistent with existing work.\n But it actually finds the Exact K paths with smallest listener log_prob.\n :return:\n [{\n "scan": XXX\n "instr_id":XXX,\n \'instr_enco... |
def beam_search(self, speaker):
'\n :param speaker: The speaker to be used in searching.\n :return:\n {\n "scan": XXX\n "instr_id":XXX,\n "instr_encoding": XXX\n "dijk_path": [v1, v2, ...., vn]\n "paths": [{\n "trajectory": [... | -8,871,821,870,732,488,000 | :param speaker: The speaker to be used in searching.
:return:
{
"scan": XXX
"instr_id":XXX,
"instr_encoding": XXX
"dijk_path": [v1, v2, ...., vn]
"paths": [{
"trajectory": [viewoint_id0, viewpoint_id1, viewpoint_id2, ..., ],
"action": [act_1, act_2, ..., ],
"listener_scores":... | r2r_src/agent.py | beam_search | rcorona/R2R-EnvDrop | python | def beam_search(self, speaker):
'\n :param speaker: The speaker to be used in searching.\n :return:\n {\n "scan": XXX\n "instr_id":XXX,\n "instr_encoding": XXX\n "dijk_path": [v1, v2, ...., vn]\n "paths": [{\n "trajectory": [... |
def test(self, use_dropout=False, feedback='argmax', allow_cheat=False, iters=None):
' Evaluate once on each instruction in the current environment '
self.feedback = feedback
if use_dropout:
self.encoder.train()
self.decoder.train()
self.critic.train()
else:
self.encoder.... | 4,978,732,549,777,399,000 | Evaluate once on each instruction in the current environment | r2r_src/agent.py | test | rcorona/R2R-EnvDrop | python | def test(self, use_dropout=False, feedback='argmax', allow_cheat=False, iters=None):
' '
self.feedback = feedback
if use_dropout:
self.encoder.train()
self.decoder.train()
self.critic.train()
else:
self.encoder.eval()
self.decoder.eval()
self.critic.eval(... |
def train(self, n_iters, feedback='teacher', **kwargs):
' Train for a given number of iterations '
self.feedback = feedback
self.encoder.train()
self.decoder.train()
self.critic.train()
self.losses = []
for iter in tqdm(range(1, (n_iters + 1))):
self.encoder_optimizer.zero_grad()
... | 8,232,530,218,817,938,000 | Train for a given number of iterations | r2r_src/agent.py | train | rcorona/R2R-EnvDrop | python | def train(self, n_iters, feedback='teacher', **kwargs):
' '
self.feedback = feedback
self.encoder.train()
self.decoder.train()
self.critic.train()
self.losses = []
for iter in tqdm(range(1, (n_iters + 1))):
self.encoder_optimizer.zero_grad()
self.decoder_optimizer.zero_grad(... |
def save(self, epoch, path):
' Snapshot models '
(the_dir, _) = os.path.split(path)
os.makedirs(the_dir, exist_ok=True)
states = {}
def create_state(name, model, optimizer):
states[name] = {'epoch': (epoch + 1), 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}
all_... | -2,901,870,798,852,050,400 | Snapshot models | r2r_src/agent.py | save | rcorona/R2R-EnvDrop | python | def save(self, epoch, path):
' '
(the_dir, _) = os.path.split(path)
os.makedirs(the_dir, exist_ok=True)
states = {}
def create_state(name, model, optimizer):
states[name] = {'epoch': (epoch + 1), 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}
all_tuple = [('enco... |
def load(self, path):
' Loads parameters (but not training state) '
states = torch.load(path)
def recover_state(name, model, optimizer):
state = model.state_dict()
model_keys = set(state.keys())
load_keys = set(states[name]['state_dict'].keys())
if (model_keys != load_keys):... | 3,282,851,448,400,201,700 | Loads parameters (but not training state) | r2r_src/agent.py | load | rcorona/R2R-EnvDrop | python | def load(self, path):
' '
states = torch.load(path)
def recover_state(name, model, optimizer):
state = model.state_dict()
model_keys = set(state.keys())
load_keys = set(states[name]['state_dict'].keys())
if (model_keys != load_keys):
print('NOTICE: DIFFERENT KEY... |
def _get_local_ip_address(self):
'\n Gets the local ip address of this computer\n @returns str Local IP address\n '
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip_address = s.getsockname()[0]
s.close()
return local_ip_address | 7,471,134,649,321,523,000 | Gets the local ip address of this computer
@returns str Local IP address | openbci/wifi.py | _get_local_ip_address | daniellasry/OpenBCI_Python | python | def _get_local_ip_address(self):
'\n Gets the local ip address of this computer\n @returns str Local IP address\n '
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip_address = s.getsockname()[0]
s.close()
return local_ip_address |
def getBoardType(self):
' Returns the version of the board '
return self.board_type | -4,757,551,775,959,316,000 | Returns the version of the board | openbci/wifi.py | getBoardType | daniellasry/OpenBCI_Python | python | def getBoardType(self):
' '
return self.board_type |
def setImpedance(self, flag):
' Enable/disable impedance measure '
self.impedance = bool(flag) | -5,800,124,032,592,154,000 | Enable/disable impedance measure | openbci/wifi.py | setImpedance | daniellasry/OpenBCI_Python | python | def setImpedance(self, flag):
' '
self.impedance = bool(flag) |
def connect(self):
' Connect to the board and configure it. Note: recreates various objects upon call. '
if (self.ip_address is None):
raise ValueError('self.ip_address cannot be None')
if self.log:
print(('Init WiFi connection with IP: ' + self.ip_address))
'\n Docs on these HTTP... | -1,779,810,696,293,935,000 | Connect to the board and configure it. Note: recreates various objects upon call. | openbci/wifi.py | connect | daniellasry/OpenBCI_Python | python | def connect(self):
' '
if (self.ip_address is None):
raise ValueError('self.ip_address cannot be None')
if self.log:
print(('Init WiFi connection with IP: ' + self.ip_address))
'\n Docs on these HTTP requests and more are found:\n https://app.swaggerhub.com/apis/pushthewor... |
def init_streaming(self):
' Tell the board to record like crazy. '
res_stream_start = requests.get(('http://%s/stream/start' % self.ip_address))
if (res_stream_start.status_code == 200):
self.streaming = True
self.packets_dropped = 0
self.time_last_packet = timeit.default_timer()
... | -482,764,792,112,558,660 | Tell the board to record like crazy. | openbci/wifi.py | init_streaming | daniellasry/OpenBCI_Python | python | def init_streaming(self):
' '
res_stream_start = requests.get(('http://%s/stream/start' % self.ip_address))
if (res_stream_start.status_code == 200):
self.streaming = True
self.packets_dropped = 0
self.time_last_packet = timeit.default_timer()
else:
raise EnvironmentErro... |
def find_wifi_shield(self, shield_name=None, wifi_shield_cb=None):
'Detects Ganglion board MAC address -- if more than 1 around, will select first. Needs root privilege.'
if self.log:
print('Try to find WiFi shields on your local wireless network')
print(('Scanning for %d seconds nearby devices.... | 9,049,252,316,412,233,000 | Detects Ganglion board MAC address -- if more than 1 around, will select first. Needs root privilege. | openbci/wifi.py | find_wifi_shield | daniellasry/OpenBCI_Python | python | def find_wifi_shield(self, shield_name=None, wifi_shield_cb=None):
if self.log:
print('Try to find WiFi shields on your local wireless network')
print(('Scanning for %d seconds nearby devices...' % self.timeout))
list_ip = []
list_id = []
found_shield = False
def wifi_shield_fo... |
def wifi_write(self, output):
'\n Pass through commands from the WiFi Shield to the Carrier board\n :param output:\n :return:\n '
res_command_post = requests.post(('http://%s/command' % self.ip_address), json={'command': output})
if (res_command_post.status_code == 200):
... | -9,185,579,094,860,822,000 | Pass through commands from the WiFi Shield to the Carrier board
:param output:
:return: | openbci/wifi.py | wifi_write | daniellasry/OpenBCI_Python | python | def wifi_write(self, output):
'\n Pass through commands from the WiFi Shield to the Carrier board\n :param output:\n :return:\n '
res_command_post = requests.post(('http://%s/command' % self.ip_address), json={'command': output})
if (res_command_post.status_code == 200):
... |
def getNbEEGChannels(self):
'Will not get new data on impedance check.'
return self.eeg_channels_per_sample | -2,454,272,197,531,395,600 | Will not get new data on impedance check. | openbci/wifi.py | getNbEEGChannels | daniellasry/OpenBCI_Python | python | def getNbEEGChannels(self):
return self.eeg_channels_per_sample |
def start_streaming(self, callback, lapse=(- 1)):
'\n Start handling streaming data from the board. Call a provided callback\n for every single sample that is processed\n\n Args:\n callback: A callback function -- or a list of functions -- that will receive a single argument of the\n ... | 4,880,693,691,809,626,000 | Start handling streaming data from the board. Call a provided callback
for every single sample that is processed
Args:
callback: A callback function -- or a list of functions -- that will receive a single argument of the
OpenBCISample object captured. | openbci/wifi.py | start_streaming | daniellasry/OpenBCI_Python | python | def start_streaming(self, callback, lapse=(- 1)):
'\n Start handling streaming data from the board. Call a provided callback\n for every single sample that is processed\n\n Args:\n callback: A callback function -- or a list of functions -- that will receive a single argument of the\n ... |
def test_signal(self, signal):
' Enable / disable test signal '
if (signal == 0):
self.warn('Disabling synthetic square wave')
try:
self.wifi_write(']')
except Exception as e:
print(('Something went wrong while setting signal: ' + str(e)))
elif (signal == 1):
... | 7,795,635,748,368,347,000 | Enable / disable test signal | openbci/wifi.py | test_signal | daniellasry/OpenBCI_Python | python | def test_signal(self, signal):
' '
if (signal == 0):
self.warn('Disabling synthetic square wave')
try:
self.wifi_write(']')
except Exception as e:
print(('Something went wrong while setting signal: ' + str(e)))
elif (signal == 1):
self.warn('Enabling ... |
def set_channel(self, channel, toggle_position):
' Enable / disable channels '
try:
if (channel > self.num_channels):
raise ValueError('Cannot set non-existant channel')
if (toggle_position == 1):
if (channel is 1):
self.wifi_write('!')
if (cha... | -451,990,832,647,603,140 | Enable / disable channels | openbci/wifi.py | set_channel | daniellasry/OpenBCI_Python | python | def set_channel(self, channel, toggle_position):
' '
try:
if (channel > self.num_channels):
raise ValueError('Cannot set non-existant channel')
if (toggle_position == 1):
if (channel is 1):
self.wifi_write('!')
if (channel is 2):
... |
def set_sample_rate(self, sample_rate):
' Change sample rate '
try:
if ((self.board_type == k.BOARD_CYTON) or (self.board_type == k.BOARD_DAISY)):
if (sample_rate == 250):
self.wifi_write('~6')
elif (sample_rate == 500):
self.wifi_write('~5')
... | -6,714,558,995,829,764,000 | Change sample rate | openbci/wifi.py | set_sample_rate | daniellasry/OpenBCI_Python | python | def set_sample_rate(self, sample_rate):
' '
try:
if ((self.board_type == k.BOARD_CYTON) or (self.board_type == k.BOARD_DAISY)):
if (sample_rate == 250):
self.wifi_write('~6')
elif (sample_rate == 500):
self.wifi_write('~5')
elif (sampl... |
def set_accelerometer(self, toggle_position):
' Enable / disable accelerometer '
try:
if (self.board_type == k.BOARD_GANGLION):
if (toggle_position == 1):
self.wifi_write('n')
elif (toggle_position == 0):
self.wifi_write('N')
else:
... | -4,555,134,248,605,669,400 | Enable / disable accelerometer | openbci/wifi.py | set_accelerometer | daniellasry/OpenBCI_Python | python | def set_accelerometer(self, toggle_position):
' '
try:
if (self.board_type == k.BOARD_GANGLION):
if (toggle_position == 1):
self.wifi_write('n')
elif (toggle_position == 0):
self.wifi_write('N')
else:
print('Board type not supp... |
def check_connection(self):
' Check connection quality in term of lag and number of packets drop. Reinit connection if necessary. FIXME: parameters given to the board will be lost.'
if (not self.streaming):
return
if (self.packets_dropped > self.max_packets_to_skip):
self.warn('Too many pack... | -7,697,840,872,393,702,000 | Check connection quality in term of lag and number of packets drop. Reinit connection if necessary. FIXME: parameters given to the board will be lost. | openbci/wifi.py | check_connection | daniellasry/OpenBCI_Python | python | def check_connection(self):
' '
if (not self.streaming):
return
if (self.packets_dropped > self.max_packets_to_skip):
self.warn('Too many packets dropped, attempt to reconnect')
self.reconnect()
elif ((self.timeout > 0) and ((timeit.default_timer() - self.time_last_packet) > self... |
def reconnect(self):
' In case of poor connection, will shut down and relaunch everything. FIXME: parameters given to the board will be lost.'
self.warn('Reconnecting')
self.stop()
self.disconnect()
self.connect()
self.init_streaming() | 4,734,633,004,977,587,000 | In case of poor connection, will shut down and relaunch everything. FIXME: parameters given to the board will be lost. | openbci/wifi.py | reconnect | daniellasry/OpenBCI_Python | python | def reconnect(self):
' '
self.warn('Reconnecting')
self.stop()
self.disconnect()
self.connect()
self.init_streaming() |
@used
def type_from_ast(ast_node: ast.AST, visitor: Optional['NameCheckVisitor']=None, ctx: Optional[Context]=None) -> Value:
'Given an AST node representing an annotation, return a\n :class:`Value <pyanalyze.value.Value>`.\n\n :param ast_node: AST node to evaluate.\n\n :param visitor: Visitor class to use... | 6,403,837,150,855,721,000 | Given an AST node representing an annotation, return a
:class:`Value <pyanalyze.value.Value>`.
:param ast_node: AST node to evaluate.
:param visitor: Visitor class to use. This is used in the default
:class:`Context` to resolve names and show errors.
This is ignored if `ctx` is given.
... | pyanalyze/annotations.py | type_from_ast | nbdaaron/pyanalyze | python | @used
def type_from_ast(ast_node: ast.AST, visitor: Optional['NameCheckVisitor']=None, ctx: Optional[Context]=None) -> Value:
'Given an AST node representing an annotation, return a\n :class:`Value <pyanalyze.value.Value>`.\n\n :param ast_node: AST node to evaluate.\n\n :param visitor: Visitor class to use... |
def type_from_runtime(val: object, visitor: Optional['NameCheckVisitor']=None, node: Optional[ast.AST]=None, globals: Optional[Mapping[(str, object)]]=None, ctx: Optional[Context]=None) -> Value:
'Given a runtime annotation object, return a\n :class:`Value <pyanalyze.value.Value>`.\n\n :param val: Object to e... | -3,828,119,079,951,672,300 | Given a runtime annotation object, return a
:class:`Value <pyanalyze.value.Value>`.
:param val: Object to evaluate. This will usually come from an
``__annotations__`` dictionary.
:param visitor: Visitor class to use. This is used in the default
:class:`Context` to resolve names and show er... | pyanalyze/annotations.py | type_from_runtime | nbdaaron/pyanalyze | python | def type_from_runtime(val: object, visitor: Optional['NameCheckVisitor']=None, node: Optional[ast.AST]=None, globals: Optional[Mapping[(str, object)]]=None, ctx: Optional[Context]=None) -> Value:
'Given a runtime annotation object, return a\n :class:`Value <pyanalyze.value.Value>`.\n\n :param val: Object to e... |
def type_from_value(value: Value, visitor: Optional['NameCheckVisitor']=None, node: Optional[ast.AST]=None, ctx: Optional[Context]=None, is_typeddict: bool=False) -> Value:
'Given a :class:`Value <pyanalyze.value.Value` representing an annotation,\n return a :class:`Value <pyanalyze.value.Value>` representing th... | 4,292,624,891,465,387,000 | Given a :class:`Value <pyanalyze.value.Value` representing an annotation,
return a :class:`Value <pyanalyze.value.Value>` representing the type.
The input value represents an expression, the output value represents
a type. For example, the :term:`impl` of ``typing.cast(typ, val)``
calls :func:`type_from_value` on the ... | pyanalyze/annotations.py | type_from_value | nbdaaron/pyanalyze | python | def type_from_value(value: Value, visitor: Optional['NameCheckVisitor']=None, node: Optional[ast.AST]=None, ctx: Optional[Context]=None, is_typeddict: bool=False) -> Value:
'Given a :class:`Value <pyanalyze.value.Value` representing an annotation,\n return a :class:`Value <pyanalyze.value.Value>` representing th... |
def suppress_undefined_names(self) -> ContextManager[None]:
'Temporarily suppress errors about undefined names.'
return qcore.override(self, 'should_suppress_undefined_names', True) | -5,153,936,227,865,077,000 | Temporarily suppress errors about undefined names. | pyanalyze/annotations.py | suppress_undefined_names | nbdaaron/pyanalyze | python | def suppress_undefined_names(self) -> ContextManager[None]:
return qcore.override(self, 'should_suppress_undefined_names', True) |
def show_error(self, message: str, error_code: ErrorCode=ErrorCode.invalid_annotation, node: Optional[ast.AST]=None) -> None:
'Show an error found while evaluating an annotation.'
pass | 8,157,879,884,960,985,000 | Show an error found while evaluating an annotation. | pyanalyze/annotations.py | show_error | nbdaaron/pyanalyze | python | def show_error(self, message: str, error_code: ErrorCode=ErrorCode.invalid_annotation, node: Optional[ast.AST]=None) -> None:
pass |
def get_name(self, node: ast.Name) -> Value:
'Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name.'
return AnyValue(AnySource.inference) | -6,227,226,071,517,584,000 | Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name. | pyanalyze/annotations.py | get_name | nbdaaron/pyanalyze | python | def get_name(self, node: ast.Name) -> Value:
return AnyValue(AnySource.inference) |
def get_name(self, node: ast.Name) -> Value:
'Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name.'
return self.get_name_from_globals(node.id, self.globals) | 4,904,100,106,146,036,000 | Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name. | pyanalyze/annotations.py | get_name | nbdaaron/pyanalyze | python | def get_name(self, node: ast.Name) -> Value:
return self.get_name_from_globals(node.id, self.globals) |
def get_name(self, node: ast.Name) -> Value:
'Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name.'
return self.annotations_context.get_name(node) | 7,946,218,256,446,995,000 | Return the :class:`Value <pyanalyze.value.Value>` corresponding to a name. | pyanalyze/annotations.py | get_name | nbdaaron/pyanalyze | python | def get_name(self, node: ast.Name) -> Value:
return self.annotations_context.get_name(node) |
def __virtual__():
'\n Only return if python-etcd is installed\n '
return (__virtualname__ if HAS_LIBS else False) | 337,201,942,222,086,850 | Only return if python-etcd is installed | salt/pillar/vmware_pillar.py | __virtual__ | aaannz/salt-1 | python | def __virtual__():
'\n \n '
return (__virtualname__ if HAS_LIBS else False) |
def ext_pillar(minion_id, pillar, **kwargs):
'\n Check vmware/vcenter for all data\n '
vmware_pillar = {}
host = None
username = None
password = None
property_types = []
property_name = 'name'
protocol = None
port = None
pillar_key = 'vmware'
replace_default_attributes ... | -1,612,344,056,009,843,000 | Check vmware/vcenter for all data | salt/pillar/vmware_pillar.py | ext_pillar | aaannz/salt-1 | python | def ext_pillar(minion_id, pillar, **kwargs):
'\n \n '
vmware_pillar = {}
host = None
username = None
password = None
property_types = []
property_name = 'name'
protocol = None
port = None
pillar_key = 'vmware'
replace_default_attributes = False
type_specific_pillar_... |
def _recurse_config_to_dict(t_data):
'\n helper function to recurse through a vim object and attempt to return all child objects\n '
if (not isinstance(t_data, type(None))):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_con... | 7,516,975,427,656,124,000 | helper function to recurse through a vim object and attempt to return all child objects | salt/pillar/vmware_pillar.py | _recurse_config_to_dict | aaannz/salt-1 | python | def _recurse_config_to_dict(t_data):
'\n \n '
if (not isinstance(t_data, type(None))):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_config_to_dict(i))
return t_list
elif isinstance(t_data, dict):
... |
def _crawl_attribute(this_data, this_attr):
'\n helper function to crawl an attribute specified for retrieval\n '
if isinstance(this_data, list):
t_list = []
for d in this_data:
t_list.append(_crawl_attribute(d, this_attr))
return t_list
elif isinstance(this_attr, d... | -6,944,335,053,640,380,000 | helper function to crawl an attribute specified for retrieval | salt/pillar/vmware_pillar.py | _crawl_attribute | aaannz/salt-1 | python | def _crawl_attribute(this_data, this_attr):
'\n \n '
if isinstance(this_data, list):
t_list = []
for d in this_data:
t_list.append(_crawl_attribute(d, this_attr))
return t_list
elif isinstance(this_attr, dict):
t_dict = {}
for k in this_attr:
... |
def _serializer(obj):
'\n helper function to serialize some objects for prettier return\n '
import datetime
if isinstance(obj, datetime.datetime):
if (obj.utcoffset() is not None):
obj = (obj - obj.utcoffset())
return obj.__str__()
return obj | -3,098,185,855,057,940,000 | helper function to serialize some objects for prettier return | salt/pillar/vmware_pillar.py | _serializer | aaannz/salt-1 | python | def _serializer(obj):
'\n \n '
import datetime
if isinstance(obj, datetime.datetime):
if (obj.utcoffset() is not None):
obj = (obj - obj.utcoffset())
return obj.__str__()
return obj |
def sjoin(left_df, right_df, how='inner', op='intersects', lsuffix='left', rsuffix='right'):
"Spatial join of two GeoDataFrames.\n\n Parameters\n ----------\n left_df, right_df : GeoDataFrames\n how : string, default 'inner'\n The type of join:\n\n * 'left': use keys from left_df; retain o... | -7,132,081,164,258,639,000 | Spatial join of two GeoDataFrames.
Parameters
----------
left_df, right_df : GeoDataFrames
how : string, default 'inner'
The type of join:
* 'left': use keys from left_df; retain only left_df geometry column
* 'right': use keys from right_df; retain only right_df geometry column
* 'inner': use interse... | geopandas/tools/sjoin.py | sjoin | anathnathphy67/geopandas | python | def sjoin(left_df, right_df, how='inner', op='intersects', lsuffix='left', rsuffix='right'):
"Spatial join of two GeoDataFrames.\n\n Parameters\n ----------\n left_df, right_df : GeoDataFrames\n how : string, default 'inner'\n The type of join:\n\n * 'left': use keys from left_df; retain o... |
def test_minify(self):
'Tests _minify with an invalid filepath.'
with self.assertRaises(subprocess.CalledProcessError) as called_process:
build._minify(INVALID_INPUT_FILEPATH, INVALID_OUTPUT_FILEPATH)
self.assertEqual(called_process.exception.returncode, 1) | -1,228,251,134,857,554,400 | Tests _minify with an invalid filepath. | scripts/build_test.py | test_minify | muarachmann/oppia | python | def test_minify(self):
with self.assertRaises(subprocess.CalledProcessError) as called_process:
build._minify(INVALID_INPUT_FILEPATH, INVALID_OUTPUT_FILEPATH)
self.assertEqual(called_process.exception.returncode, 1) |
def test_minify_and_create_sourcemap(self):
'Tests _minify_and_create_sourcemap with an invalid filepath.'
with self.assertRaises(subprocess.CalledProcessError) as called_process:
build._minify_and_create_sourcemap(INVALID_INPUT_FILEPATH, INVALID_OUTPUT_FILEPATH)
self.assertEqual(called_process.exce... | -7,904,411,719,584,090,000 | Tests _minify_and_create_sourcemap with an invalid filepath. | scripts/build_test.py | test_minify_and_create_sourcemap | muarachmann/oppia | python | def test_minify_and_create_sourcemap(self):
with self.assertRaises(subprocess.CalledProcessError) as called_process:
build._minify_and_create_sourcemap(INVALID_INPUT_FILEPATH, INVALID_OUTPUT_FILEPATH)
self.assertEqual(called_process.exception.returncode, 1) |
def test_ensure_files_exist(self):
'Test _ensure_files_exist raises exception with a non-existent\n filepath.\n '
non_existent_filepaths = [INVALID_INPUT_FILEPATH]
with self.assertRaisesRegexp(OSError, ('File %s does not exist.' % non_existent_filepaths[0])):
build._ensure_files_exist(... | 1,052,954,398,160,072,000 | Test _ensure_files_exist raises exception with a non-existent
filepath. | scripts/build_test.py | test_ensure_files_exist | muarachmann/oppia | python | def test_ensure_files_exist(self):
'Test _ensure_files_exist raises exception with a non-existent\n filepath.\n '
non_existent_filepaths = [INVALID_INPUT_FILEPATH]
with self.assertRaisesRegexp(OSError, ('File %s does not exist.' % non_existent_filepaths[0])):
build._ensure_files_exist(... |
def test_join_files(self):
'Determine third_party.js contains the content of the first 10 JS\n files in /third_party/static.\n '
third_party_js_stream = StringIO.StringIO()
dependency_filepaths = build.get_dependencies_filepaths()
build._join_files(dependency_filepaths['js'], third_party_j... | 5,106,008,982,036,936,000 | Determine third_party.js contains the content of the first 10 JS
files in /third_party/static. | scripts/build_test.py | test_join_files | muarachmann/oppia | python | def test_join_files(self):
'Determine third_party.js contains the content of the first 10 JS\n files in /third_party/static.\n '
third_party_js_stream = StringIO.StringIO()
dependency_filepaths = build.get_dependencies_filepaths()
build._join_files(dependency_filepaths['js'], third_party_j... |
def test_generate_copy_tasks_for_fonts(self):
'Test _generate_copy_tasks_for_fonts ensures that the number of copy\n tasks matches the number of font files.\n '
copy_tasks = collections.deque()
dependency_filepaths = build.get_dependencies_filepaths()
test_target = os.path.join('target', '... | -4,733,900,273,529,137,000 | Test _generate_copy_tasks_for_fonts ensures that the number of copy
tasks matches the number of font files. | scripts/build_test.py | test_generate_copy_tasks_for_fonts | muarachmann/oppia | python | def test_generate_copy_tasks_for_fonts(self):
'Test _generate_copy_tasks_for_fonts ensures that the number of copy\n tasks matches the number of font files.\n '
copy_tasks = collections.deque()
dependency_filepaths = build.get_dependencies_filepaths()
test_target = os.path.join('target', '... |
def test_insert_hash(self):
'Test _insert_hash returns correct filenames with provided hashes.'
self.assertEqual(build._insert_hash('file.js', '123456'), 'file.123456.js')
self.assertEqual(build._insert_hash('path/to/file.js', '654321'), 'path/to/file.654321.js')
self.assertEqual(build._insert_hash('fil... | 713,936,822,209,947,500 | Test _insert_hash returns correct filenames with provided hashes. | scripts/build_test.py | test_insert_hash | muarachmann/oppia | python | def test_insert_hash(self):
self.assertEqual(build._insert_hash('file.js', '123456'), 'file.123456.js')
self.assertEqual(build._insert_hash('path/to/file.js', '654321'), 'path/to/file.654321.js')
self.assertEqual(build._insert_hash('file.min.js', 'abcdef'), 'file.min.abcdef.js')
self.assertEqual(bu... |
def test_get_file_count(self):
'Test get_file_count returns the correct number of files, excluding\n file with extensions in FILE_EXTENSIONS_TO_IGNORE and files that should\n not be built.\n '
all_inclusive_file_count = 0
for (_, _, files) in os.walk(MOCK_EXTENSIONS_DEV_DIR):
al... | -4,047,248,619,172,851,000 | Test get_file_count returns the correct number of files, excluding
file with extensions in FILE_EXTENSIONS_TO_IGNORE and files that should
not be built. | scripts/build_test.py | test_get_file_count | muarachmann/oppia | python | def test_get_file_count(self):
'Test get_file_count returns the correct number of files, excluding\n file with extensions in FILE_EXTENSIONS_TO_IGNORE and files that should\n not be built.\n '
all_inclusive_file_count = 0
for (_, _, files) in os.walk(MOCK_EXTENSIONS_DEV_DIR):
al... |
def test_compare_file_count(self):
'Test _compare_file_count raises exception when there is a\n mismatched file count between 2 dirs list.\n '
build.ensure_directory_exists(EMPTY_DIR)
source_dir_file_count = build.get_file_count(EMPTY_DIR)
assert (source_dir_file_count == 0)
target_dir... | 7,889,284,212,739,964,000 | Test _compare_file_count raises exception when there is a
mismatched file count between 2 dirs list. | scripts/build_test.py | test_compare_file_count | muarachmann/oppia | python | def test_compare_file_count(self):
'Test _compare_file_count raises exception when there is a\n mismatched file count between 2 dirs list.\n '
build.ensure_directory_exists(EMPTY_DIR)
source_dir_file_count = build.get_file_count(EMPTY_DIR)
assert (source_dir_file_count == 0)
target_dir... |
def test_verify_filepath_hash(self):
'Test _verify_filepath_hash raises exception:\n 1) When there is an empty hash dict.\n 2) When a filename is expected to contain hash but does not.\n 3) When there is a hash in filename that cannot be found in\n hash dict.\n ... | -1,598,340,757,166,783,200 | Test _verify_filepath_hash raises exception:
1) When there is an empty hash dict.
2) When a filename is expected to contain hash but does not.
3) When there is a hash in filename that cannot be found in
hash dict. | scripts/build_test.py | test_verify_filepath_hash | muarachmann/oppia | python | def test_verify_filepath_hash(self):
'Test _verify_filepath_hash raises exception:\n 1) When there is an empty hash dict.\n 2) When a filename is expected to contain hash but does not.\n 3) When there is a hash in filename that cannot be found in\n hash dict.\n ... |
def test_process_html(self):
'Test process_html removes whitespaces and adds hash to filepaths.'
BASE_HTML_SOURCE_PATH = os.path.join(MOCK_TEMPLATES_DEV_DIR, 'base.html')
BASE_JS_RELATIVE_PATH = os.path.join('pages', 'Base.js')
BASE_JS_SOURCE_PATH = os.path.join(MOCK_TEMPLATES_COMPILED_JS_DIR, BASE_JS_R... | -218,790,766,903,421,200 | Test process_html removes whitespaces and adds hash to filepaths. | scripts/build_test.py | test_process_html | muarachmann/oppia | python | def test_process_html(self):
BASE_HTML_SOURCE_PATH = os.path.join(MOCK_TEMPLATES_DEV_DIR, 'base.html')
BASE_JS_RELATIVE_PATH = os.path.join('pages', 'Base.js')
BASE_JS_SOURCE_PATH = os.path.join(MOCK_TEMPLATES_COMPILED_JS_DIR, BASE_JS_RELATIVE_PATH)
build._ensure_files_exist([BASE_HTML_SOURCE_PATH,... |
def test_should_file_be_built(self):
'Test should_file_be_built returns the correct boolean value for\n filepath that should be built.\n '
service_js_filepath = os.path.join('local_compiled_js', 'core', 'pages', 'AudioService.js')
generated_parser_js_filepath = os.path.join('core', 'expression... | 1,018,427,264,036,538,800 | Test should_file_be_built returns the correct boolean value for
filepath that should be built. | scripts/build_test.py | test_should_file_be_built | muarachmann/oppia | python | def test_should_file_be_built(self):
'Test should_file_be_built returns the correct boolean value for\n filepath that should be built.\n '
service_js_filepath = os.path.join('local_compiled_js', 'core', 'pages', 'AudioService.js')
generated_parser_js_filepath = os.path.join('core', 'expression... |
def test_hash_should_be_inserted(self):
'Test hash_should_be_inserted returns the correct boolean value\n for filepath that should be hashed.\n '
with self.swap(build, 'FILEPATHS_NOT_TO_RENAME', ('*.py', 'path/to/fonts/*', 'path/to/third_party.min.js.map', 'path/to/third_party.min.css.map')):
... | -5,054,451,901,803,749,000 | Test hash_should_be_inserted returns the correct boolean value
for filepath that should be hashed. | scripts/build_test.py | test_hash_should_be_inserted | muarachmann/oppia | python | def test_hash_should_be_inserted(self):
'Test hash_should_be_inserted returns the correct boolean value\n for filepath that should be hashed.\n '
with self.swap(build, 'FILEPATHS_NOT_TO_RENAME', ('*.py', 'path/to/fonts/*', 'path/to/third_party.min.js.map', 'path/to/third_party.min.css.map')):
... |
def test_generate_copy_tasks_to_copy_from_source_to_target(self):
'Test generate_copy_tasks_to_copy_from_source_to_target queues up\n the same number of copy tasks as the number of files in the directory.\n '
assets_hashes = build.get_file_hashes(MOCK_ASSETS_DEV_DIR)
total_file_count = build.g... | 8,098,721,213,208,466,000 | Test generate_copy_tasks_to_copy_from_source_to_target queues up
the same number of copy tasks as the number of files in the directory. | scripts/build_test.py | test_generate_copy_tasks_to_copy_from_source_to_target | muarachmann/oppia | python | def test_generate_copy_tasks_to_copy_from_source_to_target(self):
'Test generate_copy_tasks_to_copy_from_source_to_target queues up\n the same number of copy tasks as the number of files in the directory.\n '
assets_hashes = build.get_file_hashes(MOCK_ASSETS_DEV_DIR)
total_file_count = build.g... |
def test_is_file_hash_provided_to_frontend(self):
'Test is_file_hash_provided_to_frontend returns the correct boolean\n value for filepath that should be provided to frontend.\n '
with self.swap(build, 'FILEPATHS_PROVIDED_TO_FRONTEND', ('path/to/file.js', 'path/to/file.html', 'file.js')):
... | -9,103,280,922,856,293,000 | Test is_file_hash_provided_to_frontend returns the correct boolean
value for filepath that should be provided to frontend. | scripts/build_test.py | test_is_file_hash_provided_to_frontend | muarachmann/oppia | python | def test_is_file_hash_provided_to_frontend(self):
'Test is_file_hash_provided_to_frontend returns the correct boolean\n value for filepath that should be provided to frontend.\n '
with self.swap(build, 'FILEPATHS_PROVIDED_TO_FRONTEND', ('path/to/file.js', 'path/to/file.html', 'file.js')):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.