code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''Creates an Isoleucine residue'''
##R-group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG1_length=geo.CB_CG1_length
CA_CB_CG1_angle=geo.CA_CB_CG1_angle
N_CA_CB_CG1_diangle=geo.N_CA_CB_CG1_diangle
CB_CG2_length... | def makeIle(segID, N, CA, C, O, geo) | Creates an Isoleucine residue | 1.730926 | 1.728787 | 1.001237 |
'''Creates a Leucine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle= geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD1_length=geo.CG_CD1_le... | def makeLeu(segID, N, CA, C, O, geo) | Creates a Leucine residue | 1.71031 | 1.719467 | 0.994674 |
'''Creates a Threonine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_OG1_length=geo.CB_OG1_length
CA_CB_OG1_angle=geo.CA_CB_OG1_angle
N_CA_CB_OG1_diangle=geo.N_CA_CB_OG1_diangle
CB_CG2_leng... | def makeThr(segID, N, CA, C, O, geo) | Creates a Threonine residue | 2.015139 | 2.019803 | 0.997691 |
'''Creates a Lysine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD_length=geo.CG_CD_length
... | def makeLys(segID, N, CA, C, O, geo) | Creates a Lysine residue | 1.569009 | 1.576974 | 0.994949 |
'''Creates an Aspartic Acid residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_OD1_length=geo.CG_OD1_... | def makeAsp(segID, N, CA, C, O, geo) | Creates an Aspartic Acid residue | 1.688404 | 1.681675 | 1.004002 |
'''Creates an Asparagine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_OD1_length=geo.CG... | def makeAsn(segID,N, CA, C, O, geo) | Creates an Asparagine residue | 1.744195 | 1.732296 | 1.006869 |
'''Creates a Glutamic Acid residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle = geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD_length=geo.CG_... | def makeGlu(segID, N, CA, C, O, geo) | Creates a Glutamic Acid residue | 1.591407 | 1.588249 | 1.001988 |
'''Creates a Glutamine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD_length=geo.CG_CD_len... | def makeGln(segID, N, CA, C, O, geo) | Creates a Glutamine residue | 1.625772 | 1.622133 | 1.002243 |
'''Creates a Methionine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_SD_length=geo.CG_SD_le... | def makeMet(segID, N, CA, C, O, geo) | Creates a Methionine residue | 1.759484 | 1.75904 | 1.000253 |
'''Creates a Histidine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_ND1_length=geo.CG_ND1_l... | def makeHis(segID, N, CA, C, O, geo) | Creates a Histidine residue | 1.449853 | 1.449495 | 1.000247 |
'''Creates a Proline residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD_length=geo.CG_CD_l... | def makePro(segID, N, CA, C, O, geo) | Creates a Proline residue | 1.97203 | 1.984071 | 0.993931 |
'''Place a sequence of amino acids into a peptide in the extended
conformation. The argument AA_chain holds the sequence of amino
acids to be used.'''
geo = geometry(AA_chain[0])
struc=initialize_res(geo)
for i in range(1,len(AA_chain)):
AA = AA_chain[i]
geo = geometry(AA)
... | def make_extended_structure(AA_chain) | Place a sequence of amino acids into a peptide in the extended
conformation. The argument AA_chain holds the sequence of amino
acids to be used. | 6.143685 | 3.309873 | 1.856169 |
'''Adds a residue to chain A model 0 of the given structure, and
returns the new structure. The residue to be added can be specified
in two ways: either as a geometry object (in which case
the remaining arguments phi, psi_im1, and omega are ignored) or as a
single-letter amino-acid code. In the latt... | def add_residue(structure, residue, phi=-120, psi_im1=140, omega=-370) | Adds a residue to chain A model 0 of the given structure, and
returns the new structure. The residue to be added can be specified
in two ways: either as a geometry object (in which case
the remaining arguments phi, psi_im1, and omega are ignored) or as a
single-letter amino-acid code. In the latter case... | 5.218374 | 1.780646 | 2.930606 |
'''Place a sequence of amino acids into a peptide with specified
backbone dihedral angles. The argument AA_chain holds the
sequence of amino acids to be used. The arguments phi and psi_im1 hold
lists of backbone angles, one for each amino acid, *starting from
the second amino acid in the chain*. The... | def make_structure(AA_chain,phi,psi_im1,omega=[]) | Place a sequence of amino acids into a peptide with specified
backbone dihedral angles. The argument AA_chain holds the
sequence of amino acids to be used. The arguments phi and psi_im1 hold
lists of backbone angles, one for each amino acid, *starting from
the second amino acid in the chain*. The argume... | 3.268312 | 1.732743 | 1.886207 |
'''Creates a structure out of a list of geometry objects.'''
model_structure=initialize_res(geos[0])
for i in range(1,len(geos)):
model_structure=add_residue(model_structure, geos[i])
return model_structure | def make_structure_from_geos(geos) | Creates a structure out of a list of geometry objects. | 4.623374 | 4.386463 | 1.05401 |
'''Generates the geometry of the requested amino acid.
The amino acid needs to be specified by its single-letter
code. If an invalid code is specified, the function
returns the geometry of Glycine.'''
if(AA=='G'):
return GlyGeo()
elif(AA=='A'):
return AlaGeo()
elif(AA=='S'):
... | def geometry(AA) | Generates the geometry of the requested amino acid.
The amino acid needs to be specified by its single-letter
code. If an invalid code is specified, the function
returns the geometry of Glycine. | 1.790388 | 1.421435 | 1.259564 |
return svc.connectQ2Q(q2q.Q2QAddress("",""),
q2q.Q2QAddress(newAddress.domain, "accounts"),
'identity-admin',
protocol.ClientFactory.forProtocol(AMP)
).addCallback(
AMP.callRemote,
... | def enregister(svc, newAddress, password) | Register a new account and return a Deferred that fires if it worked.
@param svc: a Q2QService
@param newAddress: a Q2QAddress object
@param password: a shared secret (str) | 12.794044 | 11.649513 | 1.098247 |
key = endpoint, extraHash
D = Deferred()
if key in self.cachedConnections:
D.callback(self.cachedConnections[key])
elif key in self.inProgress:
self.inProgress[key].append(D)
else:
self.inProgress[key] = [D]
endpoint.connec... | def connectCached(self, endpoint, protocolFactory,
extraWork=lambda x: x,
extraHash=None) | See module docstring
@param endpoint:
@param protocolFactory:
@param extraWork:
@param extraHash:
@return: the D | 3.024727 | 3.485727 | 0.867746 |
if key in self.cachedConnections:
del self.cachedConnections[key]
if self._shuttingDown and self._shuttingDown.get(key):
d, self._shuttingDown[key] = self._shuttingDown[key], None
d.callback(None) | def connectionLostForKey(self, key) | Remove lost connection from cache.
@param key: key of connection that was lost
@type key: L{tuple} of L{IAddress} and C{extraHash} | 2.742362 | 2.984375 | 0.918906 |
self._shuttingDown = {key: Deferred()
for key in self.cachedConnections.keys()}
return DeferredList(
[maybeDeferred(p.transport.loseConnection)
for p in self.cachedConnections.values()]
+ self._shuttingDown.values()) | def shutdown(self) | Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred} | 6.178101 | 5.435936 | 1.136529 |
if isinstance(state, bool):
return state
if not isinstance(state, basestring):
raise TypeError('ACL state must be bool or string')
try:
return _state_strings[state.lower()]
except KeyError:
raise ValueError('unknown ACL state string') | def parse_state(state) | Convert a bool, or string, into a bool.
The string pairs we respond to (case insensitively) are:
- ALLOW & DENY
- GRANT & REJECT
:returns bool: ``True`` or ``False``.
:raises ValueError: when not a ``bool`` or one of the above strings.
E.g.::
>>> parse_state('Allow')
Tru... | 4.232768 | 5.068328 | 0.835141 |
if not path:
return None
for attr in path.split('.'):
obj = getattr(obj, attr, None)
return obj | def _getattr_path(obj, path) | getattr for a dot separated path
If an AttributeError is raised, it will return None. | 3.393049 | 3.695767 | 0.918091 |
def tween(request):
zipkin_settings = _get_settings_from_request(request)
tracer = get_default_tracer()
tween_kwargs = dict(
service_name=zipkin_settings.service_name,
span_name=zipkin_settings.span_name,
zipkin_attrs=zipkin_settings.zipkin_attrs,
... | def zipkin_tween(handler, registry) | Factory for pyramid tween to handle zipkin server logging. Note that even
if the request isn't sampled, Zipkin attributes are generated and pushed
into threadlocal storage, so `create_http_headers_for_new_span` and
`zipkin_span` will have access to the proper Zipkin state.
Consumes custom create_zipkin... | 2.416128 | 2.508083 | 0.963337 |
path_to_sha = {
folder: sha for folder, sha in self.get_shas()
}
modules = self.read_file('.gitmodules').split('[submodule "')
for i, module in enumerate(modules):
if not module:
continue
try:
name = module.spli... | def get_skill_data(self) | generates tuples of name, path, url, sha | 3.692094 | 3.243828 | 1.13819 |
last = self.lastTransmitted
self.ackPredicate = lambda ackPacket: (
ackPacket.relativeAck() >= last.relativeSeq()
) | def expectAck(self) | When the most recent packet produced as an output of this state machine
is acknowledged by our peer, generate a single 'ack' input. | 23.4718 | 19.41947 | 1.208674 |
ackPredicate = self.ackPredicate
self.ackPredicate = lambda packet: False
if ackPacket.syn:
# New SYN packets are always news.
self.synAck()
return
if ackPredicate(ackPacket):
self.ack() | def maybeReceiveAck(self, ackPacket) | Receive an L{ack} or L{synAck} input from the given packet. | 8.209387 | 7.323343 | 1.120989 |
CleanCommand.user_options = _CleanCommand.user_options[:]
CleanCommand.user_options.extend([
('dist', 'd', 'remove distribution directory'),
('eggs', None, 'remove egg and egg-info directories'),
('environment', 'E', 'remove virtual environment directory'),
('pycache', 'p', ... | def _set_options() | Set the options for CleanCommand.
There are a number of reasons that this has to be done in an
external function instead of inline in the class. First of all,
the setuptools machinery really wants the options to be defined
in a class attribute - otherwise, the help command doesn't work
so we need ... | 3.695899 | 3.653799 | 1.011522 |
check_universe(universe)
# check, if the universe already exists in the list:
if universe in self._outputs:
return
# add new sending:
new_output = Output(DataPacket(cid=self.__CID, sourceName=self.source_name, universe=universe))
self._outputs[univers... | def activate_output(self, universe: int) -> None | Activates a universe that's then starting to sending every second.
See http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf for more information
:param universe: the universe to activate | 8.523892 | 8.309023 | 1.02586 |
check_universe(universe)
try: # try to send out three messages with stream_termination bit set to 1
self._outputs[universe]._packet.option_StreamTerminated = True
for i in range(0, 3):
self._output_thread.send_out(self._outputs[universe])
except:... | def deactivate_output(self, universe: int) -> None | Deactivates an existing sending. Every data from the existing sending output will be lost.
(TTL, Multicast, DMX data, ..)
:param universe: the universe to deactivate. If the universe was not activated before, no error is raised | 8.287688 | 8.041181 | 1.030656 |
check_universe(universe_from)
check_universe(universe_to)
# store the sending object and change the universe in the packet of the sending
tmp_output = self._outputs[universe_from]
tmp_output._packet.universe = universe_to
# deactivate sending
self.deactiv... | def move_universe(self, universe_from: int, universe_to: int) -> None | Moves an sending from one universe to another. All settings are being restored and only the universe changes
:param universe_from: the universe that should be moved
:param universe_to: the target universe. An existing universe will be overwritten | 5.555367 | 5.109901 | 1.087177 |
if bind_address is None:
bind_address = self.bindAddress
if fps is None:
fps = self._fps
if bind_port is None:
bind_port = self.bind_port
self.stop()
self._output_thread = OutputThread(cid=self.__CID, source_name=self.source_name,
... | def start(self, bind_address=None, bind_port: int = None, fps: int = None) -> None | Starts or restarts a new Thread with the parameters given in the constructor or
the parameters given in this function.
The parameters in this function do not override the class specific values!
:param bind_address: the IP-Address to bind to
:param bind_port: the port to bind to
:... | 3.407127 | 3.408901 | 0.99948 |
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
try:
return file(filename, 'rb+')
except IOError:
return file(filename, 'wb+') | def openReadWrite(filename) | Return a 2-tuple of: (whether the file existed before, open file object) | 2.407949 | 2.665065 | 0.903524 |
dirname, basename = os.path.split(filename)
newbasename = '_%s_.sbm' % (basename,)
maskfname = os.path.join(dirname, newbasename)
maskfile = openReadWrite(maskfname)
return maskfile | def openMaskFile(filename) | Open the bitmask file sitting next to a file in the filesystem. | 4.886822 | 4.827565 | 1.012275 |
self.callRemote(Data, name=name, chunk=chunk, body=body) | def data(self, name, chunk, body) | Issue a DATA command
return None
Sends a chunk of data to a peer. | 5.248819 | 5.949371 | 0.882248 |
mypeer = self.transport.getQ2QPeer()
tl = self.nexus.transloads[name]
peerz = tl.peers
if mypeer in peerz:
peerk = peerz[mypeer]
else:
# all turned on initially; we aren't going to send them anything.
peerk = PeerKnowledge(bits.BitArra... | def get(self, name, mask=None) | Issue a GET command
Return a Deferred which fires with the size of the name being requested | 10.531528 | 9.580078 | 1.099316 |
self.nexus.conns.connectionLostForKey((endpoint.Q2QEndpoint(
self.nexus.svc,
self.nexus.addr,
self.transport.getQ2QPeer(),
PROTOCOL_NAME), None))
AMP.connectionLost(self, reason) | def connectionLost(self, reason) | Inform the associated L{conncache.ConnectionCache} that this
protocol has been disconnected. | 22.047642 | 19.893427 | 1.108288 |
# print 'sending some data', howMany
if self.transport is None:
return
peer = self.transport.getQ2QPeer()
while howMany > 0:
# sort transloads so that the least-frequently-serviced ones will
# come first
tloads = [
... | def sendSomeData(self, howMany) | Send some DATA commands to my peer(s) to relay some data.
@param howMany: an int, the number of chunks to send out. | 5.428951 | 5.329742 | 1.018614 |
for peer in otherPeers:
if peer not in self.otherPeers:
self.otherPeers.append(peer)
return peer | def selectPeerToIntroduce(self, otherPeers) | Choose a peer to introduce. Return a q2q address or None, if there are
no suitable peers to introduce at this time. | 3.068342 | 2.785751 | 1.101442 |
def verifyError(error):
error.trap(VerifyError)
self.nexus.decreaseScore(who, self.authorities)
return self.nexus.verifyChunk(self.name,
who,
chunkNumber,
sh... | def chunkReceived(self, who, chunkNumber, chunkData) | A chunk was received from the peer. | 7.08025 | 7.114452 | 0.995193 |
if self.mask[chunkNumber]:
# already received that chunk.
return
self.file.seek(chunkNumber * CHUNK_SIZE)
self.file.write(chunkData)
self.file.flush()
self.sha1sums[chunkNumber] = sha.new(chunkData).digest()
if not self.mask[chunkNumber]:... | def chunkVerified(self, who, chunkNumber, chunkData) | A chunk (#chunkNumber) containing the data C{chunkData} was verified, sent
to us by the Q2QAddress C{who}. | 5.428424 | 5.411554 | 1.003117 |
# stuff I have
have = sets.Set(self.mask.positions(1))
# stuff that this peer wants
want = sets.Set(self.peers[peer].mask.positions(0))
exchangeable = have.intersection(want)
finalSet = dict.fromkeys(exchangeable, 0)
# taking a page from bittorrent, rar... | def selectOptimalChunk(self, peer) | select an optimal chunk to send to a peer.
@return: int(chunkNumber), str(chunkData) if there is data to be sent,
otherwise None, None | 4.954545 | 4.823083 | 1.027257 |
peerDir = self.basepath.child(str(peer))
if not peerDir.isdir():
peerDir.makedirs()
return (peerDir.child(sharename+'.incomplete'),
peerDir.child(sharename)) | def allocateFile(self, sharename, peer) | return a 2-tuple of incompletePath, fullPath | 4.597405 | 3.562956 | 1.290335 |
for tl in self.transloads.itervalues():
if peer in tl.peers:
yield tl | def transloadsForPeer(self, peer) | Returns an iterator of transloads that apply to a particular peer. | 4.960435 | 3.979942 | 1.246359 |
t = self.transloads[name] = Transload(self.addr, self, name,
None, path,
self.ui.startTransload(name,
self.addr),
... | def seed(self, path, name) | Create a transload from an existing file that is complete. | 11.572677 | 8.344179 | 1.386916 |
return self.conns.connectCached(endpoint.Q2QEndpoint(self.svc,
self.addr,
peer,
PROTOCOL_NAME),
... | def connectPeer(self, peer) | Establish a SIGMA connection to the given peer.
@param peer: a Q2QAddress of a peer which has a file that I want
@return: a Deferred which fires a SigmaProtocol. | 23.117727 | 20.754919 | 1.113843 |
if participant not in self.scores:
self.scores[participant] = 0
self.scores[participant] += 1 | def increaseScore(self, participant) | The participant successfully transferred a chunk to me. | 2.358852 | 2.424488 | 0.972928 |
def decorator(f):
self.register_listener(trigger, f, **kwargs)
return f
return decorator | def listen_on(self, trigger: str, **kwargs) -> callable | This is a simple decorator for registering a callback for an event. You can also use 'register_listener'.
A list with all possible options is available via LISTEN_ON_OPTIONS.
:param trigger: Currently supported options: 'universe availability change', 'universe' | 4.4315 | 4.859058 | 0.912008 |
if trigger in LISTEN_ON_OPTIONS:
if trigger == LISTEN_ON_OPTIONS[1]: # if the trigger is universe, use the universe from args as key
try:
self._callbacks[kwargs[LISTEN_ON_OPTIONS[1]]].append(func)
except:
self._callbac... | def register_listener(self, trigger: str, func: callable, **kwargs) -> None | Register a listener for the given trigger. Raises an TypeError when the trigger is not a valid one.
To get a list with all valid triggers, use LISTEN_ON_OPTIONS.
:param trigger: the trigger on which the given callback should be used.
Currently supported: 'universe availability change', 'univers... | 3.615667 | 2.750195 | 1.314695 |
self.sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(calculate_multicast_addr(universe)) +
socket.inet_aton(self._bindAddress)) | def join_multicast(self, universe: int) -> None | Joins the multicast address that is used for the given universe. Note: If you are on Windows you must have given
a bind IP-Address for this feature to function properly. On the other hand you are not allowed to set a bind
address if you are on any other OS.
:param universe: the universe to join ... | 4.039245 | 3.43795 | 1.174899 |
try:
self.sock.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP,
socket.inet_aton(calculate_multicast_addr(universe)) +
socket.inet_aton(self._bindAddress))
except: # try to leave the multicast group for the unive... | def leave_multicast(self, universe: int) -> None | Try to leave the multicast group with the specified universe. This does not throw any exception if the group
could not be leaved.
:param universe: the universe to leave the multicast group.
The network hardware has to support the multicast feature! | 4.549493 | 3.970619 | 1.145789 |
self.stop() # stop an existing thread
self._thread = receiverThread(socket=self.sock, callbacks=self._callbacks)
self._thread.start() | def start(self) -> None | Starts a new thread that handles the input. If a thread is already running, the thread will be restarted. | 8.897407 | 6.173487 | 1.441229 |
if func is None:
return functools.partial(self.predicate, name)
self.predicates[name] = func
return func | def predicate(self, name, func=None) | Define a new predicate (directly, or as a decorator).
E.g.::
@authz.predicate('ROOT')
def is_root(user, **ctx):
# return True of user is in group "wheel". | 2.595342 | 3.479007 | 0.746001 |
if func is None:
return functools.partial(self.predicate, name)
self.permission_sets[name] = func
return func | def permission_set(self, name, func=None) | Define a new permission set (directly, or as a decorator).
E.g.::
@authz.permission_set('HTTP')
def is_http_perm(perm):
return perm.startswith('http.') | 4.329427 | 5.407217 | 0.800676 |
def _route_acl(func):
func.__acl__ = acl
@functools.wraps(func)
def wrapped(*args, **kwargs):
permission = 'http.' + request.method.lower()
local_opts = options.copy()
local_opts.setdefault('default', current_app.con... | def route_acl(self, *acl, **options) | Decorator to attach an ACL to a route.
E.g::
@app.route('/url/to/view')
@authz.route_acl('''
ALLOW WHEEL ALL
DENY ANY ALL
''')
def my_admin_function():
pass | 4.043953 | 4.146398 | 0.975293 |
context = {'user': current_user}
for func in self.context_processors:
context.update(func())
context.update(get_object_context(obj))
context.update(kwargs)
return check(permission, iter_object_acl(obj), **context) | def can(self, permission, obj, **kwargs) | Check if we can do something with an object.
:param permission: The permission to look for.
:param obj: The object to check the ACL of.
:param **kwargs: The context to pass to predicates.
>>> auth.can('read', some_object)
>>> auth.can('write', another_object, group=some_group) | 5.604306 | 5.953152 | 0.941401 |
flash_message = kwargs.pop('flash', None)
stealth = kwargs.pop('stealth', False)
default = kwargs.pop('default', None)
res = self.can(permission, obj, **kwargs)
res = default if res is None else res
if not res:
if flash_message and not stealth:
... | def assert_can(self, permission, obj, **kwargs) | Make sure we have a permission, or abort the request.
:param permission: The permission to look for.
:param obj: The object to check the ACL of.
:param flash: The message to flask if denied (keyword only).
:param stealth: Abort with a 404? (keyword only).
:param **kwargs: The co... | 2.935764 | 2.820765 | 1.040769 |
view = flask.current_app.view_functions.get(endpoint)
if not view:
endpoint, args = flask._request_ctx.top.match(endpoint)
view = flask.current_app.view_functions.get(endpoint)
if not view:
return False
return self.can('http.' + (method or '... | def can_route(self, endpoint, method=None, **kwargs) | Make sure we can route to the given endpoint or url.
This checks for `http.get` permission (or other methods) on the ACL of
route functions, attached via the `ACL` decorator.
:param endpoint: A URL or endpoint to check for permission to access.
:param method: The HTTP method to check; ... | 4.000404 | 3.838317 | 1.042229 |
# XXX This is overriding a private interface
super(ConnectionStartBox, self)._sendTo(proto)
self.virtualTransport.startProtocol() | def _sendTo(self, proto) | When sent, call the C{startProtocol} method on the virtual transport
object.
@see: L{vertex.ptcp.PTCP.startProtocol}
@see: L{vertex.q2q.VirtualTransport.startProtocol}
@param proto: the AMP protocol that this is being sent on. | 28.779902 | 18.291239 | 1.573425 |
tpt = objects.pop('__transport__')
# XXX Using a private API
return _objectsToStrings(
objects, cls.response,
ConnectionStartBox(tpt),
proto) | def makeResponse(cls, objects, proto) | Create a response dictionary using this L{Virtual} command's schema; do
the same thing as L{Command.makeResponse}, but additionally do
addition.
@param objects: The dictionary of strings mapped to Python objects.
@param proto: The AMP protocol that this command is serialized to.
... | 39.455521 | 28.010399 | 1.408603 |
if 'X-B3-TraceId' in request.headers:
trace_id = _convert_signed_hex(request.headers['X-B3-TraceId'])
# Tolerates 128 bit X-B3-TraceId by reading the right-most 16 hex
# characters (as opposed to overflowing a U64 and starting a new trace).
trace_id = trace_id[-16:]
elif 'zi... | def get_trace_id(request) | Gets the trace id based on a request. If not present with the request,
create a custom (depending on config: `zipkin.trace_id_generator`) or a
completely random trace id.
:param: current active pyramid request
:returns: a 64-bit hex string | 3.812601 | 3.399398 | 1.121552 |
if s.startswith('0x') or s.startswith('-0x'):
s = '{0:x}'.format(struct.unpack('Q', struct.pack('q', int(s, 16)))[0])
return s.zfill(16) | def _convert_signed_hex(s) | Takes a signed hex string that begins with '0x' and converts it to
a 16-character string representing an unsigned hex value.
Examples:
'0xd68adf75f4cfd13' => 'd68adf75f4cfd13'
'-0x3ab5151d76fb85e1' => 'c54aeae289047a1f' | 2.795601 | 2.795436 | 1.000059 |
blacklisted_paths = request.registry.settings.get(
'zipkin.blacklisted_paths', [])
# Only compile strings, since even recompiling existing
# compiled regexes takes time.
regexes = [
re.compile(r) if isinstance(r, six.string_types) else r
for r in blacklisted_paths
]
... | def should_not_sample_path(request) | Decided whether current request path should be sampled or not. This is
checked previous to `should_not_sample_route` and takes precedence.
:param: current active pyramid request
:returns: boolean whether current request path is blacklisted. | 5.099152 | 5.15144 | 0.98985 |
blacklisted_routes = request.registry.settings.get(
'zipkin.blacklisted_routes', [])
if not blacklisted_routes:
return False
route_mapper = request.registry.queryUtility(IRoutesMapper)
route_info = route_mapper(request).get('route')
return (route_info and route_info.name in bla... | def should_not_sample_route(request) | Decided whether current request route should be sampled or not.
:param: current active pyramid request
:returns: boolean whether current request route is blacklisted. | 3.757713 | 3.6702 | 1.023844 |
if should_not_sample_path(request):
return False
elif should_not_sample_route(request):
return False
elif 'X-B3-Sampled' in request.headers:
return request.headers.get('X-B3-Sampled') == '1'
else:
zipkin_tracing_percent = request.registry.settings.get(
'z... | def is_tracing(request) | Determine if zipkin should be tracing
1) Check whether the current request path is blacklisted.
2) If not, check whether the current request route is blacklisted.
3) If not, check if specific sampled header is present in the request.
4) If not, Use a tracing percent (default: 0.5%) to decide.
:para... | 3.538988 | 2.67756 | 1.321721 |
settings = request.registry.settings
if 'zipkin.is_tracing' in settings:
is_sampled = settings['zipkin.is_tracing'](request)
else:
is_sampled = is_tracing(request)
request.zipkin_trace_id = get_trace_id(request)
span_id = request.headers.get(
'X-B3-SpanId', generate_r... | def create_zipkin_attr(request) | Create ZipkinAttrs object from a request with sampled flag as True.
Attaches lazy attribute `zipkin_trace_id` with request which is then used
throughout the tween.
Consumes custom is_tracing function to determine if the request is traced
if one is set in the pyramid registry.
:param request: pyram... | 2.112087 | 2.007046 | 1.052336 |
route = request.matched_route.pattern if request.matched_route else ''
annotations = {
'http.uri': request.path,
'http.uri.qs': request.path_qs,
'http.route': route,
'response_status_code': str(response.status_code),
}
settings = request.registry.settings
if 'zi... | def get_binary_annotations(request, response) | Helper method for getting all binary annotations from the request.
:param request: the Pyramid request object
:param response: the Pyramid response object
:returns: binary annotation dict of {str: str} | 3.786742 | 4.162014 | 0.909834 |
newData = [0]*512
for i in range(0, min(len(data), 512)):
newData[i] = data[i]
self._dmxData = tuple(newData)
# in theory this class supports dynamic length, so the next line is correcting the length
self.length = 126 + len(self._dmxData) | def dmxData(self, data: tuple) | For legacy devices and to prevent errors, the length of the DMX data is normalized to 512 | 6.527605 | 5.72251 | 1.140689 |
# Check if the length is sufficient
if len(raw_data) < 126:
raise TypeError('The length of the provided data is not long enough! Min length is 126!')
# Check if the three Vectors are correct
if tuple(raw_data[18:22]) != tuple(VECTOR_ROOT_E131_DATA) or \
tu... | def make_data_packet(raw_data) -> 'DataPacket' | Converts raw byte data to a sACN DataPacket. Note that the raw bytes have to come from a 2016 sACN Message.
This does not support Sync Addresses, Force_Sync option and DMX Start code!
:param raw_data: raw bytes as tuple or list
:return: a DataPacket with the properties set like the raw bytes | 5.679257 | 5.38762 | 1.054131 |
'''Returns the Root layer as list with bytes'''
tmpList = []
tmpList.extend(_FIRST_INDEX)
# first append the high byte from the Flags and Length
# high 4 bit: 0x7 then the bits 8-11(indexes) from _length
length = self.length - 16
tmpList.append((0x7 << 4) + (lengt... | def getBytes(self) -> list | Returns the Root layer as list with bytes | 9.983075 | 8.093081 | 1.233532 |
local_skills = [s for s in self.list() if s.is_local]
default_skills = [s.name for s in self.list_defaults()]
local_skill_names = [s.name for s in local_skills]
skills_data_skills = [s['name'] for s in skills_data['skills']]
# Check for skills that aren't in the list
... | def curate_skills_data(self, skills_data) | Sync skills_data with actual skills on disk. | 2.988256 | 2.851623 | 1.047914 |
self.skills_data = self.load_skills_data()
if 'upgraded' in self.skills_data:
self.skills_data.pop('upgraded')
else:
self.skills_data_hash = skills_data_hash(self.skills_data) | def sync_skills_data(self) | Update internal skill_data_structure from disk. | 3.685581 | 3.177744 | 1.159811 |
data = data or self.skills_data
if skills_data_hash(data) != self.skills_data_hash:
write_skills_data(data)
self.skills_data_hash = skills_data_hash(data) | def write_skills_data(self, data=None) | Write skills data hash if it has been modified. | 2.578726 | 2.004693 | 1.286345 |
if isinstance(param, SkillEntry):
skill = param
else:
skill = self.find_skill(param, author)
entry = build_skill_entry(skill.name, origin, skill.is_beta)
try:
skill.install(constraints)
entry['installed'] = time.time()
... | def install(self, param, author=None, constraints=None, origin='') | Install by url or name | 4.203209 | 4.162776 | 1.009713 |
if isinstance(param, SkillEntry):
skill = param
else:
skill = self.find_skill(param, author)
skill.remove()
skills = [s for s in self.skills_data['skills']
if s['name'] != skill.name]
self.skills_data['skills'] = skills
r... | def remove(self, param, author=None) | Remove by url or name | 3.515218 | 3.373796 | 1.041918 |
if skill is None:
return self.update_all()
else:
if isinstance(skill, str):
skill = self.find_skill(skill, author)
entry = get_skill_entry(skill.name, self.skills_data)
if entry:
entry['beta'] = skill.is_beta
... | def update(self, skill=None, author=None) | Update all downloaded skills or one specified skill. | 5.218431 | 4.570106 | 1.141862 |
def run_item(skill):
try:
func(skill)
return True
except MsmException as e:
LOG.error('Error running {} on {}: {}'.format(
func.__name__, skill.name, repr(e)
))
return False
... | def apply(self, func, skills) | Run a function on all skills in parallel | 3.493138 | 3.288817 | 1.062126 |
def install_or_update_skill(skill):
if skill.is_local:
self.update(skill)
else:
self.install(skill, origin='default')
return self.apply(install_or_update_skill, self.list_defaults()) | def install_defaults(self) | Installs the default skills, updates all others | 7.017254 | 5.725766 | 1.225557 |
section_skills = []
for skill_name in skill_names:
if skill_name in name_to_skill:
section_skills.append(name_to_skill[skill_name])
else:
LOG.warning('No such default skill: ' + skill_name)
defaults[section_n... | def list_all_defaults(self): # type: () -> Dict[str, List[SkillEntry]]
skills = self.list()
name_to_skill = {skill.name: skill for skill in skills}
defaults = {group: [] for group in self.SKILL_GROUPS}
for section_name, skill_names in self.repo.get_default_skill_names() | Returns {'skill_group': [SkillEntry('name')]} | 2.4856 | 2.304908 | 1.078395 |
try:
self.repo.update()
except GitException as e:
if not isdir(self.repo.path):
raise
LOG.warning('Failed to update repo: {}'.format(repr(e)))
remote_skill_list = (
SkillEntry(
name, SkillEntry.create_path(s... | def list(self) | Load a list of SkillEntry objects from both local and
remote skills
It is necessary to load both local and remote skills at
the same time to correctly associate local skills with the name
in the repo and remote skills with any custom path that they
have been downloaded to | 4.288575 | 3.857968 | 1.111615 |
# type: (str, str, List[SkillEntry]) -> SkillEntry
if param.startswith('https://') or param.startswith('http://'):
repo_id = SkillEntry.extract_repo_id(param)
for skill in self.list():
if skill.id == repo_id:
return skill
n... | def find_skill(self, param, author=None, skills=None) | Find skill by name or url | 3.321385 | 3.263762 | 1.017656 |
offt = 0
while offt < len(data):
yield data[offt:offt+chunksize]
offt += chunksize | def iterchunks(data, chunksize) | iterate chunks of data | 2.916753 | 2.884743 | 1.011096 |
if SEG_LEN == 0 and RCV_WND == 0:
return SEG_SEQ == RCV_NXT
if SEG_LEN == 0 and RCV_WND > 0:
return ((RCV_NXT <= SEG_SEQ) and (SEG_SEQ < RCV_NXT + RCV_WND))
if SEG_LEN > 0 and RCV_WND == 0:
return False
if SEG_LEN > 0 and RCV_WND > 0:
return (( (RCV_NXT <= SEG_SEQ) ... | def segmentAcceptable(RCV_NXT, RCV_WND, SEG_SEQ, SEG_LEN) | An acceptable segment: RFC 793 page 26. | 1.879825 | 1.848918 | 1.016716 |
if self.syn or self.fin or self.dlen:
return True
return False | def mustRetransmit(self) | Check to see if this packet must be retransmitted until it was
received.
Packets which contain a connection-state changing flag (SYN or FIN) or
a non-zero amount of data can be retransmitted. | 12.978312 | 7.620964 | 1.702975 |
if self._ackTimer is None:
def originateAck():
self._ackTimer = None
self.originate(ack=True)
self._ackTimer = reactor.callLater(0.1, originateAck)
else:
self._ackTimer.reset(ACK_DELAY) | def ackSoon(self) | Emit an acknowledgement packet soon. | 4.575168 | 4.316034 | 1.06004 |
if self._ackTimer is not None:
self._ackTimer.cancel()
self._ackTimer = None
if syn:
# We really should be randomizing the ISN but until we finish the
# implementations of the various bits of wraparound logic that were
# started with r... | def originate(self, data='', syn=False, ack=False, fin=False, rst=False) | Create a packet, enqueue it to be sent, and return it. | 7.186916 | 7.057794 | 1.018295 |
assert not self.disconnecting
assert not self.disconnected
try:
p = self.factory.buildProtocol(PTCPAddress(
self.peerAddressTuple, self.pseudoPortPair))
p.makeConnection(self)
except:
log.msg("Exception during PTCP connecti... | def connectionJustEstablished(self) | We sent out SYN, they acknowledged it. Congratulations, you
have a new baby connection. | 6.438514 | 6.442761 | 0.999341 |
sourcePseudoPort = genConnID() % MAX_PSEUDO_PORT
conn = self._connections[(pseudoPort, sourcePseudoPort, (host, port))
] = PTCPConnection(
sourcePseudoPort, pseudoPort, self, factory, (host, port))
conn.machine.appActiveOpen()
return ... | def connect(self, factory, host, port, pseudoPort=1) | Attempt to establish a new connection via PTCP to the given
remote address.
@param factory: A L{ClientFactory} which will be used to
create an L{IProtocol} provider if the connection is
successfully set up, or which will have failure callbacks
invoked on it otherwise... | 11.903642 | 12.202069 | 0.975543 |
for conn in self._connections.values():
conn.releaseConnectionResources()
assert not self._connections | def _finalCleanup(self) | Clean up all of our connections by issuing application-level close and
stop notifications, sending hail-mary final FIN packets (which may not
reach the other end, but nevertheless can be useful) when possible. | 12.461769 | 9.402973 | 1.325301 |
if not self._connections:
return self._stop()
return self._allConnectionsClosed.deferred().addBoth(self._stop) | def waitForAllConnectionsToClose(self) | Wait for all currently-open connections to enter the 'CLOSED' state.
Currently this is only usable from test fixtures. | 10.588915 | 9.284256 | 1.140524 |
def decorator(argClass):
class LoadableArgument(String):
def toString(self, arg):
assert isinstance(arg, loaderClass), \
("%r not %r" % (arg, loaderClass))
return String.toString(self, arg.dump())
def fromString(self, arg):
... | def _argumentForLoader(loaderClass) | Create an AMP argument for (de-)serializing instances of C{loaderClass}.
@param loaderClass: A type object with a L{load} class method that takes
some bytes and returns an instance of itself, and a L{dump} instance
method that returns some bytes.
@return: a class decorator which decorates an A... | 3.397959 | 3.042273 | 1.116914 |
host, sPort = inStr.split(":")
return (host, int(sPort)) | def fromString(self, inStr) | Convert the given bytes into a C{(host, port)} tuple.
@param inStr: bytes in the format C{host:port}
@type inStr: L{bytes}
@return: a C{(host, port)} tuple
@rtype: 2-L{tuple} of L{bytes}, L{int} | 6.518195 | 8.571884 | 0.760416 |
store = DirectoryCertificateAndUserStore(path)
# store.addPrivateCertificate("kazekage")
# store.addUser("kazekage", "username", "password1234")
self.attach(q2q.Q2QService(
protocolFactoryFactory=IdentityAdminFactory(store).examineRequest,
certif... | def setup_Q2Q(self, path,
q2qPortnum=q2q.port,
inboundTCPPortnum=q2q.port+1,
publicIP=None
) | Set up a Q2Q service. | 8.905048 | 8.779254 | 1.014329 |
if spec:
assert isinstance(spec, Spec)
def _is_conditional(macro: str) -> bool:
return macro.startswith("?") or macro.startswith("!")
def _test_conditional(macro: str) -> bool:
if macro[0] == "?":
return True
if macro[0] == "!":
return False
... | def replace_macros(string, spec=None) | Replace all macros in given string with corresponding values.
For example: a string '%{name}-%{version}.tar.gz' will be transformed to 'foo-2.0.tar.gz'.
:param string A string containing macros that you want to be replaced
:param spec An optional spec file. If given, definitions in that spec
file will... | 2.618972 | 2.751627 | 0.951791 |
assert spec_obj
assert context
assert match_obj
assert line
return self.update_impl(spec_obj, context, match_obj, line) | def update(self, spec_obj, context, match_obj, line) | Update given spec object and parse context and return them again.
:param spec_obj: An instance of Spec class
:param context: The parse context
:param match_obj: The re.match object
:param line: The original line
:return: Given updated Spec instance and parse context dictionary. | 2.960134 | 3.321176 | 0.891291 |
assert self.packages
return dict(zip([package.name for package in self.packages], self.packages)) | def packages_dict(self) | All packages in this RPM spec as a dictionary.
You can access the individual packages by their package name, e.g.,
git_spec.packages_dict['git-doc'] | 5.651726 | 7.089264 | 0.797223 |
spec = Spec()
with open(filename, "r", encoding="utf-8") as f:
parse_context = {"current_subpackage": None}
for line in f:
spec, parse_context = _parse(spec, parse_context, line)
return spec | def from_file(filename) | Creates a new Spec object from a given file.
:param filename: The path to the spec file.
:return: A new Spec object. | 5.555363 | 4.986824 | 1.114008 |
spec = Spec()
parse_context = {"current_subpackage": None}
for line in string.splitlines():
spec, parse_context = _parse(spec, parse_context, line)
return spec | def from_string(string: str) | Creates a new Spec object from a given string.
:param string: The contents of a spec file.
:return: A new Spec object. | 9.371012 | 6.661042 | 1.406839 |
if isinstance(acl_iter, basestring):
acl_iter = [acl_iter]
for chunk in acl_iter:
if isinstance(chunk, basestring):
chunk = chunk.splitlines()
chunk = [re.sub(r'#.+', '', line).strip() for line in chunk]
chunk = filter(None, chunk)
else:
... | def parse_acl(acl_iter) | Parse a string, or list of ACE definitions, into usable ACEs. | 2.981074 | 2.886374 | 1.032809 |
for obj in iter_object_graph(root):
for ace in parse_acl(getattr(obj, '__acl__', ())):
yield ace | def iter_object_acl(root) | Child-first discovery of ACEs for an object.
Walks the ACL graph via ``__acl_bases__`` and yields the ACEs parsed from
``__acl__`` on each object. | 6.489376 | 3.986862 | 1.62769 |
context = {}
for obj in iter_object_graph(root, parents_first=True):
context.update(getattr(obj, '__acl_context__', {}))
return context | def get_object_context(root) | Depth-first discovery of authentication context for an object.
Walks the ACL graph via ``__acl_bases__`` and merges the ``__acl_context__``
attributes. | 5.998042 | 3.956355 | 1.516053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.