code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\ 'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\ 'P':115,'S':105,'T':119,'W':204,'Y':181,'V':117} aas = sorted(AA_TO_INDEX.keys()) mws = [d[aa] for aa in aas] if reverse: mws = [-1 * x for x in mw...
def MWColorMapping(maptype='jet', reverse=True)
Maps amino-acid molecular weights to colors. Otherwise, this function is identical to *KyteDoolittleColorMapping*
3.068216
2.830281
1.084068
pos_color = '#FF0000' neg_color = '#0000FF' neut_color = '#000000' mapping_d = {'A':neut_color,'R':pos_color,'N':neut_color,\ 'D':neg_color,'C':neut_color,'Q':neut_color,\ 'E':neg_color,'G':neut_color,'H':pos_color,\ 'I':neut_color,'L':neut_color...
def ChargeColorMapping(maptype='jet', reverse=False)
Maps amino-acid charge at neutral pH to colors. Currently does not use the keyword arguments for *maptype* or *reverse* but accepts these arguments to be consistent with KyteDoolittleColorMapping and MWColorMapping for now.
1.91681
1.854874
1.033391
small_color = '#f76ab4' nucleophilic_color = '#ff7f00' hydrophobic_color = '#12ab0d' aromatic_color = '#84380b' acidic_color = '#e41a1c' amide_color = '#972aa8' basic_color = '#3c58e5' mapping_d = {'G':small_color, 'A':small_color, 'S':nucleophilic_color, 'T':nucl...
def FunctionalGroupColorMapping(maptype='jet', reverse=False)
Maps amino-acid functional groups to colors. Currently does not use the keyword arguments for *maptype* or *reverse* but accepts these arguments to be consistent with the other mapping functions, which all get called with these arguments.
2.674427
2.614085
1.023083
eps = _my_eps_formatter(data, format, ordered_alphabets).decode() gs = weblogolib.GhostscriptAPI() return gs.convert('pdf', eps, format.logo_width, format.logo_height)
def _my_pdf_formatter(data, format, ordered_alphabets)
Generate a logo in PDF format. Modified from weblogo version 3.4 source code.
11.218677
7.248447
1.547735
items = [] start=True for line in fin : if line.isspace() or line[0] =='#' : continue stuff = line.split() if start and stuff[0] != 'PO' and stuff[0] != 'P0': continue if stuff[0]=='XX' or stuff[0]=='//': break start = Fal...
def read_transfac( fin, alphabet = None)
Parse a sequence matrix from a file. Returns a tuple of (alphabet, matrix)
3.59342
3.546169
1.013324
_atoms = self.atoms[:] for atom in _atoms: if atom not in atoms: self.remove_atom(atom)
def pruneToAtoms(self, atoms)
Prune the molecule to the specified atoms bonds will be removed atomatically
4.438124
3.606295
1.23066
if timeout > 0.0: log('Polling for events (Blocking, {} seconds)...'.format(timeout), logger_name=_LOGGER_NAME) else: log('Polling for events (Non-Blocking)...', logger_name=_LOGGER_NAME) if select.select([connection], [], [], timeout) == ([], [], []): log('...No events found',...
def poll(connection: connection, timeout: float=1.0) -> Iterable[Event]
Poll the connection for notification events. This method operates as an iterable. It will keep returning events until all events have been read. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. timeout: float Number of...
2.853721
3.213326
0.88809
obj = json.loads(json_string) return cls( UUID(obj['event_id']), obj['event_type'], obj['schema_name'], obj['table_name'], obj['row_id'] )
def fromjson(cls, json_string: str) -> 'Event'
Create a new Event from a from a psycopg2-pgevent event JSON. Parameters ---------- json_string: str Valid psycopg2-pgevent event JSON. Returns ------- Event Event created from JSON deserialization.
3.273854
3.646402
0.897831
return json.dumps({ 'event_id': str(self.id), 'event_type': self.type, 'schema_name': self.schema_name, 'table_name': self.table_name, 'row_id': self.row_id })
def tojson(self) -> str
Serialize an Event into JSON. Returns ------- str JSON-serialized Event.
2.838579
3.037797
0.93442
ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int)) trans_cont_dict = OrderedDict() for i in ordererd: trans_cont_dict[str(i)] = self.plot_info[str(i)] self.plot_info = trans_cont_dict # set empty lists for x,y,z x = [[]for i in...
def input_data(self)
Function to extract data from files according to pid. This function will read in the data with :class:`bowie.plotutils.readdata.ReadInData`.
2.315921
2.281466
1.015102
# declare figure and axes environments fig, ax = plt.subplots(nrows=int(self.num_rows), ncols=int(self.num_cols), sharex=self.sharex, sharey=self.sharey) fig.set_size_inches(self.figure_width,...
def setup_figure(self)
Sets up the initial figure on to which every plot is added.
2.121751
2.120813
1.000442
for i, axis in enumerate(self.ax): # plot everything. First check general dict for parameters related to plots. trans_plot_class_call = globals()[self.plot_types[i]] trans_plot_class = trans_plot_class_call(self.fig, axis, ...
def create_plots(self)
Creates plots according to each plotting class.
4.566364
4.399498
1.037929
query = "CREATE TABLE IF NOT EXISTS _{0}_gram (".format(cardinality) unique = "" for i in reversed(range(cardinality)): if i != 0: unique += "word_{0}, ".format(i) query += "word_{0} TEXT, ".format(i) else: unique +...
def create_ngram_table(self, cardinality)
Creates a table for n-gram of a give cardinality. The table name is constructed from this parameter, for example for cardinality `2` there will be a table `_2_gram` created. Parameters ---------- cardinality : int The cardinality to create a table for.
3.968595
3.804694
1.043079
for i in reversed(range(cardinality)): if i != 0: query = "CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});".format(cardinality, i) self.execute_sql(query)
def create_index(self, cardinality)
Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for.
4.862597
5.552792
0.875703
query = "SELECT " for i in reversed(range(self.cardinality)): if i != 0: query += "word_{0}, ".format(i) elif i == 0: query += "word" if with_counts: query += ", count" query += " FROM _{0}_gram;".format(self....
def ngrams(self, with_counts=False)
Returns all ngrams that are in the table. Parameters ---------- None Returns ------- ngrams : generator A generator for ngram tuples.
3.731061
3.999254
0.932939
query = "SELECT count FROM _{0}_gram".format(len(ngram)) query += self._build_where_clause(ngram) query += ";" result = self.execute_sql(query) return self._extract_first_integer(result)
def ngram_count(self, ngram)
Gets the count for a given ngram from the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. Returns ------- count : int The count of the ngram.
6.155938
5.539348
1.111311
query = "INSERT INTO _{0}_gram {1};".format(len(ngram), self._build_values_clause(ngram, count)) self.execute_sql(query)
def insert_ngram(self, ngram, count)
Inserts a given n-gram with count into the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram.
6.94887
7.386078
0.940806
query = "UPDATE _{0}_gram SET count = {1}".format(len(ngram), count) query += self._build_where_clause(ngram) query += ";" self.execute_sql(query)
def update_ngram(self, ngram, count)
Updates a given ngram in the database. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram.
5.222042
5.603596
0.931909
query = "DELETE FROM _{0}_gram".format(len(ngram)) query += self._build_where_clause(ngram) query += ";" self.execute_sql(query)
def remove_ngram(self, ngram)
Removes a given ngram from the databae. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings.
5.873644
7.868029
0.74652
c = self.con.cursor() c.execute(query) result = c.fetchall() return result
def execute_sql(self, query)
Executes a given query string on an open sqlite database.
3.201767
2.856952
1.120693
if not self._database_exists(): con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) con.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) query = "CREAT...
def create_database(self)
Creates an empty database if not exists.
3.456379
3.332909
1.037046
if self._database_exists(): con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) con.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) query = "DROP DATA...
def reset_database(self)
Re-create an empty database.
2.374108
2.227037
1.066039
DatabaseConnector.create_index(self, cardinality) query = "CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);".format(cardinality) self.execute_sql(query) if self.lowercase: for i in reversed(range(cardinality)): if i != 0: ...
def create_index(self, cardinality)
Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for.
2.170463
2.217575
0.978755
DatabaseConnector.delete_index(self, cardinality) query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;".format(cardinality) self.execute_sql(query) query = "DROP INDEX IF EXISTS idx_{0}_gram_normalized_varchar;".format( cardinality) self.execute_sql(query) ...
def delete_index(self, cardinality)
Delete index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality of the index to delete.
2.246034
2.255091
0.995984
if not self.con: try: self.con = psycopg2.connect(host=self.host, database=self.dbname, user=self.user, password=self.password, port=self.port) except psycopg2.Error as e: print("Error while opening database...
def open_database(self)
Opens the sqlite database.
2.417438
2.348468
1.029368
c = self.con.cursor() c.execute(query) result = [] if c.rowcount > 0: try: result = c.fetchall() except psycopg2.ProgrammingError: pass return result
def execute_sql(self, query)
Executes a given query string on an open postgres database.
2.712446
2.580099
1.051296
con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) query_check = "select datname from pg_catalog.pg_database" query_check += " where datname = '{0}';".format(self.dbname) c = con.cursor() c.exec...
def _database_exists(self)
Check if the database exists.
2.388108
2.280135
1.047354
indices = tuple([self._initialOrder.index(atom.handle) for atom in order]) same = chiral_table[indices] if same: return self.chirality else: if self.chirality == "@": return "@@" else: return "@"
def getChirality(self, order)
(order)->what is the chirality of a given order of atoms?
8.510401
7.917948
1.074824
cef_logger = commonware.log.getLogger('cef') c = {'product': settings.CEF_PRODUCT, 'vendor': settings.CEF_VENDOR, 'version': settings.CEF_VERSION, 'device_version': settings.CEF_DEVICE_VERSION} # The CEF library looks for some things in the env object like # REQUEST_ME...
def log_cef(name, severity=logging.INFO, env=None, username='none', signature=None, **kwargs)
Wraps cef logging function so we don't need to pass in the config dictionary every time. See bug 707060. ``env`` can be either a request object or just the request.META dictionary.
8.773046
8.499962
1.032128
"changedir = {envdir}" from ctox.subst import replace_braces changedir = _get_env_maybe(env, 'testenv', 'changedir') if changedir: return replace_braces(changedir, env) else: return env.toxinidir
def get_changedir(env)
changedir = {envdir}
9.620062
7.507071
1.281467
if hasattr(instance, "__listeners__"): for listener in list(instance.__listeners__): for signal in instance.__listeners__[listener]: signal.disconnect(listener)
def remove_signals_listeners(instance)
utility function that disconnects all listeners from all signals on an object
3.152322
3.482296
0.905242
info = listenerinfo(listener, pass_signal) self._listeners.append(info) _logger.debug("connect %r to %r", str(listener), self._name) # Track listeners in the instances only if inspect.ismethod(listener): listener_object = listener.__self__ # Ensur...
def connect(self, listener, pass_signal=False)
Connect a new listener to this signal :param listener: The listener (callable) to add :param pass_signal: An optional argument that controls if the signal object is explicitly passed to this listener when it is being fired. If enabled, a ``signal=`` keywo...
5.003459
5.009868
0.998721
info = listenerinfo(listener, pass_signal) self._listeners.remove(info) _logger.debug( "disconnect %r from %r", str(listener), self._name) if inspect.ismethod(listener): listener_object = listener.__self__ if hasattr(listener_object, "__listen...
def disconnect(self, listener, pass_signal=False)
Disconnect an existing listener from this signal :param listener: The listener (callable) to remove :param pass_signal: An optional argument that controls if the signal object is explicitly passed to this listener when it is being fired. If enabled, a ``s...
4.098975
4.316866
0.949525
for info in self._listeners[:]: if info.pass_signal: info.listener(*args, signal=self, **kwargs) else: info.listener(*args, **kwargs)
def fire(self, args, kwargs)
Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently.
4.601806
4.951889
0.929303
self._extend_state() def signal_handler(*args, **kwargs): self._events_seen.append((signal, args, kwargs)) signal.connect(signal_handler) if hasattr(self, 'addCleanup'): self.addCleanup(signal.disconnect, signal_handler)
def watchSignal(self, signal)
Setup provisions to watch a specified signal :param signal: The :class:`Signal` to watch for. After calling this method you can use :meth:`assertSignalFired()` and :meth:`assertSignalNotFired()` with the same signal.
4.568482
5.115964
0.892986
event = (signal, args, kwargs) self.assertIn( event, self._events_seen, "\nSignal unexpectedly not fired: {}\n".format(event)) return event
def assertSignalFired(self, signal, *args, **kwargs)
Assert that a signal was fired with appropriate arguments. :param signal: The :class:`Signal` that should have been fired. Typically this is ``SomeClass.on_some_signal`` reference :param args: List of positional arguments passed to the signal handler :param k...
7.654278
9.527964
0.803349
event = (signal, args, kwargs) self.assertNotIn( event, self._events_seen, "\nSignal unexpectedly fired: {}\n".format(event))
def assertSignalNotFired(self, signal, *args, **kwargs)
Assert that a signal was fired with appropriate arguments. :param signal: The :class:`Signal` that should not have been fired. Typically this is ``SomeClass.on_some_signal`` reference :param args: List of positional arguments passed to the signal handler :par...
6.620996
9.02069
0.733979
expected_order = [self._events_seen.index(event) for event in expected_events] actual_order = sorted(expected_order) self.assertEqual( expected_order, actual_order, "\nExpected order of fired signals:\n{}\n" "Actual order obs...
def assertSignalOrdering(self, *expected_events)
Assert that a signals were fired in a specific sequence. :param expected_events: A (varadic) list of events describing the signals that were fired Each element is a 3-tuple (signal, args, kwargs) that describes the event. .. note:: If you are using :meth...
2.718052
2.885433
0.941991
return reverse(viewname, args=args, kwargs=kwargs)
def url(viewname, *args, **kwargs)
Helper for Django's ``reverse`` in templates.
2.985829
2.865619
1.041949
url = urlparse.urlparse(url_) fragment = hash if hash is not None else url.fragment # Use dict(parse_qsl) so we don't get lists of values. q = url.query query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {} query_dict.update((k, v) for k, v in query.items()) query_string = ...
def urlparams(url_, hash=None, **query)
Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced.
2.611548
2.610186
1.000522
try: return urllib.urlencode(items) except UnicodeEncodeError: return urllib.urlencode([(k, smart_str(v)) for k, v in items])
def _urlencode(items)
A Unicode-safe URLencoder.
2.426958
2.317137
1.047395
if isinstance(txt, unicode): txt = txt.encode('utf-8') return urllib.quote_plus(txt)
def urlencode(txt)
Url encode a path.
2.100082
2.274501
0.923316
if isinstance(token.pos, int): _, lineno, colno = node.getpos(subnode, token.pos) else: lineno, colno = None, None yield StreamFragment(subnode, lineno, colno, None, sourcepath_stack[-1])
def token_handler_str_default( token, dispatcher, node, subnode, sourcepath_stack=(None,))
Standard token handler that will return the value, ignoring any tokens or strings that have been remapped.
5.691899
5.854917
0.972157
original = ( node.value if isinstance(node, Identifier) and node.value != subnode else None ) if isinstance(token.pos, int): _, lineno, colno = node.getpos(original or subnode, token.pos) else: lineno, colno = None, None yield StreamFragment( s...
def token_handler_unobfuscate( token, dispatcher, node, subnode, sourcepath_stack=(None,))
A token handler that will resolve and return the original identifier value.
6.199032
6.308612
0.98263
source = stream() if callable(stream) else stream try: text = source.read() stream_name = getattr(source, 'name', None) try: result = parser(text) except ECMASyntaxError as e: error_name = repr_compat(stream_name or source) raise type(e)(...
def read(parser, stream)
Return an AST from the input ES5 stream. Arguments parser A parser instance. stream Either a stream object or a callable that produces one. The stream object to read from; its 'read' method will be invoked. If a callable was provided, the 'close' method on its return ...
5.053178
5.466105
0.924457
closer = [] def get_stream(stream): if callable(stream): result = stream() closer.append(result.close) else: result = stream return result def cleanup(): for close in reversed(closer): close() chunks = None if i...
def write( unparser, nodes, output_stream, sourcemap_stream=None, sourcemap_normalize_mappings=True, sourcemap_normalize_paths=True, source_mapping_url=NotImplemented)
Write out the node using the unparser into an output stream, and optionally the sourcemap using the sourcemap stream. Ideally, file objects should be passed to the *_stream arguments, so that the name resolution built into the sourcemap builder function will be used. Also, if these file objects are op...
2.775587
2.752982
1.008211
if index is None: dof = 0 for i in range(self.len): dof += self.A[i].shape[0] * self.F[i].shape[1] return dof else: return self.A[index].shape[0] * self.F[index].shape[1]
def dof(self, index=None)
The number of degrees of freedom
2.306565
2.288617
1.007842
self.A = [] self.F = [] self.F_any = np.zeros((self.N,0)) self.clear_cache()
def clearFixedEffect(self)
erase all fixed effects
9.79852
9.119329
1.074478
if F is None: F = np.ones((self.N,1)) else: assert F.shape[0]==self.N, "F dimension mismatch" if ((A is None) or ( (A.shape == (self.P,self.P)) and (A==np.eye(self.P)).all() )): #case any effect self.F_any = np.hstack((self.F_any,F)) ...
def addFixedEffect(self,F=None,A=None,index=None)
set sample and trait designs F: NxK sample design A: LxP sample design fast_computations: False deactivates the fast computations for any and common effects (for debugging)
3.17909
3.091118
1.02846
assert value.shape==(self.N, self.N), 'dimension mismatch' self._Lr = value self.clear_cache()
def Lr(self,value)
set row rotation
6.955894
7.921322
0.878123
assert value.shape==(self.P, self.P), 'dimension mismatch' self._Lc = value self.clear_cache()
def Lc(self,value)
set col rotation
7.782881
9.341923
0.833113
assert value.shape[0]==self.P*self.N, 'd dimension mismatch' self._d = value self.clear_cache()
def d(self,value)
set anisotropic scaling
7.192936
7.936202
0.906345
XKY = self.XKY() XanyKY = self.XanyKY() beta_hat, beta_hat_any = self.Areml_solver.solve(b_any=XanyKY,b=XKY,check_finite=True) return beta_hat, beta_hat_any
def beta_hat(self)
compute ML beta
8.931925
8.179308
1.092015
result = np.empty((self.P,self.F_any.shape[1],self.F_any.shape[1]), order='C') for p in range(self.P): X1D = self.Fstar_any * self.D[:,p:p+1] X1X2 = X1D.T.dot(self.Fstar_any) result[p] = X1X2 return result
def XanyKXany(self)
compute self covariance for any
4.367105
3.928221
1.111726
result = np.empty((self.P,self.F_any.shape[1],self.dof), order='C') #This is trivially parallelizable: for p in range(self.P): FanyD = self.Fstar_any * self.D[:,p:p+1] start = 0 #This is trivially parallelizable: for term in range(self.len...
def XanyKX(self)
compute cross covariance for any and rest
5.042521
4.725649
1.067054
cov_beta = np.zeros((self.dof,self.dof)) start_row = 0 #This is trivially parallelizable: for term1 in range(self.len): stop_row = start_row + self.A[term1].shape[0] * self.F[term1].shape[1] start_col = start_row #This is trivially paralleliza...
def XKX(self)
compute self covariance for rest
2.940807
2.799107
1.050623
url = build_url(auth.SERVER_HOST, auth.ACCESS_TOKEN_PATH) if isinstance(scopes, set): scopes = ' '.join(scopes) args = { 'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'scope': scopes, 'code': code, 'refresh_to...
def request_access_token( grant_type, client_id=None, client_secret=None, scopes=None, code=None, refresh_token=None )
Make an HTTP POST to request an access token. Parameters grant_type (str) Either 'client_credientials' (Client Credentials Grant) or 'authorization_code' (Authorization Code Grant). client_id (str) Your app's Client ID. client_secret (str) Your...
2.411364
2.36309
1.020428
if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT: response = request_access_token( grant_type=auth.REFRESH_TOKEN, client_id=credential.client_id, client_secret=credential.client_secret, refresh_token=credential.refresh_token, ) o...
def refresh_access_token(credential)
Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credenti...
1.960772
1.708446
1.147693
url = build_url(auth.SERVER_HOST, auth.REVOKE_PATH) args = { 'token': credential.access_token, } response = post(url=url, params=args) if response.status_code == codes.ok: return message = 'Failed to revoke access token: {}.' message = message.format(response.reason)...
def revoke_access_token(credential)
Revoke an access token. All future requests with the access token will be invalid. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Raises ClientError (APIError) Thrown if there was an HTTP error.
3.505342
3.781963
0.926858
if response_type not in auth.VALID_RESPONSE_TYPES: message = '{} is not a valid response type.' raise LyftIllegalState(message.format(response_type)) args = OrderedDict([ ('scope', ' '.join(self.scopes)), ('state', state), ('response_...
def _build_authorization_request_url( self, response_type, state=None )
Form URL to request an auth code or access token. Parameters response_type (str) Only 'code' (Authorization Code Grant) supported at this time state (str) Optional CSRF State token to send to server. Returns (str) The fu...
3.51468
2.859937
1.228936
qs = urlparse(redirect_url) # redirect_urls return data after query identifier (?) qs = qs.query query_params = parse_qs(qs) query_params = {qp: query_params[qp][0] for qp in query_params} return query_params
def _extract_query(self, redirect_url)
Extract query parameters from a url. Parameters redirect_url (str) The full URL that the Lyft server redirected to after the user authorized your app. Returns (dict) A dictionary of query parameters.
5.534475
6.700484
0.825981
query_params = self._extract_query(redirect_url) authorization_code = self._verify_query(query_params) response = request_access_token( grant_type=auth.AUTHORIZATION_CODE_GRANT, client_id=self.client_id, client_secret=self.client_secret, ...
def get_session(self, redirect_url)
Complete the Authorization Code Grant process. The redirect URL received after the user has authorized your application contains an authorization code. Use this authorization code to request an access token. Parameters redirect_url (str) The full URL that the ...
2.654044
2.55807
1.037518
response = request_access_token( grant_type=auth.CLIENT_CREDENTIAL_GRANT, client_id=self.client_id, client_secret=self.client_secret, scopes=self.scopes, ) oauth2credential = OAuth2Credential.make_from_response( response=respo...
def get_session(self)
Create Session to store credentials. Returns (Session) A Session object with OAuth 2.0 credentials.
2.661037
2.47724
1.074195
try: response = api_client.get_user_profile() except (ClientError, ServerError) as error: fail_print(error) return else: profile = response.json user_id = profile.get('id') message = 'Hello. Successfully granted access token to User ID {}.'.format(user...
def hello_user(api_client)
Use an authorized client to fetch and print profile information. Parameters api_client (LyftRidesClient) An LyftRidesClient with OAuth 2.0 credentials.
5.316257
4.929837
1.078384
"report pylint results" # report according to file extension report_formats = { ".html": "html", ".log": "parseable", ".txt": "text", } lint_build_dir = easy.path("build/lint") lint_build_dir.exists() or lint_build_dir.makedirs() # pylint: disable=expression-not-assigne...
def lint()
report pylint results
3.618198
3.554313
1.017974
# check if pid is dicionary or GenInput class # if GenInput, change to dictionary if isinstance(pid, GenInput): pid = pid.return_dict() begin_time = time.time() WORKING_DIRECTORY = '.' if 'WORKING_DIRECTORY' not in pid['general'].keys(): pid['general']['WORKING_DIRECTORY'...
def generate_contour_data(pid)
Main function for this program. This will read in sensitivity_curves and binary parameters; calculate snrs with a matched filtering approach; and then read the contour data out to a file. Args: pid (obj or dict): GenInput class or dictionary containing all of the input information for ...
5.462134
4.735705
1.153394
if self.socket is not None: msg.version = self.PROTOCOL_VERSION serialized = msg.SerializeToString() data = struct.pack(">I", len(serialized)) + serialized #print("Sending message: %s" % msg) try: self.socket.send(data) ...
def send_message(self, msg)
Internal method used to send messages through Clementine remote network protocol.
3.768516
3.610235
1.043842
self.first_data_sent_complete = False self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) msg = cr.Message() msg.type = cr.CONNECT msg.request_connect.auth_code = self.auth_code or 0 msg.request_co...
def _connect(self)
Connects to the server defined in the constructor.
4.946126
4.4755
1.105156
msg = cr.Message() msg.type = cr.PLAY self.send_message(msg)
def play(self)
Sends a "play" command to the player.
9.400646
6.831972
1.375978
msg = cr.Message() msg.type = cr.PAUSE self.send_message(msg)
def pause(self)
Sends a "play" command to the player.
7.374694
6.907515
1.067633
msg = cr.Message() msg.type = cr.STOP self.send_message(msg)
def stop(self)
Sends a "play" command to the player.
7.135717
6.585185
1.083602
msg = cr.Message() msg.type = cr.PLAYPAUSE self.send_message(msg)
def playpause(self)
Sends a "playpause" command to the player.
7.931174
6.29895
1.259126
msg = cr.Message() msg.type = cr.NEXT self.send_message(msg)
def next(self)
Sends a "next" command to the player.
10.518635
6.718714
1.565573
msg = cr.Message() msg.type = cr.PREVIOUS self.send_message(msg)
def previous(self)
Sends a "previous" command to the player.
10.187168
6.825152
1.492592
msg = cr.Message() msg.type = cr.SET_VOLUME msg.request_set_volume.volume = int(volume) self.send_message(msg)
def set_volume(self, volume)
Sets player volume (note, this does not change host computer main volume).
5.375107
5.119668
1.049894
if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt M = _Mt.transpose([0,2,1]) MLc = sp.tensordot(M, self.Lc().T, (2,0)) MLcLc = sp.tensordot(MLc, self.Lc(), (2,0)) WrMLcWc = sp.tensordot(sp.tensordot(self.Wr(), MLc, (1,0)), self...
def solve_t(self, Mt)
Mt is dim_r x dim_c x d tensor
2.774607
2.694052
1.029901
p[0] = p[1] # section 3.2: REQUIRE command must come before any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands): print("REQUIRE command on line %d must come before any " ...
def p_commands_list(p)
commands : commands command
3.387545
3.298435
1.027016
#print("COMMAND:", p[1], p[2], p[3]) tests = p[2].get('tests') block = None if p[3] != ';': block = p[3] handler = sifter.handler.get('command', p[1]) if handler is None: print("No handler registered for command '%s' on line %d" % (p[1], p.lineno(1))) raise Synta...
def p_command(p)
command : IDENTIFIER arguments ';' | IDENTIFIER arguments block
4.118083
3.794959
1.085146
# section 3.2: REQUIRE command must come before any other commands, # which means it can't be in the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): print("REQUIRE command not allowed inside of a block (line %d)" % (p.li...
def p_block(p)
block : '{' commands '}'
9.236448
7.954487
1.161162
p[0] = { 'args' : p[1], } if len(p) > 2: if p[2] == '(': p[0]['tests'] = p[3] else: p[0]['tests'] = [ p[2] ]
def p_arguments(p)
arguments : argumentlist | argumentlist test | argumentlist '(' testlist ')
2.90035
2.566498
1.130081
if self.module: app.config.from_object(self.module)
def init_app(self, app)
Initialize Flask application.
5.911019
4.874125
1.212735
assert len(context.buf) == len(context.fuzzed_buf) count = number_of_modified_bytes(context.buf, context.fuzzed_buf) assert count < 3 assert count >= 0
def step_impl03(context)
Check assertions. :param context: test context.
5.59334
6.688904
0.836212
assert len(context.buf) == len(context.fuzzed_buf) count = number_of_modified_bytes(context.buf, context.fuzzed_buf) assert count >= 0 assert count <= max_modified
def step_impl(context, max_modified)
Check assertions. :param max_modified: maximum expected number of modifications. :param context: test context.
4.399075
5.044316
0.872085
fuzz_factor = 11 context.fuzzed_string_list = fuzz_string(context.seed, count, fuzz_factor)
def step_impl06(context, count)
Execute fuzzer. :param count: number of string variants to generate. :param context: test context.
7.786883
7.640431
1.019168
assert len(context.fuzzed_string_list) == len_list for fuzzed_string in context.fuzzed_string_list: assert len(context.seed) == len(fuzzed_string) count = number_of_modified_bytes(context.seed, fuzzed_string) assert count >= 0
def step_impl07(context, len_list)
Check assertions. :param len_list: expected number of variants. :param context: test context.
3.622071
4.074868
0.888881
assert context.table, "ENSURE: table is provided." context.file_list = [row['file_path'] for row in context.table.rows]
def step_impl08(context)
Create file list. :param context: test context.
9.276599
9.000966
1.030623
assert context.table, "ENSURE: table is provided." context.app_list = [row['application'] for row in context.table.rows]
def step_impl09(context)
Create application list. :param context: test context.
11.499115
11.304022
1.017259
assert context.app_list and len( context.app_list) > 0, "ENSURE: app list is provided." assert context.file_list and len( context.file_list) > 0, "ENSURE: file list is provided." context.fuzz_executor = FuzzExecutor(context.app_list, context.file_list) assert context.fuzz_executor, ...
def step_impl10(context)
Create application list. :param context: test context.
3.664766
3.652128
1.00346
executor = context.fuzz_executor executor.run_test(runs) stats = executor.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: stats available."
def step_impl11(context, runs)
Execute multiple runs. :param runs: number of test runs to perform. :param context: test context.
16.614876
18.3685
0.904531
executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs."
def step_impl12(context, runs)
Check called apps / files. :param runs: expected number of records. :param context: test context.
19.510523
19.528259
0.999092
executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." successful_runs = stats.cumulated_counts_for_status(Status.SUCCESS) assert successful_runs == runs
def step_impl13(context, runs)
Check called apps / files. :param runs: expected number of records. :param context: test context.
8.871456
8.883206
0.998677
executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." failed_runs = stats.cumulated_counts_for_status(Status.FAILED) assert failed_runs == runs
def step_impl14(context, runs)
Check called apps / files. :param runs: expected number of records. :param context: test context.
9.096228
9.182721
0.990581
count = 0 for idx, b in enumerate(buf): if b != fuzzed_buf[idx]: count += 1 return count
def number_of_modified_bytes(buf, fuzzed_buf)
Determine the number of differing bytes. :param buf: original buffer. :param fuzzed_buf: fuzzed buffer. :return: number of different bytes. :rtype: int
2.414924
2.803714
0.861331
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): '''Given a connected graph adj matrix (W), add edges to flesh it out.''' W = W.astype(bool) assert np.all(W == W.T), 'graph given to flesh_out must be symmetric' D = pa...
Given a connected graph adj matrix (W), add edges to flesh it out.
null
null
null
def edge_cluster_angle(edge_dirs, subspaces1, subspaces2): '''edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.''' QG = edge_dirs / np.linalg.norm(edge_dirs, ord=2, axis=1)[:,None] X1 = np.einsum...
edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.
null
null
null
'''Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2) ''' if not symmetric: if weights is None: return EdgePairGraph(pairs, num_vertices=num_vertices) row, col = np.asarray(pairs).T row, weights = np.broadcast_arrays(ro...
def from_edge_pairs(pairs, num_vertices=None, symmetric=False, weights=None)
Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2)
3.24834
2.872657
1.130779
if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
def W(self,value)
set fixed effect design
9.089366
8.531675
1.065367
if value is None: self._use_to_predict = False else: assert value.shape[1]==self._K, 'Dimension mismatch' self._use_to_predict = True self._Wstar = value self.clear_cache('predict')
def Wstar(self,value)
set fixed effect design for predictions
5.148726
4.544645
1.132921
def name_obfuscation_rules(): inst = Obfuscator( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=reserved_keywords, ) return { 'token_handler': token_handler_unobfuscate, 'deferrable_han...
def obfuscate( obfuscate_globals=False, shadow_funcname=False, reserved_keywords=())
An example, barebone name obfuscation ruleset obfuscate_globals If true, identifier names on the global scope will also be obfuscated. Default is False. shadow_funcname If True, obfuscated function names will be shadowed. Default is False. reserved_keywords A tuple...
4.269869
4.346321
0.98241
return self.local_declared_symbols | ( self.parent.declared_symbols if self.parent else set())
def declared_symbols(self)
Return all local symbols here, and also of the parents
9.112299
5.678647
1.60466