_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40100 | check_units_and_type | train | def check_units_and_type(input, expected_units, num=None, is_scalar=False):
"""Check whether variable has expected units and type.
If input does not have units and expected units is not None, then the
output will be assigned those units. If input has units that conflict
with expected units a ValueError... | python | {
"resource": ""
} |
q40101 | check_array_or_list | train | def check_array_or_list(input):
"""Return 1D ndarray, if input can be converted and elements are
non-negative."""
if type(input) != np.ndarray:
if type(input) == list:
output = np.array(input)
else:
raise TypeError('Expecting input type as ndarray or list.')
else:... | python | {
"resource": ""
} |
q40102 | print_object_attributes | train | def print_object_attributes( thing, heading=None, file=None ):
'''
Print the attribute names in thing vertically
'''
if heading : print( '==', heading, '==', file=file )
print( '\n'.join( object_attributes( thing ) ), file=file ) | python | {
"resource": ""
} |
q40103 | _get_a_code_object_from | train | def _get_a_code_object_from( thing ) :
'''
Given a thing that might be a property, a class method,
a function or a code object, reduce it to code object.
If we cannot, return the thing itself.
'''
# If we were passed a Method wrapper, get its function
if isinstance( thing, types.MethodType )... | python | {
"resource": ""
} |
q40104 | printcodelist | train | def printcodelist(thing, to=sys.stdout, heading=None):
'''
Write the lines of the codelist string list to the given file, or to
the default output.
A little Python 3 problem: if the to-file is in binary mode, we need to
encode the strings, else a TypeError will be raised. Obvious answer, test
f... | python | {
"resource": ""
} |
q40105 | Code._findlinestarts | train | def _findlinestarts(code_object):
"""
Find the offsets in a byte code which are the start of source lines.
Generate pairs (offset, lineno) as described in Python/compile.c.
This is a modified version of dis.findlinestarts. This version allows
multiple "line starts" with the sam... | python | {
"resource": ""
} |
q40106 | EmbedMixin.isomap | train | def isomap(self, num_dims=None, directed=None):
'''Isomap embedding.
num_dims : dimension of embedded coordinates, defaults to input dimension
directed : used for .shortest_path() calculation
'''
W = -0.5 * self.shortest_path(directed=directed) ** 2
kpca = KernelPCA(n_components=num_dims, kerne... | python | {
"resource": ""
} |
q40107 | EmbedMixin.laplacian_eigenmaps | train | def laplacian_eigenmaps(self, num_dims=None, normed=True, val_thresh=1e-8):
'''Laplacian Eigenmaps embedding.
num_dims : dimension of embedded coordinates, defaults to input dimension
normed : used for .laplacian() calculation
val_thresh : threshold for omitting vectors with near-zero eigenvalues
'... | python | {
"resource": ""
} |
q40108 | EmbedMixin.layout_circle | train | def layout_circle(self):
'''Position vertices evenly around a circle.'''
n = self.num_vertices()
t = np.linspace(0, 2*np.pi, n+1)[:n]
return np.column_stack((np.cos(t), np.sin(t))) | python | {
"resource": ""
} |
q40109 | walk | train | def walk(dispatcher, node, definition=None):
"""
The default, standalone walk function following the standard
argument ordering for the unparsing walkers.
Arguments:
dispatcher
a Dispatcher instance, defined earlier in this module. This
instance will dispatch out the correct calla... | python | {
"resource": ""
} |
q40110 | constructFiniteStateMachine | train | def constructFiniteStateMachine(inputs, outputs, states, table, initial,
richInputs, inputContext, world,
logger=LOGGER):
"""
Construct a new finite state machine from a definition of its states.
@param inputs: Definitions of all input symbols... | python | {
"resource": ""
} |
q40111 | _checkConsistency | train | def _checkConsistency(richInputs, fsm, inputContext):
"""
Verify that the outputs that can be generated by fsm have their
requirements satisfied by the given rich inputs.
@param richInputs: A L{list} of all of the types which will serve as rich
inputs to an L{IFiniteStateMachine}.
@type ric... | python | {
"resource": ""
} |
q40112 | minify | train | def minify(drop_semi=True):
"""
Rules for minifying output.
Arguments:
drop_semi
Drop semicolons whenever possible. Note that if Dedent and
OptionalNewline has a handler defined, it will stop final break
statements from being resolved due to reliance on normalized
reso... | python | {
"resource": ""
} |
q40113 | indent | train | def indent(indent_str=None):
"""
A complete, standalone indent ruleset.
Arguments:
indent_str
The string used for indentation. Defaults to None, which will
defer the value used to the one provided by the Dispatcher.
"""
def indentation_rule():
inst = Indentator(indent... | python | {
"resource": ""
} |
q40114 | getPyroleLikeAtoms | train | def getPyroleLikeAtoms(cycle):
"""cycle->return a dictionary of pyrole nitrogen-like atoms in
a cycle or a molecule The dictionary is keyed on the atom.handle"""
result = {}
# the outgoing bonds might need to be single or aromatic
for atom in cycle.atoms:
lookup = (atom.symbol, atom.cha... | python | {
"resource": ""
} |
q40115 | convert | train | def convert(cycle, pyroleLike, usedPyroles):
"""cycle, pyroleLike, aromatic=0-> aromatize the cycle
pyroleLike is a lookup of the pyrole like atoms in the
cycle.
return 1 if the cycle was aromatized
2 if the cycle could not be aromatized"""
bonds = cycle.bonds
atoms = cycle.atoms
... | python | {
"resource": ""
} |
q40116 | SensitivityContainer._prep_noise_interpolants | train | def _prep_noise_interpolants(self):
"""Construct interpolated sensitivity curves
This will construct the interpolated sensitivity curves
using scipy.interpolate.interp1d. It will add wd noise
if that is requested.
Raises:
ValueError: ``len(noise_type_in) != len(sens... | python | {
"resource": ""
} |
q40117 | create_selfsim | train | def create_selfsim(oracle, method='rsfx'):
""" Create self similarity matrix from attributes of a vmo object
:param oracle: a encoded vmo object
:param method:
"comp":use the compression codes
"sfx" - use suffix links
"rsfx" - use reverse suffix links
"lrs" - use LRS values
... | python | {
"resource": ""
} |
q40118 | create_transition | train | def create_transition(oracle, method='trn'):
"""Create a transition matrix based on oracle links"""
mat, hist, n = _create_trn_mat_symbolic(oracle, method)
return mat, hist, n | python | {
"resource": ""
} |
q40119 | predict | train | def predict(oracle, context, ab=None, verbose=False):
"""Single symbolic prediction given a context, an oracle and an alphabet.
:param oracle: a learned vmo object from a symbolic sequence.
:param context: the context precedes the predicted symbol
:param ab: alphabet
:param verbose: to show if the ... | python | {
"resource": ""
} |
q40120 | log_loss | train | def log_loss(oracle, test_seq, ab=[], m_order=None, verbose=False):
""" Evaluate the average log-loss of a sequence given an oracle """
if not ab:
ab = oracle.get_alphabet()
if verbose:
print(' ')
logP = 0.0
context = []
increment = np.floor((len(test_seq) - 1) / 100)
bar_c... | python | {
"resource": ""
} |
q40121 | _rsfx_count | train | def _rsfx_count(oracle, s, count, hist, ab):
""" Accumulate counts for context """
trn_data = [oracle.data[n] for n in oracle.trn[s]]
for k in trn_data:
hist[ab[k]] += 1.0
count += 1.0
rsfx_candidate = oracle.rsfx[s][:]
while rsfx_candidate:
s = rsfx_candidate.pop(0)
... | python | {
"resource": ""
} |
q40122 | tracking | train | def tracking(oracle, obs, trn_type=1, reverse_init=False, method='else', decay=1.0):
""" Off-line tracking function using sub-optimal query-matching algorithm"""
N = len(obs)
if reverse_init:
r_oracle = create_reverse_oracle(oracle)
_ind = [r_oracle.n_states - rsfx for rsfx in r_oracle.rsfx[... | python | {
"resource": ""
} |
q40123 | _query_init | train | def _query_init(k, oracle, query, method='all'):
"""A helper function for query-matching function initialization."""
if method == 'all':
a = np.subtract(query, [oracle.f_array[t] for t in oracle.latent[oracle.data[k]]])
dvec = (a * a).sum(axis=1) # Could skip the sqrt
_d = dvec.argmin()... | python | {
"resource": ""
} |
q40124 | _dist_obs_oracle | train | def _dist_obs_oracle(oracle, query, trn_list):
"""A helper function calculating distances between a feature and frames in oracle."""
a = np.subtract(query, [oracle.f_array[t] for t in trn_list])
return (a * a).sum(axis=1) | python | {
"resource": ""
} |
q40125 | safe_shell_out | train | def safe_shell_out(cmd, verbose=False, **kwargs):
"""run cmd and return True if it went ok, False if something went wrong.
Suppress all output.
"""
# TODO rename this suppressed_shell_out ?
# TODO this should probably return 1 if there's an error (i.e. vice-versa).
# print("cmd %s" % cmd)
... | python | {
"resource": ""
} |
q40126 | prev_deps | train | def prev_deps(env):
"""Naively gets the dependancies from the last time ctox was run."""
# TODO something more clever.
if not os.path.isfile(env.envctoxfile):
return []
with open(env.envctoxfile) as f:
return f.read().split() | python | {
"resource": ""
} |
q40127 | make_dist | train | def make_dist(toxinidir, toxdir, package):
"""zip up the package into the toxdir."""
dist = os.path.join(toxdir, "dist")
# Suppress warnings.
success = safe_shell_out(["python", "setup.py", "sdist", "--quiet",
"--formats=zip", "--dist-dir", dist],
... | python | {
"resource": ""
} |
q40128 | print_pretty_command | train | def print_pretty_command(env, command):
"""This is a hack for prettier printing.
Rather than "{envpython} foo.py" we print "python foo.py".
"""
cmd = abbr_cmd = command[0]
if cmd.startswith(env.envbindir):
abbr_cmd = os.path.relpath(cmd, env.envbindir)
if abbr_cmd == ".":
... | python | {
"resource": ""
} |
q40129 | TreeLikelihood.tree | train | def tree(self):
"""Tree with branch lengths in codon substitutions per site.
The tree is a `Bio.Phylo.BaseTree.Tree` object.
This is the current tree after whatever optimizations have
been performed so far.
"""
bs = self.model.branchScale
for node in self._tree.... | python | {
"resource": ""
} |
q40130 | TreeLikelihood.paramsarraybounds | train | def paramsarraybounds(self):
"""Bounds for parameters in `paramsarray`."""
bounds = []
for (i, param) in self._index_to_param.items():
if isinstance(param, str):
bounds.append(self.model.PARAMLIMITS[param])
elif isinstance(param, tuple):
bo... | python | {
"resource": ""
} |
q40131 | TreeLikelihood.paramsarray | train | def paramsarray(self):
"""All free model parameters as 1-dimensional `numpy.ndarray`.
You are allowed to update model parameters by direct
assignment of this property."""
# Return copy of `_paramsarray` because setter checks if changed
if self._paramsarray is not None:
... | python | {
"resource": ""
} |
q40132 | TreeLikelihood.paramsarray | train | def paramsarray(self, value):
"""Set new `paramsarray` and update via `updateParams`."""
nparams = len(self._index_to_param)
assert (isinstance(value, scipy.ndarray) and value.ndim == 1), (
"paramsarray must be 1-dim ndarray")
assert len(value) == nparams, ("Assigning par... | python | {
"resource": ""
} |
q40133 | TreeLikelihood.dtcurrent | train | def dtcurrent(self, value):
"""Set value of `dtcurrent`, update derivatives if needed."""
assert isinstance(value, bool)
if value and self.dparamscurrent:
raise RuntimeError("Can't set both dparamscurrent and dtcurrent True")
if value != self.dtcurrent:
self._dtcu... | python | {
"resource": ""
} |
q40134 | TreeLikelihood.t | train | def t(self, value):
"""Set new branch lengths, update likelihood and derivatives."""
assert (isinstance(value, scipy.ndarray) and (value.dtype ==
'float') and (value.shape == self.t.shape))
if (self._t != value).any():
self._t = value.copy()
self._updateIn... | python | {
"resource": ""
} |
q40135 | TreeLikelihood.dloglikarray | train | def dloglikarray(self):
"""Derivative of `loglik` with respect to `paramsarray`."""
assert self.dparamscurrent, "dloglikarray requires paramscurrent == True"
nparams = len(self._index_to_param)
dloglikarray = scipy.ndarray(shape=(nparams,), dtype='float')
for (i, param) in self._... | python | {
"resource": ""
} |
q40136 | TreeLikelihood.updateParams | train | def updateParams(self, newvalues):
"""Update model parameters and re-compute likelihoods.
This method is the **only** acceptable way to update model
parameters. The likelihood is re-computed as needed
by this method.
Args:
`newvalues` (dict)
A dictio... | python | {
"resource": ""
} |
q40137 | TreeLikelihood._M | train | def _M(self, k, t, tips=None, gaps=None):
"""Returns matrix exponential `M`."""
if self._distributionmodel:
return self.model.M(k, t, tips, gaps)
else:
return self.model.M(t, tips, gaps) | python | {
"resource": ""
} |
q40138 | TreeLikelihood._dM | train | def _dM(self, k, t, param, M, tips=None, gaps=None):
"""Returns derivative of matrix exponential."""
if self._distributionmodel:
return self.model.dM(k, t, param, M, tips, gaps)
else:
return self.model.dM(t, param, M, tips, gaps) | python | {
"resource": ""
} |
q40139 | TreeLikelihood._stationarystate | train | def _stationarystate(self, k):
"""Returns the stationarystate ."""
if self._distributionmodel:
return self.model.stationarystate(k)
else:
return self.model.stationarystate | python | {
"resource": ""
} |
q40140 | TreeLikelihood._dstationarystate | train | def _dstationarystate(self, k, param):
"""Returns the dstationarystate ."""
if self._distributionmodel:
return self.model.dstationarystate(k, param)
else:
return self.model.dstationarystate(param) | python | {
"resource": ""
} |
q40141 | TreeLikelihood._paramlist_PartialLikelihoods | train | def _paramlist_PartialLikelihoods(self):
"""List of parameters looped over in `_computePartialLikelihoods`."""
if self._distributionmodel:
return [param for param in self.model.freeparams +
[self.model.distributedparam] if param not in
self.model.distr... | python | {
"resource": ""
} |
q40142 | TreeLikelihood._sub_index_param | train | def _sub_index_param(self, param):
"""Returns list of sub-indexes for `param`.
Used in computing partial likelihoods; loop over these indices."""
if self._distributionmodel and (param ==
self.model.distributedparam):
indices = [()]
else:
paramvalu... | python | {
"resource": ""
} |
q40143 | JSHost.send_request | train | def send_request(self, *args, **kwargs):
"""
Intercept connection errors which suggest that a managed host has
crashed and raise an exception indicating the location of the log
"""
try:
return super(JSHost, self).send_request(*args, **kwargs)
except RequestsCo... | python | {
"resource": ""
} |
q40144 | _updateB | train | def _updateB(oldB, B, W, degrees, damping, inds, backinds): # pragma: no cover
'''belief update function.'''
for j,d in enumerate(degrees):
kk = inds[j]
bk = backinds[j]
if d == 0:
B[kk,bk] = -np.inf
continue
belief = W[kk,bk] + W[j]
oldBj = oldB[j]
if d == oldBj.s... | python | {
"resource": ""
} |
q40145 | make_constants | train | def make_constants(builtin_only=False, stoplist=[], verbose=False):
"""
Return a decorator for optimizing global references.
Verify that the first argument is a function.
"""
if type(builtin_only) == type(make_constants):
raise ValueError("The make_constants decorator must have argumen... | python | {
"resource": ""
} |
q40146 | pause | train | def pause():
'''Pause playback.
Calls PlaybackController.pause()'''
server = getServer()
server.core.playback.pause()
pos = server.core.playback.get_time_position()
print('Paused at {}'.format(formatTimeposition(pos))) | python | {
"resource": ""
} |
q40147 | play_backend_uri | train | def play_backend_uri(argv=None):
'''Get album or track from backend uri and play all tracks found.
uri is a string which represents some directory belonging to a backend.
Calls LibraryController.browse(uri) to get an album and LibraryController.lookup(uri)
to get track'''
if argv is None:
... | python | {
"resource": ""
} |
q40148 | peekable.peek | train | def peek(self, default=None):
'''Returns `default` is there is no subsequent item'''
try:
result = self.pointer.next()
# immediately push it back onto the front of the iterable
self.pointer = itertools.chain([result], self.pointer)
return result
ex... | python | {
"resource": ""
} |
q40149 | Payment.token | train | def token(self):
"""
Token given by Transbank for payment initialization url.
Will raise PaymentError when an error ocurred.
"""
if not self._token:
self._token = self.fetch_token()
logger.payment(self)
return self._token | python | {
"resource": ""
} |
q40150 | Payment.transaction_id | train | def transaction_id(self):
"""
Transaction ID for Transbank, a secure random int between 0 and 999999999.
"""
if not self._transaction_id:
self._transaction_id = random.randint(0, 10000000000 - 1)
return self._transaction_id | python | {
"resource": ""
} |
q40151 | PhenomDWaveforms._broadcast_and_set_attrs | train | def _broadcast_and_set_attrs(self, local_dict):
"""Cast all inputs to correct dimensions.
This method fixes inputs who have different lengths. Namely one input as
an array and others that are scalara or of len-1.
Raises:
Value Error: Multiple length arrays of len>1
... | python | {
"resource": ""
} |
q40152 | PhenomDWaveforms._create_waveforms | train | def _create_waveforms(self):
"""Create frequency domain waveforms.
Method to create waveforms for PhenomDWaveforms class.
It adds waveform information in the form of attributes.
"""
c_obj = ctypes.CDLL(self.exec_call)
# prepare ctypes arrays
freq_amp_cast = ct... | python | {
"resource": ""
} |
q40153 | EccentricBinaries._convert_units | train | def _convert_units(self):
"""Convert units to geometrized units.
Change to G=c=1 (geometrized) units for ease in calculations.
"""
self.m1 = self.m1*M_sun*ct.G/ct.c**2
self.m2 = self.m2*M_sun*ct.G/ct.c**2
initial_cond_type_conversion = {
'time': ct.c*ct.Juli... | python | {
"resource": ""
} |
q40154 | EccentricBinaries._t_of_e | train | def _t_of_e(self, a0=None, t_start=None, f0=None, ef=None, t_obs=5.0):
"""Rearranged versions of Peters equations
This function calculates the semi-major axis and eccentricity over time.
"""
if ef is None:
ef = np.ones_like(self.e0)*0.0000001
beta = 64.0/5.0*self.m... | python | {
"resource": ""
} |
q40155 | EccentricBinaries._chirp_mass | train | def _chirp_mass(self):
"""Chirp mass calculation
"""
return (self.m1*self.m2)**(3./5.)/(self.m1+self.m2)**(1./5.) | python | {
"resource": ""
} |
q40156 | EccentricBinaries._g_func | train | def _g_func(self):
"""Eq. 20 in Peters and Mathews 1963.
"""
return (self.n**4./32.
* ((jv(self.n-2., self.n*self.e_vals)
- 2. * self.e_vals*jv(self.n-1., self.n*self.e_vals)
+ 2./self.n * jv(self.n, self.n*self.e_vals)
+ ... | python | {
"resource": ""
} |
q40157 | EccentricBinaries._hcn_func | train | def _hcn_func(self):
"""Eq. 56 from Barack and Cutler 2004
"""
self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr())
return | python | {
"resource": ""
} |
q40158 | _create_oracle | train | def _create_oracle(oracle_type, **kwargs):
"""A routine for creating a factor oracle."""
if oracle_type == 'f':
return FO(**kwargs)
elif oracle_type == 'a':
return MO(**kwargs)
else:
return MO(**kwargs) | python | {
"resource": ""
} |
q40159 | FactorOracle.segment | train | def segment(self):
"""An non-overlap version Compror"""
if not self.seg:
j = 0
else:
j = self.seg[-1][1]
last_len = self.seg[-1][0]
if last_len + j > self.n_states:
return
i = j
while j < self.n_states - 1:
... | python | {
"resource": ""
} |
q40160 | Cycle.set_aromatic | train | def set_aromatic(self):
"""set the cycle to be an aromatic ring"""
#XXX FIX ME
# this probably shouldn't be here
for atom in self.atoms:
atom.aromatic = 1
for bond in self.bonds:
bond.aromatic = 1
bond.bondorder = 1.5
b... | python | {
"resource": ""
} |
q40161 | set_debug | train | def set_debug(enabled: bool):
"""Enable or disable debug logs for the entire package.
Parameters
----------
enabled: bool
Whether debug should be enabled or not.
"""
global _DEBUG_ENABLED
if not enabled:
log('Disabling debug output...', logger_name=_LOGGER_NAME)
_D... | python | {
"resource": ""
} |
q40162 | log | train | def log(message: str, *args: str, category: str='info', logger_name: str='pgevents'):
"""Log a message to the given logger.
If debug has not been enabled, this method will not log a message.
Parameters
----------
message: str
Message, with or without formatters, to print.
args: Any
... | python | {
"resource": ""
} |
q40163 | toposort | train | def toposort(initialAtoms, initialBonds):
"""initialAtoms, initialBonds -> atoms, bonds
Given the list of atoms and bonds in a ring
return the topologically sorted atoms and bonds.
That is each atom is connected to the following atom
and each bond is connected to the following bond in
the follow... | python | {
"resource": ""
} |
q40164 | checkEdges | train | def checkEdges(ringSet, lookup, oatoms):
"""atoms, lookup -> ring
atoms must be in the order of traversal around a ring!
break an optimal non N2 node and return the largest ring
found
"""
bondedAtoms = map( None, ringSet[:-1], ringSet[1:] )
bondedAtoms += [ (ringSet[-1], ringSet[0]) ]
#... | python | {
"resource": ""
} |
q40165 | diffPrefsPrior | train | def diffPrefsPrior(priorstring):
"""Parses `priorstring` and returns `prior` tuple."""
assert isinstance(priorstring, str)
prior = priorstring.split(',')
if len(prior) == 3 and prior[0] == 'invquadratic':
[c1, c2] = [float(x) for x in prior[1 : ]]
assert c1 > 0 and c2 > 0, "C1 and C2 mus... | python | {
"resource": ""
} |
q40166 | ExistingFileOrNone | train | def ExistingFileOrNone(fname):
"""Like `Existingfile`, but if `fname` is string "None" then return `None`."""
if os.path.isfile(fname):
return fname
elif fname.lower() == 'none':
return None
else:
raise ValueError("%s must specify a valid file name or 'None'" % fname) | python | {
"resource": ""
} |
q40167 | PhyDMSLogoPlotParser | train | def PhyDMSLogoPlotParser():
"""Returns `argparse.ArgumentParser` for ``phydms_logoplot``."""
parser = ArgumentParserNoArgHelp(description=
"Make logo plot of preferences or differential preferences. "
"Uses weblogo (http://weblogo.threeplusone.com/). "
"{0} Version {1}. Full ... | python | {
"resource": ""
} |
q40168 | ArgumentParserNoArgHelp.error | train | def error(self, message):
"""Prints error message, then help."""
sys.stderr.write('error: %s\n\n' % message)
self.print_help()
sys.exit(2) | python | {
"resource": ""
} |
q40169 | Graph.add_edges | train | def add_edges(self, from_idx, to_idx, weight=1, symmetric=False, copy=False):
'''Adds all from->to edges. weight may be a scalar or 1d array.
If symmetric=True, also adds to->from edges with the same weights.'''
raise NotImplementedError() | python | {
"resource": ""
} |
q40170 | Graph.add_self_edges | train | def add_self_edges(self, weight=None, copy=False):
'''Adds all i->i edges. weight may be a scalar or 1d array.'''
ii = np.arange(self.num_vertices())
return self.add_edges(ii, ii, weight=weight, symmetric=False, copy=copy) | python | {
"resource": ""
} |
q40171 | Graph.reweight | train | def reweight(self, weight, edges=None, copy=False):
'''Replaces existing edge weights. weight may be a scalar or 1d array.
edges is a mask or index array that specifies a subset of edges to modify'''
if not self.is_weighted():
warnings.warn('Cannot supply weights for unweighted graph; '
... | python | {
"resource": ""
} |
q40172 | Graph.to_igraph | train | def to_igraph(self, weighted=None):
'''Converts this Graph object to an igraph-compatible object.
Requires the python-igraph library.'''
# Import here to avoid ImportErrors when igraph isn't available.
import igraph
ig = igraph.Graph(n=self.num_vertices(), edges=self.pairs().tolist(),
... | python | {
"resource": ""
} |
q40173 | Graph.to_graph_tool | train | def to_graph_tool(self):
'''Converts this Graph object to a graph_tool-compatible object.
Requires the graph_tool library.
Note that the internal ordering of graph_tool seems to be column-major.'''
# Import here to avoid ImportErrors when graph_tool isn't available.
import graph_tool
gt = graph_... | python | {
"resource": ""
} |
q40174 | Graph.to_networkx | train | def to_networkx(self, directed=None):
'''Converts this Graph object to a networkx-compatible object.
Requires the networkx library.'''
import networkx as nx
directed = directed if directed is not None else self.is_directed()
cls = nx.DiGraph if directed else nx.Graph
adj = self.matrix()
if s... | python | {
"resource": ""
} |
q40175 | _check_inputs | train | def _check_inputs(z, m):
"""Check inputs are arrays of same length or array and a scalar."""
try:
nz = len(z)
z = np.array(z)
except TypeError:
z = np.array([z])
nz = len(z)
try:
nm = len(m)
m = np.array(m)
except TypeError:
m = np.array([m])
... | python | {
"resource": ""
} |
q40176 | Label._set_label | train | def _set_label(self, which, label, **kwargs):
"""Private method for setting labels.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `xlabel`/`ylabel`,
and `title`.
label (str): The label to be added.
... | python | {
"resource": ""
} |
q40177 | Limits._set_axis_limits | train | def _set_axis_limits(self, which, lims, d, scale, reverse=False):
"""Private method for setting axis limits.
Sets the axis limits on each axis for an individual plot.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `x` a... | python | {
"resource": ""
} |
q40178 | Limits.set_xlim | train | def set_xlim(self, xlims, dx, xscale, reverse=False):
"""Set x limits for plot.
This will set the limits for the x axis
for the specific plot.
Args:
xlims (len-2 list of floats): The limits for the axis.
dx (float): Amount to increment by between the limits.
... | python | {
"resource": ""
} |
q40179 | Limits.set_ylim | train | def set_ylim(self, xlims, dx, xscale, reverse=False):
"""Set y limits for plot.
This will set the limits for the y axis
for the specific plot.
Args:
ylims (len-2 list of floats): The limits for the axis.
dy (float): Amount to increment by between the limits.
... | python | {
"resource": ""
} |
q40180 | Legend.add_legend | train | def add_legend(self, labels=None, **kwargs):
"""Specify legend for a plot.
Adds labels and basic legend specifications for specific plot.
For the optional Args, refer to
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
for more information.
# TODO: Add ... | python | {
"resource": ""
} |
q40181 | DataImport.add_dataset | train | def add_dataset(self, name=None, label=None,
x_column_label=None, y_column_label=None, index=None, control=False):
"""Add a dataset to a specific plot.
This method adds a dataset to a plot. Its functional use is imperative
to the plot generation. It handles adding new files ... | python | {
"resource": ""
} |
q40182 | Figure.savefig | train | def savefig(self, output_path, **kwargs):
"""Save figure during generation.
This method is used to save a completed figure during the main function run.
It represents a call to ``matplotlib.pyplot.fig.savefig``.
# TODO: Switch to kwargs for matplotlib.pyplot.savefig
Args:
... | python | {
"resource": ""
} |
q40183 | Figure.set_fig_size | train | def set_fig_size(self, width, height=None):
"""Set the figure size in inches.
Sets the figure size with a call to fig.set_size_inches.
Default in code is 8 inches for each.
Args:
width (float): Dimensions for figure width in inches.
height (float, optional): Dim... | python | {
"resource": ""
} |
q40184 | Figure.set_spacing | train | def set_spacing(self, space):
"""Set the figure spacing.
Sets whether in general there is space between subplots.
If all axes are shared, this can be `tight`. Default in code is `wide`.
The main difference is the tick labels extend to the ends if space==`wide`.
If space==`tight... | python | {
"resource": ""
} |
q40185 | Figure.subplots_adjust | train | def subplots_adjust(self, **kwargs):
"""Adjust subplot spacing and dimensions.
Adjust bottom, top, right, left, width in between plots, and height in between plots
with a call to ``plt.subplots_adjust``.
See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
... | python | {
"resource": ""
} |
q40186 | Figure.set_fig_x_label | train | def set_fig_x_label(self, xlabel, **kwargs):
"""Set overall figure x.
Set label for x axis on overall figure. This is not for a specific plot.
It will place the label on the figure at the left with a call to ``fig.text``.
Args:
xlabel (str): xlabel for entire figure.
... | python | {
"resource": ""
} |
q40187 | Figure.set_fig_y_label | train | def set_fig_y_label(self, ylabel, **kwargs):
"""Set overall figure y.
Set label for y axis on overall figure. This is not for a specific plot.
It will place the label on the figure at the left with a call to ``fig.text``.
Args:
ylabel (str): ylabel for entire figure.
... | python | {
"resource": ""
} |
q40188 | Figure.set_fig_title | train | def set_fig_title(self, title, **kwargs):
"""Set overall figure title.
Set title for overall figure. This is not for a specific plot.
It will place the title at the top of the figure with a call to ``fig.suptitle``.
Args:
title (str): Figure title.
Keywork Argument... | python | {
"resource": ""
} |
q40189 | Figure.set_colorbar | train | def set_colorbar(self, plot_type, **kwargs):
"""Setup colorbar for specific type of plot.
Specify a plot type to customize its corresponding colorbar in the figure.
See the ColorbarContainer class attributes for more specific explanations.
Args:
plot_type (str): Type of pl... | python | {
"resource": ""
} |
q40190 | General.set_all_file_column_labels | train | def set_all_file_column_labels(self, xlabel=None, ylabel=None):
"""Indicate general x,y column labels.
This sets the general x and y column labels into data files for all plots.
It can be overridden for specific plots.
Args:
xlabel/ylabel (str, optional): String indicating ... | python | {
"resource": ""
} |
q40191 | General._set_all_lims | train | def _set_all_lims(self, which, lim, d, scale, fontsize=None):
"""Set limits and ticks for an axis for whole figure.
This will set axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.
Args:
which (str): The indicator of which part o... | python | {
"resource": ""
} |
q40192 | General.set_all_xlims | train | def set_all_xlims(self, xlim, dx, xscale, fontsize=None):
"""Set limits and ticks for x axis for whole figure.
This will set x axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.
Args:
xlim (len-2 list of floats): The limits for t... | python | {
"resource": ""
} |
q40193 | General.set_all_ylims | train | def set_all_ylims(self, ylim, dy, yscale, fontsize=None):
"""Set limits and ticks for y axis for whole figure.
This will set y axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.
Args:
ylim (len-2 list of floats): The limits for t... | python | {
"resource": ""
} |
q40194 | General.reverse_axis | train | def reverse_axis(self, axis_to_reverse):
"""Reverse an axis in all figure plots.
This will reverse the tick marks on an axis for each plot in the figure.
It can be overridden in SinglePlot class.
Args:
axis_to_reverse (str): Axis to reverse. Supports `x` and `y`.
R... | python | {
"resource": ""
} |
q40195 | MainContainer.return_dict | train | def return_dict(self):
"""Output dictionary for ``make_plot.py`` input.
Iterates through the entire MainContainer class turning its contents
into dictionary form. This dictionary becomes the input for ``make_plot.py``.
If `print_input` attribute is True, the entire dictionary will be p... | python | {
"resource": ""
} |
q40196 | MainContainer._iterate_through_class | train | def _iterate_through_class(self, class_dict):
"""Recursive function for output dictionary creation.
Function will check each value in a dictionary to see if it is a
class, list, or dictionary object. The idea is to turn all class objects into
dictionaries. If it is a class object it wil... | python | {
"resource": ""
} |
q40197 | ReadInData.txt_read_in | train | def txt_read_in(self):
"""Read in txt files.
Method for reading in text or csv files. This uses ascii class from astropy.io
for flexible input. It is slower than numpy, but has greater flexibility with less input.
"""
# read in
data = ascii.read(self.WORKING_DIRECTORY ... | python | {
"resource": ""
} |
q40198 | ReadInData.hdf5_read_in | train | def hdf5_read_in(self):
"""Method for reading in hdf5 files.
"""
with h5py.File(self.WORKING_DIRECTORY + '/' + self.file_name) as f:
# read in
data = f['data']
# find number of distinct x and y points.
num_x_pts = len(np.unique(data[self.x_colu... | python | {
"resource": ""
} |
q40199 | GenProcess.set_parameters | train | def set_parameters(self):
"""Setup all the parameters for the binaries to be evaluated.
Grid values and store necessary parameters for input into the SNR function.
"""
# declare 1D arrays of both paramters
if self.xscale != 'lin':
self.xvals = np.logspace(np.log10(... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.