_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40200 | GenProcess.run_snr | train | def run_snr(self):
"""Run the snr calculation.
Takes results from ``self.set_parameters`` and other inputs and inputs these
into the snr calculator.
"""
if self.ecc:
required_kwargs = {'dist_type': self.dist_type,
'initial_cond_type':... | python | {
"resource": ""
} |
q40201 | BaseHandler.event_payment | train | def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server):
'''Record the payment event
Official handler writes this information to TBK_EVN%Y%m%d file.
'''
raise NotImplementedError("Logging Handler must implement event_payment") | python | {
"resource": ""
} |
q40202 | BaseHandler.event_confirmation | train | def event_confirmation(self, date, time, pid, commerce_id, transaction_id, request_ip, order_id):
'''Record the confirmation event.
Official handler writes this information to TBK_EVN%Y%m%d file.
'''
raise NotImplementedError("Logging Handler must implement event_confirmation") | python | {
"resource": ""
} |
q40203 | JSHostManager.stop | train | def stop(self):
"""
If the manager is running, tell it to stop its process
"""
res = self.send_request('manager/stop', post=True)
if res.status_code != 200:
raise UnexpectedResponse(
'Attempted to stop manager. {res_code}: {res_text}'.format(
... | python | {
"resource": ""
} |
q40204 | JSHostManager.stop_host | train | def stop_host(self, config_file):
"""
Stops a managed host specified by `config_file`.
"""
res = self.send_json_request('host/stop', data={'config': config_file})
if res.status_code != 200:
raise UnexpectedResponse(
'Attempted to stop a JSHost. Respon... | python | {
"resource": ""
} |
q40205 | PVWatts.get_data | train | def get_data(self, params={}):
"""
Make the request and return the deserialided JSON from the response
:param params: Dictionary mapping (string) query parameters to values
:type params: dict
:return: JSON object with the data fetched from that URL as a
JSON-for... | python | {
"resource": ""
} |
q40206 | FiniteStateLogger.receive | train | def receive(self, input):
"""
Add logging of state transitions to the wrapped state machine.
@see: L{IFiniteStateMachine.receive}
"""
if IRichInput.providedBy(input):
richInput = unicode(input)
symbolInput = unicode(input.symbol())
else:
... | python | {
"resource": ""
} |
q40207 | ParallelContainer.prep_parallel | train | def prep_parallel(self, binary_args, other_args):
"""Prepare the parallel calculations
Prepares the arguments to be run in parallel.
It will divide up arrays according to num_splits.
Args:
binary_args (list): List of binary arguments for input into the SNR function.
... | python | {
"resource": ""
} |
q40208 | ParallelContainer.run_parallel | train | def run_parallel(self, para_func):
"""Run parallel calulation
This will run the parallel calculation on self.num_processors.
Args:
para_func (obj): Function object to be used in parallel.
Returns:
(dict): Dictionary with parallel results.
"""
i... | python | {
"resource": ""
} |
q40209 | RawParserUnparserFactory | train | def RawParserUnparserFactory(parser_name, parse_callable, *unparse_callables):
"""
Produces a callable object that also has callable attributes that
passes its first argument to the parent callable.
"""
def build_unparse(f):
@wraps(f)
def unparse(self, source, *a, **kw):
... | python | {
"resource": ""
} |
q40210 | downsample_trajectories | train | def downsample_trajectories(trajectories, downsampler, *args, **kwargs):
'''Downsamples all points together, then re-splits into original trajectories.
trajectories : list of 2-d arrays, each representing a trajectory
downsampler(X, *args, **kwargs) : callable that returns indices into X
'''
X = np.vstack(tr... | python | {
"resource": ""
} |
q40211 | epsilon_net | train | def epsilon_net(points, close_distance):
'''Selects a subset of `points` to preserve graph structure while minimizing
the number of points used, by removing points within `close_distance`.
Returns the downsampled indices.'''
num_points = points.shape[0]
indices = set(range(num_points))
selected = []
while... | python | {
"resource": ""
} |
q40212 | transport_from_url | train | def transport_from_url(url):
""" Create a transport for the given URL.
"""
if '/' not in url and ':' in url and url.rsplit(':')[-1].isdigit():
url = 'scgi://' + url
url = urlparse.urlsplit(url, scheme="scgi", allow_fragments=False) # pylint: disable=redundant-keyword-arg
try:
trans... | python | {
"resource": ""
} |
q40213 | _encode_payload | train | def _encode_payload(data, headers=None):
"Wrap data in an SCGI request."
prolog = "CONTENT_LENGTH\0%d\0SCGI\x001\0" % len(data)
if headers:
prolog += _encode_headers(headers)
return _encode_netstring(prolog) + data | python | {
"resource": ""
} |
q40214 | _parse_headers | train | def _parse_headers(headers):
"Get headers dict from header string."
try:
return dict(line.rstrip().split(": ", 1)
for line in headers.splitlines()
if line
)
except (TypeError, ValueError) as exc:
raise SCGIException("Error in SCGI headers %r (%s)" % (headers, ... | python | {
"resource": ""
} |
q40215 | _parse_response | train | def _parse_response(resp):
""" Get xmlrpc response from scgi response
"""
# Assume they care for standards and send us CRLF (not just LF)
try:
headers, payload = resp.split("\r\n\r\n", 1)
except (TypeError, ValueError) as exc:
raise SCGIException("No header delimiter in SCGI response... | python | {
"resource": ""
} |
q40216 | scgi_request | train | def scgi_request(url, methodname, *params, **kw):
""" Send a XMLRPC request over SCGI to the given URL.
@param url: Endpoint URL.
@param methodname: XMLRPC method name.
@param params: Tuple of simple python objects.
@keyword deserialize: Parse XML result? (default is True)
@... | python | {
"resource": ""
} |
q40217 | SCGIRequest.send | train | def send(self, data):
""" Send data over scgi to URL and get response.
"""
start = time.time()
try:
scgi_resp = ''.join(self.transport.send(_encode_payload(data)))
finally:
self.latency = time.time() - start
resp, self.resp_headers = _parse_respon... | python | {
"resource": ""
} |
q40218 | Rollback._frames | train | def _frames(traceback):
'''
Returns generator that iterates over frames in a traceback
'''
frame = traceback
while frame.tb_next:
frame = frame.tb_next
yield frame.tb_frame
return | python | {
"resource": ""
} |
q40219 | Rollback._methodInTraceback | train | def _methodInTraceback(self, name, traceback):
'''
Returns boolean whether traceback contains method from this instance
'''
foundMethod = False
for frame in self._frames(traceback):
this = frame.f_locals.get('self')
if this is self and frame.f_code.co_name == name:
foundMethod = ... | python | {
"resource": ""
} |
q40220 | Rollback.addStep | train | def addStep(self, callback, *args, **kwargs):
'''
Add rollback step with optional arguments. If a rollback is
triggered, each step is called in LIFO order.
'''
self.steps.append((callback, args, kwargs)) | python | {
"resource": ""
} |
q40221 | Rollback.doRollback | train | def doRollback(self):
'''
Call each rollback step in LIFO order.
'''
while self.steps:
callback, args, kwargs = self.steps.pop()
callback(*args, **kwargs) | python | {
"resource": ""
} |
q40222 | describe | train | def describe(db, zip, case_insensitive):
"""Show .dbf file statistics."""
with open_db(db, zip, case_sensitive=not case_insensitive) as dbf:
click.secho('Rows count: %s' % (dbf.prolog.records_count))
click.secho('Fields:')
for field in dbf.fields:
click.secho(' %s: %s' % (f... | python | {
"resource": ""
} |
q40223 | clone_repo | train | def clone_repo(pkg, dest, repo, repo_dest, branch):
"""Clone the Playdoh repo into a custom path."""
git(['clone', '--recursive', '-b', branch, repo, repo_dest]) | python | {
"resource": ""
} |
q40224 | create_virtualenv | train | def create_virtualenv(pkg, repo_dest, python):
"""Creates a virtualenv within which to install your new application."""
workon_home = os.environ.get('WORKON_HOME')
venv_cmd = find_executable('virtualenv')
python_bin = find_executable(python)
if not python_bin:
raise EnvironmentError('%s is n... | python | {
"resource": ""
} |
q40225 | install_reqs | train | def install_reqs(venv, repo_dest):
"""Installs all compiled requirements that can't be shipped in vendor."""
with dir_path(repo_dest):
args = ['-r', 'requirements/compiled.txt']
if not verbose:
args.insert(0, '-q')
subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'ins... | python | {
"resource": ""
} |
q40226 | find_executable | train | def find_executable(name):
"""
Finds the actual path to a named command.
The first one on $PATH wins.
"""
for pt in os.environ.get('PATH', '').split(':'):
candidate = os.path.join(pt, name)
if os.path.exists(candidate):
return candidate | python | {
"resource": ""
} |
q40227 | _my_pdf_formatter | train | def _my_pdf_formatter(data, format, ordered_alphabets) :
""" Generate a logo in PDF format.
Modified from weblogo version 3.4 source code.
"""
eps = _my_eps_formatter(data, format, ordered_alphabets).decode()
gs = weblogolib.GhostscriptAPI()
return gs.convert('pdf', eps, format.logo_wid... | python | {
"resource": ""
} |
q40228 | Molecule.pruneToAtoms | train | def pruneToAtoms(self, atoms):
"""Prune the molecule to the specified atoms
bonds will be removed atomatically"""
_atoms = self.atoms[:]
for atom in _atoms:
if atom not in atoms:
self.remove_atom(atom) | python | {
"resource": ""
} |
q40229 | poll | train | 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
... | python | {
"resource": ""
} |
q40230 | Event.fromjson | train | 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 deser... | python | {
"resource": ""
} |
q40231 | Event.tojson | train | def tojson(self) -> str:
"""Serialize an Event into JSON.
Returns
-------
str
JSON-serialized Event.
"""
return json.dumps({
'event_id': str(self.id),
'event_type': self.type,
'schema_name': self.schema_name,
'... | python | {
"resource": ""
} |
q40232 | MakePlotProcess.setup_figure | train | def setup_figure(self):
"""Sets up the initial figure on to which every plot is added.
"""
# declare figure and axes environments
fig, ax = plt.subplots(nrows=int(self.num_rows),
ncols=int(self.num_cols),
sharex=self.sharex,... | python | {
"resource": ""
} |
q40233 | MakePlotProcess.create_plots | train | def create_plots(self):
"""Creates plots according to each plotting class.
"""
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_cla... | python | {
"resource": ""
} |
q40234 | DatabaseConnector.create_ngram_table | train | 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
... | python | {
"resource": ""
} |
q40235 | DatabaseConnector.ngrams | train | def ngrams(self, with_counts=False):
"""
Returns all ngrams that are in the table.
Parameters
----------
None
Returns
-------
ngrams : generator
A generator for ngram tuples.
"""
query = "SELECT "
for i in reversed(ra... | python | {
"resource": ""
} |
q40236 | DatabaseConnector.ngram_count | train | 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.
"""
... | python | {
"resource": ""
} |
q40237 | DatabaseConnector.insert_ngram | train | 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.
"""
query = ... | python | {
"resource": ""
} |
q40238 | DatabaseConnector.update_ngram | train | 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 :... | python | {
"resource": ""
} |
q40239 | DatabaseConnector.remove_ngram | train | 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.
"""
... | python | {
"resource": ""
} |
q40240 | SqliteDatabaseConnector.execute_sql | train | def execute_sql(self, query):
"""
Executes a given query string on an open sqlite database.
"""
c = self.con.cursor()
c.execute(query)
result = c.fetchall()
return result | python | {
"resource": ""
} |
q40241 | PostgresDatabaseConnector.create_database | train | def create_database(self):
"""
Creates an empty database if not exists.
"""
if not self._database_exists():
con = psycopg2.connect(host=self.host, database="postgres",
user=self.user, password=self.password, port=self.port)
con.set_isolati... | python | {
"resource": ""
} |
q40242 | PostgresDatabaseConnector.reset_database | train | def reset_database(self):
"""
Re-create an empty database.
"""
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(
... | python | {
"resource": ""
} |
q40243 | PostgresDatabaseConnector.delete_index | train | def delete_index(self, cardinality):
"""
Delete index for the table with the given cardinality.
Parameters
----------
cardinality : int
The cardinality of the index to delete.
"""
DatabaseConnector.delete_index(self, cardinality)
query = "DR... | python | {
"resource": ""
} |
q40244 | PostgresDatabaseConnector.open_database | train | def open_database(self):
"""
Opens the sqlite database.
"""
if not self.con:
try:
self.con = psycopg2.connect(host=self.host,
database=self.dbname, user=self.user,
password=self.password, port=self.port)
exc... | python | {
"resource": ""
} |
q40245 | PostgresDatabaseConnector.execute_sql | train | def execute_sql(self, query):
"""
Executes a given query string on an open postgres database.
"""
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingE... | python | {
"resource": ""
} |
q40246 | PostgresDatabaseConnector._database_exists | train | def _database_exists(self):
"""
Check if the database exists.
"""
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 += " w... | python | {
"resource": ""
} |
q40247 | log_cef | train | 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.
"""
... | python | {
"resource": ""
} |
q40248 | remove_signals_listeners | train | def remove_signals_listeners(instance):
"""
utility function that disconnects all listeners from all signals on an
object
"""
if hasattr(instance, "__listeners__"):
for listener in list(instance.__listeners__):
for signal in instance.__listeners__[listener]:
signa... | python | {
"resource": ""
} |
q40249 | signal.connect | train | 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... | python | {
"resource": ""
} |
q40250 | signal.disconnect | train | 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... | python | {
"resource": ""
} |
q40251 | signal.fire | train | 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.
"""
for inf... | python | {
"resource": ""
} |
q40252 | SignalInterceptorMixIn.watchSignal | train | 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.
"""
... | python | {
"resource": ""
} |
q40253 | SignalInterceptorMixIn.assertSignalOrdering | train | 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
... | python | {
"resource": ""
} |
q40254 | url | train | def url(viewname, *args, **kwargs):
"""Helper for Django's ``reverse`` in templates."""
return reverse(viewname, args=args, kwargs=kwargs) | python | {
"resource": ""
} |
q40255 | _urlencode | train | def _urlencode(items):
"""A Unicode-safe URLencoder."""
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for k, v in items]) | python | {
"resource": ""
} |
q40256 | urlencode | train | def urlencode(txt):
"""Url encode a path."""
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) | python | {
"resource": ""
} |
q40257 | token_handler_str_default | train | 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.
"""
if isinstance(token.pos, int):
_, lineno, colno = node.getpos(subnode, token... | python | {
"resource": ""
} |
q40258 | token_handler_unobfuscate | train | def token_handler_unobfuscate(
token, dispatcher, node, subnode, sourcepath_stack=(None,)):
"""
A token handler that will resolve and return the original identifier
value.
"""
original = (
node.value
if isinstance(node, Identifier) and node.value != subnode else
None... | python | {
"resource": ""
} |
q40259 | read | train | 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,... | python | {
"resource": ""
} |
q40260 | write | train | 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 sou... | python | {
"resource": ""
} |
q40261 | Mean.dof | train | def dof(self, index=None):
"""The number of degrees of freedom"""
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].shap... | python | {
"resource": ""
} |
q40262 | Mean.beta_hat | train | def beta_hat(self):
"""compute ML beta"""
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 | python | {
"resource": ""
} |
q40263 | Mean.XanyKXany | train | def XanyKXany(self):
"""
compute self covariance for any
"""
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... | python | {
"resource": ""
} |
q40264 | Mean.XanyKX | train | def XanyKX(self):
"""
compute cross covariance for any and rest
"""
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
... | python | {
"resource": ""
} |
q40265 | Mean.XKX | train | def XKX(self):
"""
compute self covariance for rest
"""
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]
... | python | {
"resource": ""
} |
q40266 | lint | train | def lint():
"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... | python | {
"resource": ""
} |
q40267 | generate_contour_data | train | 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 a... | python | {
"resource": ""
} |
q40268 | ClementineRemote.send_message | train | def send_message(self, msg):
"""
Internal method used to send messages through Clementine remote network protocol.
"""
if self.socket is not None:
msg.version = self.PROTOCOL_VERSION
serialized = msg.SerializeToString()
data = struct.pack(">I", len(s... | python | {
"resource": ""
} |
q40269 | ClementineRemote._connect | train | def _connect(self):
"""
Connects to the server defined in the constructor.
"""
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 =... | python | {
"resource": ""
} |
q40270 | ClementineRemote.playpause | train | def playpause(self):
"""
Sends a "playpause" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAYPAUSE
self.send_message(msg) | python | {
"resource": ""
} |
q40271 | ClementineRemote.next | train | def next(self):
"""
Sends a "next" command to the player.
"""
msg = cr.Message()
msg.type = cr.NEXT
self.send_message(msg) | python | {
"resource": ""
} |
q40272 | ClementineRemote.previous | train | def previous(self):
"""
Sends a "previous" command to the player.
"""
msg = cr.Message()
msg.type = cr.PREVIOUS
self.send_message(msg) | python | {
"resource": ""
} |
q40273 | step_impl06 | train | def step_impl06(context, count):
"""Execute fuzzer.
:param count: number of string variants to generate.
:param context: test context.
"""
fuzz_factor = 11
context.fuzzed_string_list = fuzz_string(context.seed, count, fuzz_factor) | python | {
"resource": ""
} |
q40274 | step_impl08 | train | def step_impl08(context):
"""Create file list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.file_list = [row['file_path'] for row in context.table.rows] | python | {
"resource": ""
} |
q40275 | step_impl11 | train | def step_impl11(context, runs):
"""Execute multiple runs.
:param runs: number of test runs to perform.
:param context: test context.
"""
executor = context.fuzz_executor
executor.run_test(runs)
stats = executor.stats
count = stats.cumulated_counts()
assert count == runs, "VERIFY: st... | python | {
"resource": ""
} |
q40276 | number_of_modified_bytes | train | 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
"""
count = 0
for idx, b in enumerate(buf):
if b != fuzzed_buf[idx]:
... | python | {
"resource": ""
} |
q40277 | MeanBase.W | train | def W(self,value):
""" set fixed effect design """
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') | python | {
"resource": ""
} |
q40278 | obfuscate | train | 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, ob... | python | {
"resource": ""
} |
q40279 | Scope.declared_symbols | train | def declared_symbols(self):
"""
Return all local symbols here, and also of the parents
"""
return self.local_declared_symbols | (
self.parent.declared_symbols if self.parent else set()) | python | {
"resource": ""
} |
q40280 | Scope.global_symbols | train | def global_symbols(self):
"""
These are symbols that have been referenced, but not declared
within this scope or any parent scopes.
"""
declared_symbols = self.declared_symbols
return set(
s for s in self.referenced_symbols if s not in declared_symbols) | python | {
"resource": ""
} |
q40281 | Scope.global_symbols_in_children | train | def global_symbols_in_children(self):
"""
This is based on all children referenced symbols that have not
been declared.
The intended use case is to ban the symbols from being used as
remapped symbol values.
"""
result = set()
for child in self.children:
... | python | {
"resource": ""
} |
q40282 | Scope.close | train | def close(self):
"""
Mark the scope as closed, i.e. all symbols have been declared,
and no further declarations should be done.
"""
if self._closed:
raise ValueError('scope is already marked as closed')
# By letting parent know which symbols this scope has l... | python | {
"resource": ""
} |
q40283 | Scope._reserved_symbols | train | def _reserved_symbols(self):
"""
Helper property for the build_remap_symbols method. This
property first resolves _all_ local references from parents,
skipping all locally declared symbols as the goal is to generate
a local mapping for them, but in a way not to shadow over any
... | python | {
"resource": ""
} |
q40284 | Scope.build_remap_symbols | train | def build_remap_symbols(self, name_generator, children_only=True):
"""
This builds the replacement table for all the defined symbols
for all the children, and this scope, if the children_only
argument is False.
"""
if not children_only:
replacement = name_gen... | python | {
"resource": ""
} |
q40285 | Scope.nest | train | def nest(self, node, cls=None):
"""
Create a new nested scope that is within this instance, binding
the provided node to it.
"""
if cls is None:
cls = type(self)
nested_scope = cls(node, self)
self.children.append(nested_scope)
return nested_... | python | {
"resource": ""
} |
q40286 | CatchScope.declare | train | def declare(self, symbol):
"""
Nothing gets declared here - it's the parents problem, except
for the case where the symbol is the one we have here.
"""
if symbol != self.catch_symbol:
self.parent.declare(symbol) | python | {
"resource": ""
} |
q40287 | CatchScope.reference | train | def reference(self, symbol, count=1):
"""
However, if referenced, ensure that the counter is applied to
the catch symbol.
"""
if symbol == self.catch_symbol:
self.catch_symbol_usage += count
else:
self.parent.reference(symbol, count) | python | {
"resource": ""
} |
q40288 | CatchScope.build_remap_symbols | train | def build_remap_symbols(self, name_generator, children_only=None):
"""
The children_only flag is inapplicable, but this is included as
the Scope class is defined like so.
Here this simply just place the catch symbol with the next
replacement available.
"""
repla... | python | {
"resource": ""
} |
q40289 | Obfuscator.register_reference | train | def register_reference(self, dispatcher, node):
"""
Register this identifier to the current scope, and mark it as
referenced in the current scope.
"""
# the identifier node itself will be mapped to the current scope
# for the resolve to work
# This should probabl... | python | {
"resource": ""
} |
q40290 | Obfuscator.shadow_reference | train | def shadow_reference(self, dispatcher, node):
"""
Only simply make a reference to the value in the current scope,
specifically for the FuncBase type.
"""
# as opposed to the previous one, only add the value of the
# identifier itself to the scope so that it becomes reser... | python | {
"resource": ""
} |
q40291 | Obfuscator.resolve | train | def resolve(self, dispatcher, node):
"""
For the given node, resolve it into the scope it was declared
at, and if one was found, return its value.
"""
scope = self.identifiers.get(node)
if not scope:
return node.value
return scope.resolve(node.value) | python | {
"resource": ""
} |
q40292 | Obfuscator.walk | train | def walk(self, dispatcher, node):
"""
Walk through the node with a custom dispatcher for extraction of
details that are required.
"""
deferrable_handlers = {
Declare: self.declare,
Resolve: self.register_reference,
}
layout_handlers = {
... | python | {
"resource": ""
} |
q40293 | Obfuscator.finalize | train | def finalize(self):
"""
Finalize the run - build the name generator and use it to build
the remap symbol tables.
"""
self.global_scope.close()
name_generator = NameGenerator(skip=self.reserved_keywords)
self.global_scope.build_remap_symbols(
name_gene... | python | {
"resource": ""
} |
q40294 | Obfuscator.prewalk_hook | train | def prewalk_hook(self, dispatcher, node):
"""
This is for the Unparser to use as a prewalk hook.
"""
self.walk(dispatcher, node)
self.finalize()
return node | python | {
"resource": ""
} |
q40295 | clean | train | def clean():
"take out the trash"
src_dir = easy.options.setdefault("docs", {}).get('src_dir', None)
if src_dir is None:
src_dir = 'src' if easy.path('src').exists() else '.'
with easy.pushd(src_dir):
for pkg in set(easy.options.setup.packages) | set(("tests",)):
for filenam... | python | {
"resource": ""
} |
q40296 | Generate._set_grid_info | train | def _set_grid_info(self, which, low, high, num, scale, name):
"""Set the grid values for x or y.
Create information for the grid of x and y values.
Args:
which (str): `x` or `y`.
low/high (float): Lowest/highest value for the axis.
num (int): Number of point... | python | {
"resource": ""
} |
q40297 | Generate.set_y_grid_info | train | def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name):
"""Set the grid values for y.
Create information for the grid of y values.
Args:
num_y (int): Number of points on axis.
y_low/y_high (float): Lowest/highest value for the axis.
yscale (str):... | python | {
"resource": ""
} |
q40298 | Generate.set_x_grid_info | train | def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name):
"""Set the grid values for x.
Create information for the grid of x values.
Args:
num_x (int): Number of points on axis.
x_low/x_high (float): Lowest/highest value for the axis.
xscale (str):... | python | {
"resource": ""
} |
q40299 | SensitivityInput.add_noise_curve | train | def add_noise_curve(self, name, noise_type='ASD', is_wd_background=False):
"""Add a noise curve for generation.
This will add a noise curve for an SNR calculation by appending to the sensitivity_curves
list within the sensitivity_input dictionary.
The name of the noise curve prior to t... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.