Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,800 | def generate_orchestration_playbook(self, url=None, namespace=None, vault_files=None, **kwargs):
states = [, , , ]
service_def = {}
for service_name, service in iteritems(self.services):
service_definition = {}
if service.get():
if url and namespa... | Generate an Ansible playbook to orchestrate services.
:param url: registry URL where images will be pulled from
:param namespace: registry namespace
:return: playbook dict |
344,801 | def _gt_from_ge(self, other):
op_result = self.__ge__(other)
if op_result is NotImplemented:
return NotImplemented
return op_result and self != other | Return a > b. Computed by @total_ordering from (a >= b) and (a != b). |
344,802 | def _maximization(X, posterior, force_weights=None):
n_examples, n_features = X.shape
n_clusters, n_examples = posterior.shape
concentrations = np.zeros((n_clusters,))
centers = np.zeros((n_clusters, n_features))
if force_weights is None:
weights = np.zeros((n_clusters,))
for cc in... | Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is passed, will estimate weights.
If an array is passed, ... |
344,803 | def is_number_match(num1, num2):
if isinstance(num1, PhoneNumber) and isinstance(num2, PhoneNumber):
return _is_number_match_OO(num1, num2)
elif isinstance(num1, PhoneNumber):
return _is_number_match_OS(num1, num2)
elif isinstance(num2, PhoneNumber):
return _is_number_match_OS(n... | Takes two phone numbers and compares them for equality.
For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
Arguments
num1 -- First number object or string to compare. Can contain formatting,
and can have co... |
344,804 | def format_entry(record, show_level=False, colorize=False):
if show_level:
log_str = u.format(record.levelname, record.getMessage())
else:
log_str = record.getMessage()
if colorize and record.levelname in LOG_COLORS:
log_str = u.format(LOG_COLORS[record.levelname]) + log_str + ... | Format a log entry according to its level and context |
344,805 | def unauthorized_view(self):
url = request.script_root + request.path
flash(_("You do not have permission to access .", url=url), )
return redirect(self._endpoint_url(self.USER_UNAUTHORIZED_ENDPOINT)) | Prepare a Flash message and redirect to USER_UNAUTHORIZED_ENDPOINT |
344,806 | def simxGetCollectionHandle(clientID, collectionName, operationMode):
handle = ct.c_int()
if (sys.version_info[0] == 3) and (type(collectionName) is str):
collectionName=collectionName.encode()
return c_GetCollectionHandle(clientID, collectionName, ct.byref(handle), operationMode), handle.valu... | Please have a look at the function description/documentation in the V-REP user manual |
344,807 | def main_loop_iteration(timeout=None):
prev_nr_read = nr_handle_read
asyncore.loop(count=1, timeout=timeout, use_poll=True)
return nr_handle_read - prev_nr_read | Return the number of RemoteDispatcher.handle_read() calls made by this
iteration |
344,808 | def schedule(dev):
for d in range(7):
dev.query_schedule(d)
for day in dev.schedule.values():
click.echo("Day %s, base temp: %s" % (day.day, day.base_temp))
current_hour = day.next_change_at
for hour in day.hours:
if current_hour == 0: continue
c... | Gets the schedule from the thermostat. |
344,809 | def setup_asset_page(self, ):
self.asset_asset_treev.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
self.asset_task_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) | Create and set the model on the asset page
:returns: None
:rtype: None
:raises: None |
344,810 | def _RunScript(self, script):
process = subprocess.Popen(
script, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
while True:
for line in iter(process.stdout.readline, b):
self.logger.info(line.decode().rstrip())
if process.poll() is not None:
break | Run a script and log the streamed script output.
Args:
script: string, the file location of an executable script. |
344,811 | def raster_dilation(rasterfile):
if is_string(rasterfile):
origin_raster = RasterUtilClass.read_raster(str(rasterfile))
elif isinstance(rasterfile, Raster):
origin_raster = rasterfile.data
elif isinstance(rasterfile, numpy.ndarray):
origin_raster = ra... | Dilate the raster image.
Find the max pixel's value in 8-neighborhood. Then change the compute
pixel's value into the max pixel's value.
Args:
rasterfile: input original raster image, type can be filename(string,
like "test1.tif"), rasterfile(class Raster) or numpy.nd... |
344,812 | def register_class(klass, alias=None):
meta = util.get_class_meta(klass)
if alias is not None:
meta[] = alias
alias_klass = util.get_class_alias(klass) or ClassAlias
x = alias_klass(klass, defer=True, **meta)
if not x.anonymous:
CLASS_CACHE[x.alias] = x
CLASS_CACHE[klas... | Registers a class to be used in the data streaming. This is the equivalent
to the C{[RemoteClass(alias="foobar")]} AS3 metatag.
@return: The registered L{ClassAlias} instance.
@see: L{unregister_class} |
344,813 | def decimate_smooth(self, a, maxpoints, window="flat"):
ny = a.shape[-1]
stepsize = int(ny / maxpoints)
if stepsize % 2 == 0:
stepsize += 1
out = numpy.empty_like(a)
out[0,:] = a[0]
for i in range(1, ... | Return smoothed data *a* decimated on approximately *maxpoints* points.
1. Produces a smoothed graph using the smoothing window *window*;
"flat" is a running average.
2. select points at a step size approximatelt producing maxpoints
If *a* contains <= *maxpoints* then *a* is simply ... |
344,814 | def invoke(self, ctx):
ctx.obj = GandiContextHelper(verbose=ctx.obj[])
click.Group.invoke(self, ctx) | Invoke command in context. |
344,815 | def genstis(outname):
pattern=
speclist=[,
,
]
glist={:,:,:,:,
:}
out=open(outname,)
out.write()
count=0
for g in glist:
for sp in speclist:
obsmode=%g
defn=pattern%(count,obsmode,sp)
out.write(defn)
... | Generate TestCases from cmdfile according to the pattern in patternfile |
344,816 | def neural_computation(original_func, prefer_tensor=False):
def wrapper(*args, **kwargs):
normal_args, tensor_found_in_args, neural_found_in_args = convert_to_theano_var(args)
normal_kwargs, tensor_found_in_kwargs, neural_found_in_kwargs = convert_to_theano_var(kwargs)
tensor_found = ... | An annotation to enable theano-based fucntions to be called with NeuralVar.
:param original_func:
:param prefer_tensor: a switch to return tensors when no inputs
:return: |
344,817 | def normal_name(
self,
rm_namespaces=(,),
capital_links=False,
_code: str = None,
*,
code: str = None,
capitalize=False
) -> str:
if capital_links:
warn(
, DeprecationWarning)
capitalize = capital_links... | Return normal form of self.name.
- Remove comments.
- Remove language code.
- Remove namespace ("template:" or any of `localized_namespaces`.
- Use space instead of underscore.
- Remove consecutive spaces.
- Use uppercase for the first letter if `capitalize`.
- R... |
344,818 | def render_alert(content, alert_type=None, dismissable=True):
button = ""
if not alert_type:
alert_type = "info"
css_classes = ["alert", "alert-" + text_value(alert_type)]
if dismissable:
css_classes.append("alert-dismissable")
button = (
+
... | Render a Bootstrap alert |
344,819 | def _renamer(self, tre):
names = tre.get_leaves()
for name in names:
name.name = self.samples[int(name.name)]
return tre.write(format=9) | renames newick from numbers to sample names |
344,820 | def _handle_zeros_in_scale(scale, copy=True):
if numpy.isscalar(scale):
if scale == .0:
scale = 1.
return scale
elif isinstance(scale, numpy.ndarray):
if copy:
scale = scale.copy()
scale[scale == 0.0] = 1.0
return scale | Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features. |
344,821 | def _notify_create_process(self, event):
bCallHandler = _ThreadContainer._notify_create_process(self, event)
bCallHandler = bCallHandler and \
_ModuleContainer._notify_create_process(self, event)
return bCallHandler | Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{Fal... |
344,822 | def get_all_subs_satellites_by_type(self, sat_type, realms):
res = copy.copy(getattr(self, sat_type))
for member in self.all_sub_members:
res.extend(realms[member].get_all_subs_satellites_by_type(sat_type, realms))
return res | Get all satellites of the wanted type in this realm recursively
:param sat_type: satellite type wanted (scheduler, poller ..)
:type sat_type:
:param realms: all realms
:type realms: list of realm object
:return: list of satellite in this realm
:rtype: list |
344,823 | def _docspec(func, module=None, qualname=None, of_class=None):
sp = _argspec(func)
doc = _doc_parse(getdoc(func), module=module, qualname=qualname)
doc_map = {a.name: a for a in doc.args}
doc.args = [data.Argument(a, doc_map.get(a.name.lstrip(), None)) for a in sp]
if (six.PY2 and i... | For a callable, get the full spec by merging doc_parse() and argspec()
:type func: Callable
:rtype: data.FDocstring |
344,824 | def resolve_neutral_types(storage, debug):
for run in storage[]:
start, length = run[], run[]
chars = [{: run[]}] + storage[][start:start+length] +\
[{: run[]}]
total_chars = len(chars)
seq_start = None
for idx in range(total_chars):
... | Resolving neutral types. Implements N1 and N2
See: http://unicode.org/reports/tr9/#Resolving_Neutral_Types |
344,825 | def from_config(cls, config, weights=None, weights_loader=None):
config = dict(config)
instance = cls(**config.pop())
instance.__dict__.update(config)
instance.network_weights = weights
instance.network_weights_loader = weights_loader
instance.prediction_cache = ... | deserialize from a dict returned by get_config().
Parameters
----------
config : dict
weights : list of array, optional
Network weights to restore
weights_loader : callable, optional
Function to call (no arguments) to load weights when needed
... |
344,826 | def start(self):
LOG.info()
with indicator.Spinner(run=self.run_indicator):
cdn_item = self._cdn()
self.print_virt_table(cdn_item.headers) | Return a list of objects from the API for a container. |
344,827 | def xgb_progressbar(rounds=1000):
pbar = tqdm(total=rounds)
def callback(_, ):
pbar.update(1)
return callback | Progressbar for xgboost using tqdm library.
Examples
--------
>>> model = xgb.train(params, X_train, 1000, callbacks=[xgb_progress(1000), ]) |
344,828 | def interpolate_grid(self, in_lon, in_lat):
out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1]))
for d in range(self.data.shape[0]):
print("Loading ", d, self.variable, self.start_date)
if self.data[d].max() > -999:
step = self.data... | Interpolates MRMS data to a different grid using cubic bivariate splines |
344,829 | def _drop_gracefully(self):
mr_id = self.request.get("mapreduce_id")
logging.error("Failed to kick off job %s", mr_id)
state = model.MapreduceState.get_by_job_id(mr_id)
if not self._check_mr_state(state, mr_id):
return
config = util.create_datastore_write_config(state.mapreduce_spe... | See parent. |
344,830 | def readTableFromCSV(f, dialect="excel"):
rowNames = []
columnNames = []
matrix = []
first = True
for row in csv.reader(f, dialect):
if first:
columnNames = row[1:]
first = False
else:
rowNames.append(row[0])
matrix.append([float(... | Reads a table object from given CSV file. |
344,831 | def options(self):
try:
return dict(self.cfg.items("twtxt"))
except configparser.NoSectionError as e:
logger.debug(e)
return {} | A :class:`dict` of all config options. |
344,832 | def as_opcode(cls: Type[T],
logic_fn: Callable[..., Any],
mnemonic: str,
gas_cost: int) -> Type[T]:
if gas_cost:
@functools.wraps(logic_fn)
def wrapped_logic_fn(computation: ) -> Any:
computat... | Class factory method for turning vanilla functions into Opcode classes. |
344,833 | def _readline_echo(self, char, echo):
if self._readline_do_echo(echo):
self.write(char) | Echo a recieved character, move cursor etc... |
344,834 | def uncompress_file(inputfile, filename):
zipfile = gzip.GzipFile(fileobj=inputfile, mode="rb")
try:
outputfile = create_spooled_temporary_file(fileobj=zipfile)
finally:
zipfile.close()
new_basename = os.path.basename(filename).replace(, )
return outputfile, new_basename | Uncompress this file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new file's name
:rtype: :class:`tempfile.SpooledTemporaryFile`, ``str`` |
344,835 | def cast(cls, datasets, datatype=None, cast_type=None):
datatype = datatype or cls.datatype
cast = []
for ds in datasets:
if cast_type is not None or ds.interface.datatype != datatype:
ds = ds.clone(ds, datatype=[datatype], new_type=cast_type)
cas... | Given a list of Dataset objects, cast them to the specified
datatype (by default the format matching the current interface)
with the given cast_type (if specified). |
344,836 | def markdown_to_text(body):
md = markdown.markdown(body, extensions=[
])
return soup.get_text() | Converts markdown to text.
Args:
body: markdown (or plaintext, or maybe HTML) input
Returns:
Plaintext with all tags and frills removed |
344,837 | def parse(self, stream, media_type=None, parser_context=None):
parser_context = parser_context or {}
request = parser_context[]
encoding = parser_context.get(, settings.DEFAULT_CHARSET)
meta = request.META.copy()
meta[] = media_type
upload_handlers = request.uplo... | Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the form files. |
344,838 | def solve(self, b):
y = []
for bri in range(self.N):
for li in range(self.n):
s = 0.0
for lci in range(li):
s += self.lu[bri][li, lci]*y[bri*self.n+lci]
for di in range(1, self.ndiag+1):
... | LUx = b:
Ly = b
Ux = y |
344,839 | def saveVirtualOutputs(self,outdict):
if not self.inmemory:
return
for outname in outdict:
self.virtualOutputs[outname] = outdict[outname] | Assign in-memory versions of generated products for this
``imageObject`` based on dictionary 'outdict'. |
344,840 | def ngayThangNamCanChi(nn, tt, nnnn, duongLich=True, timeZone=7):
if duongLich is True:
[nn, tt, nnnn, thangNhuan] = \
ngayThangNam(nn, tt, nnnn, timeZone=timeZone)
canThang = (nnnn * 12 + tt + 3) % 10 + 1
canNamSinh = (nnnn + 6) % 10 + 1
chiNam = (nnnn + 8) % 12 + 1
... | chuyển đổi năm, tháng âm/dương lịch sang Can, Chi trong tiếng Việt.
Không tính đến can ngày vì phải chuyển đổi qua lịch Julius.
Hàm tìm can ngày là hàm canChiNgay(nn, tt, nnnn, duongLich=True,\
timeZone=7, thangNhuan=False)
Args:
nn (int): Ngày
tt (int):... |
344,841 | def __chunk(segment, abbr=False):
names = (, , , , )
if not abbr:
sjoin =
else:
names = [s[0].upper() for s in names]
sjoin =
if segment % 2 == 0:
return (names[segment].capitalize(),
sjoin.join((names[segment].capitalize(), names[segment],
... | Generate a ``tuple`` of compass direction names.
Args:
segment (list): Compass segment to generate names for
abbr (bool): Names should use single letter abbreviations
Returns:
bool: Direction names for compass segment |
344,842 | def getColor(name):
try:
c = getColorInfoList()[getColorList().index(name.upper())]
return (c[1] / 255., c[2] / 255., c[3] / 255.)
except:
return (1, 1, 1) | Retrieve RGB color in PDF format by name.
Returns:
a triple of floats in range 0 to 1. In case of name-not-found, "white" is returned. |
344,843 | def user_data(user):
_range = _group_range(user.records, )
export = OrderedDict([
(, ),
(, [x.strftime() for x in _range]),
(, ),
(, OrderedDict()),
(, OrderedDict())
])
class Indicator(object):
def __init__(self, name, function, interactio... | Compute indicators and statistics used by the visualization
and returns a dictionnary. |
344,844 | def extract_src_loss_table(dstore, loss_type):
oq = dstore[]
li = oq.lti[loss_type]
source_ids = dstore[][]
idxs = dstore[].value[[, ]]
losses = dstore[][:, li]
slt = numpy.zeros(len(source_ids), [(, U32), (loss_type, F32)])
for loss, (srcidx, grp_id) in zip(losses, idxs):
slt[s... | Extract the source loss table for a give loss type, ordered in decreasing
order. Example:
http://127.0.0.1:8800/v1/calc/30/extract/src_loss_table/structural |
344,845 | def filename(self, filename=None):
if filename is None:
if self.debugger.mainpyfile:
filename = self.debugger.mainpyfile
else:
return None
if self.debugger.settings[]:
return(os.path.basename(filename))
return filename | Return filename or the basename of that depending on the
basename setting |
344,846 | def requeue_delayed_jobs(self):
lock_key = self.make_key(
self._name,
self.pk.get(),
"requeue_all_delayed_ready_jobs",
)
connection = self.get_connection()
if connection.exists(lock_key):
return failures | Put all delayed jobs that are now ready, back in the queue waiting list
Return a list of failures |
344,847 | def inc(self, exception=None):
try:
self._idx, self._current = next(self._chars)
return True
except StopIteration:
self._idx = len(self)
self._current = self.EOF
if exception:
raise self.parse_error(exception)
... | Increments the parser if the end of the input has not been reached.
Returns whether or not it was able to advance. |
344,848 | def _infer_interval_breaks(coord, kind=None):
if coord.ndim == 1:
return _infer_interval_breaks(coord)
elif coord.ndim == 2:
from scipy.interpolate import interp2d
kind = kind or rcParams[]
y, x = map(np.arange, coord.shape)
new_x, new... | Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids |
344,849 | def predict(self, u=None, B=None, F=None, Q=None):
if B is None:
B = self.B
if F is None:
F = self.F
if Q is None:
Q = self.Q
elif isscalar(Q):
Q = eye(self.dim_x) * Q
if B is not None and u is not None:
... | Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array
Optional control vector. If not `None`, it is multiplied by B
to create the control input into the system.
B : np.array(dim_x, dim_z), or ... |
344,850 | def sentiment(text):
sentiment.valence_dict = load_valence_dict() if sentiment.valence_dict is None else sentiment_valence_dict
wordsAndEmoticons = str(text).split()
"!!", "!!!", "??", "???", "?!?", "!?!", "?!?!", "!?!?"]
for word in wordsOnly:
for p in puncList:
... | Returns a float for sentiment strength based on the input text.
Positive values are positive valence, negative value are negative valence. |
344,851 | def update(self, configuration=values.unset, unique_name=values.unset):
data = values.of({: serialize.object(configuration), : unique_name, })
payload = self._version.update(
,
self._uri,
data=data,
)
return InstalledAddOnInstance(self._vers... | Update the InstalledAddOnInstance
:param dict configuration: The JSON object representing the configuration
:param unicode unique_name: The string that uniquely identifies this Add-on installation
:returns: Updated InstalledAddOnInstance
:rtype: twilio.rest.preview.marketplace.installe... |
344,852 | def get_small_file(context, path):
pool = mitogen.service.get_or_create_pool(router=context.router)
service = pool.get_service(u)
return service.get(path) | Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just the top-level Mitogen connection manager proce... |
344,853 | def to_string(self):
if self._string is None:
tokens = []
if self.name:
if self.scale:
token = self.name + + str(self.scale)
else:
token = self.name
else:
token =
... | Export this namespace to a string suitable for incorporation
in a VW example line, e.g.
'MetricFeatures:3.28 height:1.5 length:2.0 ' |
344,854 | def batches(arrays, steps=100, batch_size=64, rng=None):
assert batch_size >= 2,
assert isinstance(arrays, (tuple, list)),
if rng is None or isinstance(rng, int):
rng = np.random.RandomState(rng)
def sample():
xs = [np.zeros((batch_size, steps, a.shape[1]), a.dtype) for a in arr... | Create a callable that generates samples from a dataset.
Parameters
----------
arrays : list of ndarray (time-steps, data-dimensions)
Arrays of data. Rows in these arrays are assumed to correspond to time
steps, and columns to variables. Multiple arrays can be given; in such
a case,... |
344,855 | def wait(self, timeout=-1):
start = time.time()
if self._ready:
return
local_ids = filter(lambda msg_id: msg_id in self._client.outstanding, self.msg_ids)
local_ready = self._client.wait(local_ids, timeout)
if local_ready:
remote_ids = filter(lamb... | wait for result to complete. |
344,856 | def on_service_departure(self, svc_ref):
with self._lock:
try:
service = self.services.pop(svc_ref)
except KeyError:
pass
else:
self._future_value.remove(service)
... | Called when a service has been unregistered from the framework
:param svc_ref: A service reference
:return: A tuple (service, reference) if the service has been lost,
else None |
344,857 | def bytes(self):
b = [bytes([self._opcode])]
for offset in reversed(range(self.operand_size)):
b.append(bytes([(self.operand >> offset * 8) & 0xff]))
return b.join(b) | Encoded instruction |
344,858 | def exists(self, path):
cmd = load_hadoop_cmd() + [, , path]
logger.debug(, subprocess.list2cmdline(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True)
stdout, stderr = p.communicate()
if p.returncode ... | Use ``hadoop fs -stat`` to check file existence. |
344,859 | def new_message(self):
draft_message = self.message_constructor(parent=self, is_draft=True)
if self.root:
draft_message.folder_id = OutlookWellKnowFolderNames.DRAFTS.value
else:
draft_message.folder_id = self.folder_id
return draft_message | Creates a new draft message under this folder
:return: new Message
:rtype: Message |
344,860 | def unpack_chunk(chunk_data: str) -> bytes:
if not chunk_data:
return b
chunk_compressed = binascii.a2b_base64(chunk_data.encode())
return zlib.decompress(chunk_compressed) | Unpacks a previously packed chunk data back into the original
bytes representation
:param chunk_data:
The compressed, base64 encoded string to convert back to the
source bytes object. |
344,861 | def _conn_ready(self, conn):
if ON_APP_ENGINE:
return (response is None) or response.isclosed() | There is a nice state diagram at the top of httplib.py. It
indicates that once the response headers have been read (which
_mexe does before adding the connection to the pool), a
response is attached to the connection, and it stays there
until it's done reading. This isn't entirely true... |
344,862 | def from_clause(cls, clause):
field = clause[0]
value1 = field_or_value(clause[1])
op = None
value2 = None
if len(clause) > 2:
op = clause[2]
value2 = field_or_value(clause[3])
return cls(field, value1, op, value2) | Factory method |
344,863 | def target_gene_indices(gene_names,
target_genes):
if isinstance(target_genes, list) and len(target_genes) == 0:
return []
if isinstance(target_genes, str) and target_genes.upper() == :
return list(range(len(gene_names)))
elif isinstance(target_genes, int):
... | :param gene_names: list of gene names.
:param target_genes: either int (the top n), 'all', or a collection (subset of gene_names).
:return: the (column) indices of the target genes in the expression_matrix. |
344,864 | def get_random_choral(log=True):
choral_file = corpus.getBachChorales()[random.randint(0, 399)]
choral = corpus.parse(choral_file)
if log:
print("Chosen choral:", choral.metadata.title)
return choral | Gets a choral from the J. S. Bach chorals corpus (in Music21). |
344,865 | def textBlocks(self):
myBlocks = self.blocks
return [block for block in myBlocks if not issubclass(block.__class__, AdvancedTag)] | textBlocks - Property.
Returns all the blocks which are direct children of this node, where that block is a text (not a tag)
@return list<AdvancedTag> - A list of direct children which are text. |
344,866 | def _read_interleaved(self, f, data_objects):
log.debug("Reading interleaved data point by point")
object_data = {}
points_added = {}
for obj in data_objects:
object_data[obj.path] = obj._new_segment_data()
points_added[obj.path] = 0
while any([p... | Read interleaved data that doesn't have a numpy type |
344,867 | def post(self, endpoint=, url=, data=None, use_api_key=False, omit_api_version=False):
return self._request(, endpoint, url, data=data, use_api_key=use_api_key, omit_api_version=omit_api_version) | Perform a post to an API endpoint.
:param string endpoint: Target endpoint. (Optional).
:param string url: Override the endpoint and provide the full url (eg for pagination). (Optional).
:param dict data: Data to pass to the post. (Optional).
:return: Response.
:rtype: ``Respons... |
344,868 | def make_processitem_path(path, condition=, negate=False, preserve_case=False):
document =
search =
content_type =
content = path
ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content,
negate=negate, preserv... | Create a node for ProcessItem/path
:return: A IndicatorItem represented as an Element node |
344,869 | def unregister_all(self):
aliases = list(self._service_objects.keys())
for alias in aliases:
self.unregister(alias) | Safely unregisters all active instances.
Errors occurred here will be recorded but not raised. |
344,870 | def default_links_factory(pid, record=None, **kwargs):
endpoint = .format(
current_records_rest.default_endpoint_prefixes[pid.pid_type])
links = dict(self=url_for(endpoint, pid_value=pid.pid_value,
_external=True))
return links | Factory for record links generation.
:param pid: A Persistent Identifier instance.
:returns: Dictionary containing a list of useful links for the record. |
344,871 | def prime_event(event, source, **kwargs):
if not isinstance(event, Event):
event = Event(event, source=source, **kwargs)
return event | Returns the event ready to be triggered.
If the given event is a string an Event instance is generated from it. |
344,872 | def guess_package_path(searchfrom):
from snipy.io import fileutil
current = searchfrom +
init_found = False
pack_found = False
while not init_found and current != :
current = os.path.dirname(current)
initfile = os.path.join(current, )
init_found = os.path.exists(initfi... | package path. return None if failed to guess |
344,873 | def start_agent(self, cfgin=True):
default_conf = {
"threads": {
"result": {
"number": 0,
"function": None
},
"worker": {
"number": 0,
"function": None
... | CLI interface to start 12-factor service |
344,874 | def _parse_seqs(self, LOS):
self.nseqs = len(LOS)
self.width = len(LOS[0])
for i in range(self.width):
Dc = {: 0, : 0, : 0, : 0, : 0}
for seq in LOS:
key = seq[i]
Dc[key] = Dc[key] + 1
del(Dc[])
self.counts.... | m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences |
344,875 | def validate(data, schema, defined_keys=False):
if isinstance(data, dict):
validator = Validator(data, schema, defined_keys=defined_keys)
validator.validate()
else:
raise TypeError( % type(data)) | Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against |
344,876 | def get_provider(self, provider):
if self.provider is not None:
return self.provider
return providers.by_id(provider) | Get instance of the OAuth client for this provider. |
344,877 | def on_press(self, event):
if event.inaxes != self.ax:
return
self.press = [event.xdata], [event.ydata], event.button | on but-ton press we will see if the mouse is over us and store data |
344,878 | def get_submissions_by_course_and_assignment(
self, course_id, assignment_id, params={}):
url = COURSES_API.format(course_id)
url += "/assignments/{}/submissions".format(assignment_id)
submissions = []
for data in self._get_paged_resource(url, params=params):
... | https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.index |
344,879 | def return_feature_list_base(dbpath, set_object):
engine = create_engine( + dbpath)
session_cl = sessionmaker(bind=engine)
session = session_cl()
return_list = []
tmp_object = session.query(set_object).get(1)
for feature in tmp_object.features:
return_list.append(feature)
sessio... | Generic function which returns a list of the names of all available features
Parameters
----------
dbpath : string, path to SQLite database file
set_object : object (either TestSet or TrainSet) which is stored in the database
Returns
-------
return_list : list of strings corresponding to a... |
344,880 | def _spoken_representation_L1(lst_lst_char):
s =
inter_char =
inter_word = inter_char * 9
for i, word in enumerate(lst_lst_char):
if i >= 1:
s += inter_word
for j, c in enumerate(word):
if j != 0:
s += inter_char
s += _char_to_st... | >>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L1(lst)
'M O R S E C O D E'
>>> lst = [[], ['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L1(lst)
' M O R S E C O D E' |
344,881 | def logError(self):
import traceback
self.logMsg()
errMsg = traceback.format_exc()
self.logMsg(errMsg)
return errMsg | gets traceback info and logs it |
344,882 | def a_star_search(graph, start, goal):
all_nodes = graph.get_all_node_ids()
if start not in all_nodes:
raise NonexistentNodeError(start)
if goal not in all_nodes:
raise NonexistentNodeError(goal)
came_from, cost_so_far, goal_reached = _a_star_search_internal(graph, start, goal)
... | Runs an A* search on the specified graph to find a path from the ''start'' node to the ''goal'' node.
Returns a list of nodes specifying a minimal path between the two nodes.
If no path exists (disconnected components), returns an empty list. |
344,883 | def get_search_form(self):
if in self.request.GET:
return self.search_form_class(self.request.GET)
else:
return self.search_form_class(placeholder=_(u)) | Returns search form instance.
:rtype: django.forms.ModelForm. |
344,884 | def make_cubehelix(name="WrightTools", gamma=0.5, s=0.25, r=-1, h=1.3, reverse=False, darkest=0.7):
rr = .213 / .30
rg = .715 / .99
rb = .072 / .11
def get_color_function(p0, p1):
def color(x):
xg = darkest * x ** gamma
lum = 1 - xg
... | Define cubehelix type colorbars.
Look `here`__ for more information.
__ http://arxiv.org/abs/1108.5083
Parameters
----------
name : string (optional)
Name of new cmap. Default is WrightTools.
gamma : number (optional)
Intensity factor. Default is 0.5
s : number (optional)... |
344,885 | def reset(self):
self.data = []
self.size = 0
self.kdtree = None
self.nn_ready = False | Reset the dataset to zero elements. |
344,886 | def _make_individual(self, paramlist):
part = creator.Individual(paramlist)
part.ident = None
return part | Makes an individual particle. |
344,887 | def parse_url(arg, extract, key=None):
return ops.ParseURL(arg, extract, key).to_expr() | Returns the portion of a URL corresponding to a part specified
by 'extract'
Can optionally specify a key to retrieve an associated value
if extract parameter is 'QUERY'
Parameters
----------
extract : one of {'PROTOCOL', 'HOST', 'PATH', 'REF',
'AUTHORITY', 'FILE', 'USERINFO', 'Q... |
344,888 | def add_service(self, cls):
service_name = get_service_name(cls)
container = self.container_cls(cls, self.config)
self.service_map[service_name] = container | Add a service class to the runner.
There can only be one service class for a given service name.
Service classes must be registered before calling start() |
344,889 | def authenticate(self, email=None, password=None, source=None):
from gdata.service import BadAuthentication
Api.yt_service.email = email if email else settings.YOUTUBE_AUTH_EMAIL
Api.yt_service.password = password if password else settings.YOUTUBE_AUTH_PASSWORD
Api.yt_... | Authenticates the user and sets the GData Auth token.
All params are optional, if not set, we will use the ones on the settings, if no settings found, raises AttributeError
params are email, password and source. Source is the app id
Raises:
gdata.service.exceptions.BadAuthentication |
344,890 | def getHeader():
system, host, release, version, machine = os.uname()
return "
(__version__,
" ".join(sys.argv),
time.asctime(time.localtime(time.time())),
host,
global_id,
os.getpid(),
system, release, version, machine) | return a header string with command line options and timestamp |
344,891 | def fit(self):
self.n_samples, self.n_features = self.ms.shape
self.u, self.s, self.vt = np.linalg.svd(self.ms, full_matrices=False)
self.v = self.vt.T
self.u, self.vt = svd_flip(
self.u, self.v, u_based... | Fit the model by computing full SVD on m.
SVD factors the matrix m as u * np.diag(s) * v, where u and v are
unitary and s is a 1-d array of m‘s singular values. Note that the SVD
is commonly written as a = U S V.H, and the v returned by this function
is V.H (the Hermitian transpos... |
344,892 | def _get_name(self, val, src_file, default=):
t be found programmatically
return -- string -- the full.module.Name
{}.__module__.__name____class____name__', default)
full_name = "{}{}".format(module_name, class_name)
return full_name | get the full namespaced (module + class) name of the val object
since -- 6-28-12
val -- mixed -- the value (everything is an object) object
default -- string -- the default name if a decent name can't be found programmatically
return -- string -- the full.module.Name |
344,893 | def TextWidget(*args, **kw):
kw[] = str(kw[])
kw.pop(, None)
return TextInput(*args,**kw) | Forces a parameter value to be text |
344,894 | def state(self, initial=False, terminal=False,
serialized=None):
def decorator(stateMethod):
state = MethodicalState(machine=self,
method=stateMethod,
serialized=serialized)
if initial:
... | Declare a state, possibly an initial state or a terminal state.
This is a decorator for methods, but it will modify the method so as
not to be callable any more.
:param bool initial: is this state the initial state?
Only one state on this :class:`automat.MethodicalMachine`
... |
344,895 | def list_user_roles(*_, user_id):
click.echo(green())
click.echo(green( * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red())
return
for index,role in enumerate(user.roles):
click.echo(.format(... | List user roles |
344,896 | def findzc(x, thresh, t_max=None):
s Dtag toolbox method
and tested against the Matlab version to be sure it has the same result.
'
import numpy
pt_p = x > thresh
pt_n = ~pt_p
nt_n = x < -thresh
nt_p = ~nt_n
pt_np = (pt_p[:-1] & pt_n[1:]).nonzero()[0]
... | Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting a zero-crossing.
t_max: (int)
maxim... |
344,897 | def run(self):
while True:
self.display()
c = getch.getch()
if c == self.KEYS[] or c == and self.markline != 1:
self.updown(-1)
elif c == self.KEYS[] or c == :
self.updown(1)
elif c == self.KEYS[]:
... | 界面执行程序 |
344,898 | def _ValidateArguments(arg_dict, type_check_dict):
messages = []
for arg_name, arg_value in arg_dict.items():
if arg_name in type_check_dict:
type_check = type_check_dict[arg_name]
res = _ValidateValue(arg_value, type_check)
if not res:
message = ("Invalid value for argument %s. Ex... | Validate dictionary of arguments and return list of errors messages. |
344,899 | def summarize(self, fields=None, context_len=None, num_frags=None, sep=None):
args = []
fields = self._mk_field_list(fields)
if fields:
args += [, str(len(fields))] + fields
if context_len is not None:
args += [, str(context_len)]
if num_frags is... | Return an abridged format of the field, containing only the segments of
the field which contain the matching term(s).
If `fields` is specified, then only the mentioned fields are
summarized; otherwise all results are summarized.
Server side defaults are used for each option (except `fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.