language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def from_chars(chars):
"""Make Pauli's Term from chars which is written by "X", "Y", "Z" or "I".
e.g. "XZIY" => X(0) * Z(1) * Y(3)
Args:
chars (str): Written in "X", "Y", "Z" or "I".
Returns:
Term: A `Term` object.
Raises:
ValueError: When c... |
java | private boolean isSubjectValid(Subject subject) {
final WSCredential wsCred = getWSCredentialFromSubject(subject);
if (wsCred == null) {
return false;
} else {
// TODO revisit this when EJBs are supported add additional
// checks would be required
... |
python | def from_config(cls, cp, **kwargs):
"""Initializes an instance of this class from the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All additional keyword arguments are passed to the class. Any
... |
python | def xmoe_tr_dense_2k():
"""Series of architectural experiments on Translation.
# run on 8-core setup
119M params, einsum=0.95e13
Returns:
a hparams
"""
hparams = mtf_transformer2.mtf_bitransformer_base()
hparams.encoder_layers = ["self_att", "drd"] * 4
hparams.decoder_layers = ["self_att", "enc_a... |
java | public Element newElement(Locator type, String locator) {
return new Element(driver, reporter, type, locator);
} |
java | @Help(
help =
"Delete the VirtualNetworkFunctionRecord Dependency of a NetworkServiceRecord with specific id"
)
public void deleteVNFDependency(final String idNsr, final String idVnfrDep) throws SDKException {
String url = idNsr + "/vnfdependencies" + "/" + idVnfrDep;
requestDelete(url);
} |
java | public Constraint fromJSON(Model mo, JSONObject in) throws JSONConverterException {
checkKeys(in, "id");
Object id = in.get("id");
ConstraintConverter<? extends Constraint> c = json2java.get(id.toString());
if (c == null) {
throw new JSONConverterException("No converter avail... |
java | public Object getSerializedObject()
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getSerializedObject : " + ivBeanId + ", " + ivTaskId);
Object timer = TimerNpImpl.getDeserializedTimer(ivBeanId, ivTaskId); /... |
java | public IoBuffer encodePacket(Packet packet) {
IoBuffer out = null;
Header header = packet.getHeader();
int channelId = header.getChannelId();
//log.trace("Channel id: {}", channelId);
IRTMPEvent message = packet.getMessage();
if (message instanceof ChunkSize) {
... |
python | def edit_config_input_target_config_target_running_running(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
edit_config = ET.Element("edit_config")
config = edit_config
input = ET.SubElement(edit_config, "input")
target = ET.SubElement(inp... |
java | private void extractErrors(JsonObject object) {
JsonObject response;
try {
response = object.getAsJsonObject("response");
} catch (ClassCastException ex) {
return; // response is non-object
}
if (response == null) { return; }
JsonArray e = respons... |
python | def _check_transition_origin(self, transition):
"""Checks the validity of a transition origin
Checks whether the transition origin is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True, when the ... |
python | def is_partial(self):
"""
Returns True if the VG is partial, False otherwise.
"""
self.open()
part = lvm_vg_is_partial(self.handle)
self.close()
return bool(part) |
python | def run(configobj=None):
"""TEAL interface for the `clean` function."""
clean(configobj['input'],
suffix=configobj['suffix'],
stat=configobj['stat'],
maxiter=configobj['maxiter'],
sigrej=configobj['sigrej'],
lower=configobj['lower'],
upper=configobj['u... |
python | def open(path_or_url):
"""
Wrapper for opening an IO object to a local file or URL
:param path_or_url:
:return:
"""
is_url = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
... |
java | private String resolveVariables(String name) {
// Replace __variable__ with ${variable} and then evaluate the name as a groovy string
String outName = "";
int startPos = 0;
int pos = name.indexOf("__", startPos);
while (pos != -1) {
outName += name.substring(startPos, pos);
int endPos = name.indexOf("__... |
java | public <T extends Enum<T>> Optional<ImmutableSet<T>> getEnumSet(String key, Class<T> clazz) {
return this.get(key)
.map(
value ->
Streams.stream(Splitter.on(',').omitEmptyStrings().split(value))
.map(v -> asEnumValue(key, v, clazz))
.collec... |
python | def isLineComment(self, text):
"""Return true if the text is a line comment.
"""
m = self.lineComment(text, 0)
return m and m.start(0) == 0 and m.end(0) == len(text) |
python | def error_value_processor(value, error):
"""
If an error is a percentage, we convert to a float, then
calculate the percentage of the supplied value.
:param value: base value, e.g. 10
:param error: e.g. 20.0%
:return: the absolute error, e.g. 12 for the above case.
"""
if isinstance(err... |
python | def ssh_user(self, cluster='main'):
"""Return the ssh user for a cluster or current user if undefined."""
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
try:
return sel... |
python | def readline(self, size=None):
"""Reads a single line of text.
The functions reads one entire line from the file-like object. A trailing
end-of-line indicator (newline by default) is kept in the string (but may
be absent when a file ends with an incomplete line). An empty string is
returned only wh... |
java | public static void deleteFilesRecursively( File... files ) throws IOException {
if( files == null )
return;
List<File> filesToDelete = new ArrayList<> ();
filesToDelete.addAll( Arrays.asList( files ));
while( ! filesToDelete.isEmpty()) {
File currentFile = filesToDelete.remove( 0 );
if( currentFile =... |
java | @Override
public final void start(ClientStreamListener listener) {
masterListener = listener;
Status shutdownStatus = prestart();
if (shutdownStatus != null) {
cancel(shutdownStatus);
return;
}
class StartEntry implements BufferEntry {
@Override
public void runWith(Subst... |
python | def modifyContacts(self, contactids, paused):
"""Modifies a list of contacts.
Provide comma separated list of contact ids and desired paused state
Returns status message
"""
response = self.request("PUT", "notification_contacts", {'contactids': contactids,
... |
python | def get_vals_between_times(dataset_id, start_time, end_time, timestep,increment,**kwargs):
"""
Retrive data between two specified times within a timeseries. The times
need not be specified in the timeseries. This function will 'fill in the blanks'.
Two types of data retrieval can be done.
... |
python | def mark_job_as_canceling(self, job_id):
"""
Mark the job as requested for canceling. Does not actually try to cancel a running job.
:param job_id: the job to be marked as canceling.
:return: the job object
"""
job, _ = self._update_job_state(job_id, State.CANCELING)
... |
python | def graph(ctx, items, seconds, ylim):
"""Present a live graph of the incoming streaming data
This command requires that matplotlib be installed and accessible
to the application in order to work. The application reads
data from the WVA event stream and plots all data for specified
parameters within some time wind... |
python | def update(self, n=1):
"""Increment current value."""
with self._lock:
self._pbar.update(n)
self.refresh() |
python | def __stripValue(self, value):
"""strip the special characters in the value
Args:
value: value string
Returns:
value string without special characters
"""
if isinstance(value, str):
if ( value[0] == '"' and val... |
python | def cors_configuration(self):
"""
Retrieves the current CORS configuration.
:returns: CORS data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.get(endpoint)
resp.raise_for_statu... |
python | def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... |
java | public synchronized boolean isDoomed() {
if (isAlive()) {
// as long as the Thread is still active it is never doomed
return false;
}
if (m_doomed) {
// not longer active, and already doomed, so rest in peace...
return true;
}
// c... |
java | public void marshall(DeleteSchemaRequest deleteSchemaRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteSchemaRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteSchemaRequest.ge... |
java | public static void writeList(Collection<?> lines,
OutputStream output) throws IOException {
writeList(lines, output, Charset.defaultCharset());
} |
java | @Override
public Content getNavLinkPrevious() {
Content prevletterLabel = contents.prevLetter;
if (prev == -1) {
return HtmlTree.LI(prevletterLabel);
}
else {
Content prevLink = getHyperLink(DocPaths.indexN(prev),
prevletterLabel);
... |
python | def ewm_bootstrap(
a, size=None, com=None, span=None, halflife=None, alpha=None
):
"""Bootstrap a new distribution through exponential weighting.
Parameters
----------
a : 1-D array-like
Array from which to generate random sample of elements
size : int or tuple of ints, default... |
java | @Nonnull
public static String escapeMetricNamePart(@Nonnull String namePart) {
int i = 0;
int l = namePart.length();
while (i < l) {
char ch = namePart.charAt(i);
if (ch == ',' || ch == '=' || ch == '\\') {
break;
}
i++;
... |
java | @Beta
public final <T> Collection<T> parseArrayAndClose(
Class<?> destinationCollectionClass,
Class<T> destinationItemClass,
CustomizeJsonParser customizeParser)
throws IOException {
try {
return parseArray(destinationCollectionClass, destinationItemClass, customizeParser);
} fin... |
java | private void validateTableOptionShardingField(TableDefinition tableDef, String optValue) {
// Verify that the sharding-field exists and is a timestamp field.
FieldDefinition shardingFieldDef = tableDef.getFieldDef(optValue);
Utils.require(shardingFieldDef != null,
"Shar... |
python | def revoke_admin_privileges(self, username):
"""Revoke cluster administration privileges from a user.
:param username: the username to revoke privileges from
:type username: str
.. note:: Only a cluster administrator can create/ drop databases
and manage users.
"""
... |
java | @Pure
public static File getJarFile(URL url) {
if (isJarURL(url)) {
final String path = url.getPath();
final int idx = path.lastIndexOf(JAR_URL_FILE_ROOT);
if (idx >= 0) {
return new File(decodeHTMLEntities(path.substring(idx + 1)));
}
}
return null;
} |
python | def run(self):
"""Process the work unit, or wait for sentinel to exit"""
while True:
self.running = True
workunit = self._workq.get()
if is_sentinel(workunit):
# Got sentinel
break
# Run the job / sequence
worku... |
java | public SeleniumAssert isTextField(Condition<WebElement> cond) {
if (actual instanceof List) {
Conditions.instance().equals(cond);
}
return this;
} |
java | public String buildImageId() {
// stream messages end with new line, so call trim to remove it
final String stream = stream();
return stream != null && stream.startsWith("Successfully built")
? stream.substring(stream.lastIndexOf(' ') + 1).trim()
: null;
} |
python | def run_and_measure(self, quil_program, qubits, trials=1):
"""
Run a Quil program once to determine the final wavefunction, and measure multiple times.
:note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes
measurements and/or noisy quantum gates,... |
python | def delete(self, key):
"""Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None:
data = self.db.delete(key.st... |
python | def _dPdT_sat(cls, T):
"""Auxiliary equation for the dP/dT along saturation line
Parameters
----------
T : float
Temperature, [K]
Returns
-------
dPdT : float
dPdT, [MPa/K]
References
----------
IAPWS, Revised Sup... |
python | def get_neg_one_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always minus one.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.NegOneAgent(env.out... |
python | def list_column_families(self):
"""List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:return... |
java | private static void appendToBuilder(long l, int radix, StringBuilder builder, char[] bufferConversion)
{
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
{
radix = 10;
}
if (l == 0)
{
builder.append('0');
return;
}
... |
java | public SignalEventDefinitionBuilder signalEventDefinition(String signalName) {
SignalEventDefinition signalEventDefinition = createSignalEventDefinition(signalName);
element.getEventDefinitions().add(signalEventDefinition);
return new SignalEventDefinitionBuilder(modelInstance, signalEventDefinition);
} |
python | def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'):
"Get the version of the specified program"
args_prog = [program, version_arg]
try:
proc = run(
args_prog,
close_fds=True,
universal_newlines=True,
stdout=PIPE,
st... |
python | def _hm_verify_message_crc_uk(
self,
thermostat_id,
protocol,
source,
expectedFunction,
expectedLength,
datal
):
"""Verifies message appears legal"""
# expectedLength only used for read msgs as always 7 for... |
python | def next_url(request):
"""
Returns URL to redirect to from the ``next`` param in the request.
"""
next = request.GET.get("next", request.POST.get("next", ""))
host = request.get_host()
return next if next and is_safe_url(next, host=host) else None |
java | @Override
public DataBuffer create(Pointer pointer, DataType type, long length, @NonNull Indexer indexer) {
switch (type) {
case BOOL:
return new BoolBuffer(pointer, indexer, length);
case BYTE:
return new Int8Buffer(pointer, indexer, length);
... |
python | def underflow(self, axis=0):
"""
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
"""
if axis not in range(3):
raise ValueError("axis must be 0, 1, or 2")
if self.DIM == 1:
return self.GetB... |
java | @Deprecated
public Path index(Path bigwigPath) throws Exception {
// FileUtils.checkFile(indexPath);
ChunkFrequencyManager chunkFrequencyManager = new ChunkFrequencyManager(indexPath);
// get the chunk size
int chunkSize = chunkFrequencyManager.getChunkSize();
int prevChunk ... |
java | public void addSortExpression(AbstractExpression sortExpr, SortDirectionType sortDir)
{
assert(sortExpr != null);
// PlanNodes all need private deep copies of expressions
// so that the resolveColumnIndexes results
// don't get bashed by other nodes or subsequent planner runs
... |
python | def unquote_plus(string, encoding='utf-8', errors='replace'):
"""Like unquote(), but also replace plus signs by spaces, as required for
unquoting HTML form values.
unquote_plus('%7e/abc+def') -> '~/abc def'
"""
string = string.replace('+', ' ')
return unquote(string, encoding, errors) |
python | def delete_messages(self, only_processed=True):
"""Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted.
"""
messages = self._processed_messages
if not only_processed:
messages += self._messages
... |
java | public FieldReaderWriter locateField(String name) {
if (hasFieldChangedInHierarchy(name)) {
return walk(name, getLatestTypeDescriptor());
}
else {
return getFieldInHierarchy(name);
}
} |
java | @BetaApi
public final Operation startInstance(String instance) {
StartInstanceHttpRequest request =
StartInstanceHttpRequest.newBuilder().setInstance(instance).build();
return startInstance(request);
} |
java | public static Class<?> getValueType(FacesContext context, UIComponent uiComponent, Collection<Class<?>> validTypes) {
Class<?> valueType = getValueType(context, uiComponent);
if (valueType != null && isValid(validTypes, valueType)) {
return valueType;
}
else {
for (UIComponent child : uiComponent.getChild... |
python | def randomly_assign_instances(semester, pool, profiles=None, instances=None):
"""
Randomly assigns workshift instances to profiles.
Returns
-------
list of workshift.WorkshiftProfile
list of workshift.WorkshiftInstance
"""
if profiles is None:
profiles = WorkshiftProfile.objects... |
python | def ip_addresses_from_xff(value: str) -> List[str]:
"""
Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDE... |
java | public static ResourceManager get(Class<?> clazz) {
String bundleName = clazz.getName() + "RB";
return get(bundleName);
} |
python | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
... |
java | public Principal authenticate(List<String> authHeader) throws AuthException {
if (isAuthEnabled()) {
String credentials = parseCredentials(authHeader);
return pravegaAuthManager.authenticate(credentials);
}
return null;
} |
java | public D getDestinationWithoutControl(final S source){
try {
return mapper.nullVNotAllAll(source);
} catch (Exception e) {
JmapperLog.error(e);
}
return null;
} |
python | def longest_run(da, dim='time'):
"""Return the length of the longest consecutive run of True values.
Parameters
----------
arr : N-dimensional array (boolean)
Input array
dim : Xarray dimension (default = 'time')
Dimension along which to calculate consecutive run... |
java | private String getPathUntilWildcard(String locationPatternString, boolean defaultToLocaldir) {
String currentLocationPatternString;
int locationPatternStringLength = locationPatternString.length();
//Find the first occurrence of * or ?, if none, set idx to locationPatternLength
int sta... |
java | public static int cusparseScsric0(
cusparseHandle handle,
int trans,
int m,
cusparseMatDescr descrA,
Pointer csrSortedValA_ValM,
/** matrix A values are updated inplace
to be the preconditioner M values... |
python | def inserir(self, id_brand, name):
"""Inserts a new Model and returns its identifier
:param id_brand: Identifier of the Brand. Integer value and greater than zero.
:param name: Model name. String with a minimum 3 and maximum of 100 characters
:return: Dictionary with the following stru... |
java | protected void processServiceClass(ClassDoc service,
Configuration configuration) {
Tag[] serviceTagArray = service.tags(WRTagTaglet.NAME);
for (int i = 0; i < serviceTagArray.length; i++) {
Set<String> serviceTags = WRTagTaglet.getTagSet(serviceTagArray[i]
.text());
for (Iterator<String> iter = servi... |
python | def network_create_notif(self, tenant_id, tenant_name, cidr):
"""Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if not router_id:
LOG.error("Rout ID not pres... |
java | @Override
public Evaluation evaluate(SolutionType solution) {
if(penalizingConstraints.isEmpty()){
// CASE 1: no penalizing constraints
return objective.evaluate(solution, data);
} else {
// CASE 2 (default): aggregate evaluation and penalties
Evaluati... |
java | public void setExpression(Expression newExpression)
{
if (newExpression != expression)
{
NotificationChain msgs = null;
if (expression != null)
msgs = ((InternalEObject)expression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - SimpleExpressionsPackage.NOT_EXPRESSION__EXPRESSION, null, msgs... |
java | public static String toCurrency(Locale locale, double number) {
return NumberFormat.getCurrencyInstance(locale).format(number);
} |
java | public static IoBuffer copy(ByteBuffer src) {
IoBuffer copy = IoBuffer.allocate(src.remaining());
copy.put(src);
copy.flip();
return copy;
} |
java | private CompletableFuture<?> loadSmallestOffsetPage(PageCollection pageCollection, TimeoutTimer timer) {
if (pageCollection.getCount() <= 1) {
// We only modified at most one page. This means have at most one page in the index, so no point in re-loading it.
return CompletableFuture.compl... |
java | static void generateProjectPropertiesFile(
final String name,
final File destfile,
final boolean overwrite,
final Properties properties,
final boolean merge,
final Set<String> removePrefixes,
boolean addDefaultProps
)
{
... |
java | @Override
public void start(final VortexThreadPool vortexThreadPool) {
final VortexFuture future = vortexThreadPool.submit(new HelloVortexFunction(), null);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
} |
python | def updateDataset(self):
"""Updates the dataset."""
self.__updateDataItem()
self.__countNbRecords()
self.__columns = self.__parseColumns() |
python | def choose_tag(self: object, tokens: List[str], index: int, history: List[str]):
"""Use regular expressions for rules-based lemmatizing based on word endings;
tokens are matched for patterns with the base kept as a group; an word ending
replacement is added to the (base) group.
:rtype: s... |
java | public String toJSON(List<JTSFeature> list) {
Object fcJSON = this.startFeatureCollection();
for (JTSFeature feature : list) {
Object f = this.startFeature();
Object p = this.startPoint();
try {
this.addXToPoint(feature.getGeometry().getGeometry()
.getCentroid().getX(), p);
this.addYToPoint(f... |
java | public MUCLightRoomConfiguration getConfiguration(String version)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
MUCLightGetConfigsIQ mucLightGetConfigsIQ = new MUCLightGetConfigsIQ(room, version);
IQ responseIq = connection.createStanzaCollecto... |
python | def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
retu... |
python | def get_db(data):
"""Retrieve a snpEff database name and location relative to reference file.
"""
snpeff_db = utils.get_in(data, ("genome_resources", "aliases", "snpeff"))
snpeff_base_dir = None
if snpeff_db:
snpeff_base_dir = utils.get_in(data, ("reference", "snpeff"))
if not (isins... |
python | def do_cd(self, arglist):
"""Change directory.
Usage:
cd <new_dir>
"""
# Expect 1 argument, the directory to change to
if not arglist or len(arglist) != 1:
self.perror("cd requires exactly 1 argument:", traceback_war=False)
self.do_help('cd')
... |
python | def hash_hook(path, options):
"""Hash a hook file"""
with open(path, 'r') as f:
data = f.read()
for key in sorted(iterkeys(options)):
data += '\n#{}={}'.format(key, options.get(key))
return hashlib.md5(data.encode()).hexdigest() |
java | private void saveResponseCookies() throws IOException {
CookieHandler cookieHandler = CookieHandler.getDefault();
if (cookieHandler != null) {
try {
URI uri = getURL().toURI();
cookieHandler.put(uri, getHeaderFieldsDoNotForceResponse());
} catch (URISyntaxException e) {
throw... |
python | def get_info_messages(self):
"""
Method returning info messages. Should return list of messages.
By default it find element with class ``info`` and theirs value in
attribute ``info`` or text if that attribute is missing. You can change
this method accordingly to your app.
... |
java | public static Reader reader(Format type, InputStream in, Map<String, ReadHandler<?, ?>> customHandlers) {
return reader(type, in, customHandlers, null);
} |
python | def stream_name_mapping(stream, exclude_params=['name'], reverse=False):
"""
Return a complete dictionary mapping between stream parameter names
to their applicable renames, excluding parameters listed in
exclude_params.
If reverse is True, the mapping is from the renamed strings to the
origina... |
python | def get_range(self, i):
"""
Check and retrieve range if value is a valid range.
Here we are looking to see if the value is series or range.
We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine).
"""
try:
m = i.match(RE_INT_ITER)
... |
python | def mark_rewrite(self, *names):
"""Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
"""
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for... |
python | def config_files():
'''
Get list of currently used config files.
'''
sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE')
sensu_config_files = os.environ.get('SENSU_CONFIG_FILES')
sensu_v1_config = '/etc/sensu/config.json'
sensu_v1_confd = '/etc/sensu/conf.d'
if sensu_loaded_t... |
python | def run(self, *args, **kwargs):
""" Connect and run bot in event loop. """
self.eventloop.run_until_complete(self.connect(*args, **kwargs))
try:
self.eventloop.run_forever()
finally:
self.eventloop.stop() |
python | def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... |
python | def _process_pubsub(self, obj, *, process_waiters=True):
"""Processes pubsub messages."""
kind, *args, data = obj
if kind in (b'subscribe', b'unsubscribe'):
chan, = args
if process_waiters and self._in_pubsub and self._waiters:
self._process_data(obj)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.