language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def tomof(self, maxline=MAX_MOF_LINE):
"""
Return a MOF string with the declaration of this CIM class.
The returned MOF string conforms to the ``classDeclaration``
ABNF rule defined in :term:`DSP0004`.
The order of properties, methods, parameters, and qualifiers is
pres... |
java | public boolean replace(K key, V oldValue, V newValue) {
Object curValue = get(key);
if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) {
return false;
}
put(key, newValue);
return true;
} |
java | @Override
public ResourceSet<Account> read(final TwilioRestClient client) {
return new ResourceSet<>(this, client, firstPage(client));
} |
python | def maybe_download_and_extract(dest_directory, cifar_classnum):
"""Download and extract the tarball from Alex's website. Copied from tensorflow example """
assert cifar_classnum == 10 or cifar_classnum == 100
if cifar_classnum == 10:
cifar_foldername = 'cifar-10-batches-py'
else:
cifar_f... |
python | def count_time(function):
"""
Function: count_time
Summary: get the time to finish a function
print at the end that time to stdout
Examples: <NONE>
Attributes:
@param (function): function
Returns: wrapped function
"""
@wraps(function)
def _wrapper(*args, **kwargs... |
java | @Override
public final void initialize(final PhoneNumber pconstraintAnnotation) {
allowDin5008 = pconstraintAnnotation.allowDin5008();
allowE123 = pconstraintAnnotation.allowE123();
allowUri = pconstraintAnnotation.allowUri();
allowMs = pconstraintAnnotation.allowMs();
allowCommon = pconstraintAnn... |
java | void scanObject()
throws IOException
{
int ch = read();
switch (ch) {
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0... |
python | def get_public(self):
'''
Returns the public object or None if there is no such element
@return: the public object
@rtype: L{Cpublic}
'''
node = self.node.find('public')
if node is not None:
return Cpublic(node=node)
else:
return No... |
java | public void setThingGroupsToRemove(java.util.Collection<String> thingGroupsToRemove) {
if (thingGroupsToRemove == null) {
this.thingGroupsToRemove = null;
return;
}
this.thingGroupsToRemove = new java.util.ArrayList<String>(thingGroupsToRemove);
} |
python | def _rearrange_output_for_package(self, target_workdir, java_package):
"""Rearrange the output files to match a standard Java structure.
Antlr emits a directory structure based on the relative path provided
for the grammar file. If the source root of the file is different from
the Pants build root, the... |
python | def explore(node):
""" Given a node, explores on relatives, siblings and children
:param node: GraphNode from which to explore
:return: set of explored GraphNodes
"""
explored = set()
explored.add(node)
dfs(node, callback=lambda n: explored.add(n))
return explored |
python | def nss(prediction, fix):
"""
Compute the normalized scanpath salience
input:
fix : list, l[0] contains y, l[1] contains x
"""
prediction = prediction - np.mean(prediction)
prediction = prediction / np.std(prediction)
return np.mean(prediction[fix[0], fix[1]]) |
java | @Override
@SuppressLint("NewApi")
public void setTint(@ColorInt int tintColor) {
// Modulate alpha of tintColor against mBackgroundAlpha.
int backgroundTintColor = ColorUtils.setAlphaComponent(tintColor, Math.round(Color.alpha(
tintColor) * mBackgroundAlpha));
mBackground... |
python | def omg(args):
"""
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > ... |
python | def calculate_z1pt0(vs30):
'''
Reads an array of vs30 values (in m/s) and
returns the depth to the 1.0 km/s velocity horizon (in m)
Ref: Chiou & Youngs (2014) California model
:param vs30: the shear wave velocity (in m/s) at a depth of 30m
'''
c1 = 571 ** 4.
c2 = 1360.0 ** 4.
return ... |
python | def cli(ctx):
""" This is a command line app to get useful stats from a trello board
and report on them in useful ways.
Requires the following environment varilables:
TRELLOSTATS_APP_KEY=<your key here>
TRELLOSTATS_APP_TOKEN=<your token here>
"""
ctx.obj = dict()
ctx.ob... |
java | public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {
try {
Configuration conf = new Configuration();
conf.setInt("io.file.buffer.size", 4096);
SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());
... |
java | private void checkScrollBar(AdjustmentEvent e) {
// The scroll bar listModel contains information needed to determine
// whether the viewport should be repositioned or not.
JScrollBar jsb = (JScrollBar) e.getSource();
BoundedRangeModel listModel = jsb.getModel();
int value = li... |
python | def as_bin(self, *args, **kwargs):
"""Returns a binary blob containing the streamed transaction.
For information about the parameters, see :func:`Tx.stream <stream>`
:return: binary blob that would parse to the given transaction
"""
f = io.BytesIO()
self.stream(f, *args... |
java | public static final int getScript(int codepoint){
if (codepoint >= UCharacter.MIN_VALUE & codepoint <= UCharacter.MAX_VALUE) {
int scriptX=UCharacterProperty.INSTANCE.getAdditional(codepoint, 0)&UCharacterProperty.SCRIPT_X_MASK;
if(scriptX<UCharacterProperty.SCRIPT_X_WITH_COMMON) {
... |
python | async def getTriggerToken(self, *args, **kwargs):
"""
Get a trigger token
Retrieve a unique secret token for triggering the specified hook. This
token can be deactivated with `resetTriggerToken`.
This method gives output: ``v1/trigger-token-response.json#``
This method... |
python | def tmatrix_sampler(C, reversible=False, mu=None, T0=None, nsteps=None, prior='sparse'):
r"""Generate transition matrix sampler object.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
reversible : bool
If true sample from the ensemble of transition matri... |
python | def _get_default_leveldb_path() -> str:
"""
Returns the LevelDB path
:return: The LevelDB path
"""
system = platform.system().lower()
leveldb_fallback_dir = os.path.expanduser("~")
if system.startswith("darwin"):
leveldb_fallback_dir = os.path.join(
... |
python | def router_fabric_virtual_gateway_address_family_ipv6_enable_global(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
router = ET.SubElement(config, "router", xmlns="urn:brocade.com:mgmt:brocade-common-def")
fabric_virtual_gateway = ET.SubElement(router, "... |
java | @Override
public final Iterable<NoteDocument> findAll(final String filename) {
final Query searchQuery =
new Query(Criteria.where("filename").is(filename));
final List<NoteDocumentMongo> noteDocumentsMongo =
mongoTemplate.find(searchQuery, NoteDocumentMongo.class);
... |
java | private static String getFilePath(String file) {
logger.entering(file);
String filePath = null;
URL fileURL = GuiMapReaderFactory.class.getClassLoader().getResource(file);
if (fileURL != null) {
filePath = fileURL.getPath();
}
logger.exiting(filePath);
... |
python | def put_targets(Rule, Targets,
region=None, key=None, keyid=None, profile=None):
'''
Add the given targets to the given rule
Returns a dictionary describing any failures.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudwatch_event.put_targets myrule [{'Id': 'target... |
java | public Observable<CertificateBundle> restoreCertificateAsync(String vaultBaseUrl, byte[] certificateBundleBackup) {
return restoreCertificateWithServiceResponseAsync(vaultBaseUrl, certificateBundleBackup).map(new Func1<ServiceResponse<CertificateBundle>, CertificateBundle>() {
@Override
... |
java | @Requires("ClassName.isBinaryName(className)")
protected ContractAnalyzer analyze(String className)
throws IOException {
/* Skip helper classes. */
if (className.endsWith(JavaUtils.HELPER_CLASS_SUFFIX)) {
return null;
}
/* Skip interfaces. */
String helperFileName = className + JavaUt... |
python | def of_service(config):
"""Connect to an IBM Streams service instance running in IBM Cloud Private for Data.
The instance is specified in `config`. The configuration may be code injected from the list of services
in a Jupyter notebook running in ICPD or manually created. The code that selects a... |
python | def rand_hexstr(length, lower=True):
"""Gererate fixed-length random hexstring, usually for md5.
:param length: total length of this string.
:param lower: use lower case or upper case.
"""
if lower:
return rand_str(length, allowed=CHARSET_HEXSTR_LOWER)
else:
return rand_str(leng... |
python | def find(self, gridpos, find_string, flags, search_result=True):
"""Return next position of event_find_string in MainGrid
Parameters:
-----------
gridpos: 3-tuple of Integer
\tPosition at which the search starts
find_string: String
\tString to find in grid
... |
java | private void postCreatedOrEnabledUser(UserDetails userDetails, Map<String, Object> userInfo) {
if (oAuth2PostCreatedOrEnabledUserService != null) {
oAuth2PostCreatedOrEnabledUserService.postCreatedOrEnabledUser(userDetails, userInfo);
}
} |
python | def notice(txt, color=False):
"print notice"
if color:
txt = config.Col.WARNING + txt + config.Col.ENDC
print(txt) |
python | def having_raw(self, sql, bindings=None, boolean="and"):
"""
Add a raw having clause to the query
:param sql: The raw query
:type sql: str
:param bindings: The query bindings
:type bindings: list
:param boolean: Boolean joiner type
:type boolean: str
... |
python | def uncancel(self):
"""Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object.
"""
if self.cancelled:
logger.debug("Uncancelling {}".format(self))
self.cancelled = False
self.save()
# ... |
python | def _getFontChars(self, font_files):
"""
Returns code points of characters included in given font files.
"""
code_points = set()
for font_file in font_files:
face = ft.Face(font_file)
charcode, agindex = face.get_first_char()
while agindex != 0... |
java | private void init(
final Path output, final SAMFileHeader header, final boolean writeHeader,
final TaskAttemptContext ctx)
throws IOException
{
init(
output.getFileSystem(ctx.getConfiguration()).create(output),
header, writeHeader, ctx);
... |
python | def validate_csv(file):
"""Return dialect information about given csv file."""
try:
# Detect encoding and dialect
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
sample = fp.read(
current_app.config.get('PREVIEWER_CSV_VALIDATION_BYT... |
java | public static sslcertkey_service_binding[] get(nitro_service service, String certkey) throws Exception{
sslcertkey_service_binding obj = new sslcertkey_service_binding();
obj.set_certkey(certkey);
sslcertkey_service_binding response[] = (sslcertkey_service_binding[]) obj.get_resources(service);
return response;... |
java | public void afterMaterialization(IndirectionHandler handler, Object materializedObject)
{
try
{
Identity oid = handler.getIdentity();
if (log.isDebugEnabled())
log.debug("deferred registration: " + oid);
if(!isOpen())
{
... |
python | def cmd_adb(self, *args):
'''
Run adb from the Android SDK.
Args must come after --, or use
--alias to make an alias
'''
self.check_requirements()
self.install_platform()
args = args[0]
if args and args[0] == '--alias':
print('To set up... |
python | def _get_stdout(stderr=False):
"""
This utility function contains the logic to determine what streams to use
by default for standard out/err.
Typically this will just return `sys.stdout`, but it contains additional
logic for use in IPython on Windows to determine the correct stream to use
(usua... |
java | public static int medoid(boolean parallel, List<? extends Vec> X, double tol, DistanceMetric dm)
{
IntList order = new IntList(X.size());
ListUtils.addRange(order, 0, X.size(), 1);
List<Double> accel = dm.getAccelerationCache(X, parallel);
return medoid(parallel, order, tol, X, dm, a... |
python | def prefix(self, prefix, lowercase=True):
''' Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
config_dirs /e... |
java | protected void transferInvisibleValues(CmsEntity original, CmsEntity target, CmsContentTypeVisitor visitor) {
List<String> invisibleAttributes = new ArrayList<String>();
for (Entry<String, CmsAttributeConfiguration> configEntry : visitor.getAttributeConfigurations().entrySet()) {
if (!confi... |
python | def get_metric_group_definition(self, group_name):
"""
Get a faked metric group definition by its group name.
Parameters:
group_name (:term:`string`): Name of the metric group.
Returns:
:class:~zhmcclient.FakedMetricGroupDefinition`: Definition of the
... |
python | def to_dataframe(self):
"""Convert the confusion matrix to a dataframe.
Returns:
A DataFrame with "target", "predicted", "count" columns.
"""
data = []
for target_index, target_row in enumerate(self._cm):
for predicted_index, count in enumerate(target_row):
data.append((self._l... |
python | def double(window, config):
"""Double theme
==================
= Header =
==================
= items =
==================
= footer =
==================
"""
cordx = round(config.get('cordx', 0))
color = config.get('color', red)
icon = config.get('... |
python | def override_root_main_ref(config, remotes, banner):
"""Override root_ref or banner_main_ref with tags in config if user requested.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param iter remotes: List of dicts from Versions.remotes.
:param bool banner: Evaluate banner mai... |
java | @SuppressWarnings({"unchecked"})
public <T> T read(URL jsonURL) throws IOException {
return read(jsonURL, Configuration.defaultConfiguration());
} |
java | public static void setDnsCache(Properties properties) {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
final String host = (String) entry.getKey();
String ipList = (String) entry.getValue();
ipList = ipList.trim();
if (ipList.isEmpty()) continue;... |
python | def top(self):
"""Top Processes.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: list
"""
nodes = []
for node in self.nodes():
nodes.append(self.http_cl... |
python | def main():
"""
Setup the parser and call the command function
"""
parser = argparse.ArgumentParser(description='Longclaw CLI')
subparsers = parser.add_subparsers()
start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project')
start.add_argument('project_name', help='Name ... |
python | def preview(src_path):
''' Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page.
'''
previews = []
if sketch.is_sketchfile(src_path):
previews = sketch.preview(src_path)
if not previews:
previews = quicklook.preview(src_path)
previews = [... |
python | def denorm(self,arr):
"""Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz)
"""
if type(arr) is not np.ndarray: arr = to_np(arr)
if len(arr.shape)==3: arr = arr[None]
return self.transform.denorm(np.rollaxis(arr,1,4... |
java | public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) {
return getLastModified(
servletContext,
request,
path,
FileUtils.getExtension(path)
);
} |
python | def init_providers(self, provider, kwargs):
"""
Inits main and fallback provider if relevant
:param provider: Provider name to use
:param kwargs: Additional kwargs
:raises ValueError: If provider name or fallback names are not valid providers, a :exc:`ValueError` will
b... |
java | public static long usedMemory() {
long memory = 0;
for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
memory += mp.getUsage().getUsed();
}
return memory;
} |
java | @SneakyThrows
private static MongoClientOptions buildMongoDbClientOptions(final BaseMongoDbProperties mongo) {
var clientOptions = (MongoClientOptions.Builder) null;
if (StringUtils.isNotBlank(mongo.getClientUri())) {
val opts = buildMongoClientURI(mongo.getClientUri()).getOptions();
... |
python | def _vars_match(self):
"""Regular expression to match playbook variable."""
return re.compile(
r'#([A-Za-z]+)' # match literal (#App) at beginning of String
r':([\d]+)' # app id (:7979)
r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name)
r'!(St... |
python | def get_container_sas_token(block_blob_client,
container_name, blob_permissions):
"""Obtains a shared access signature granting the specified permissions to the
container.
:param block_blob_client: A blob service client.
:type block_blob_client: `azure.storage.blob.BlockBlob... |
java | protected void addTagsInfo(Element e, Content htmltree) {
if (configuration.nocomment) {
return;
}
Content dl = new HtmlTree(HtmlTag.DL);
if (utils.isExecutableElement(e) && !utils.isConstructor(e)) {
addMethodInfo((ExecutableElement)e, dl);
}
Cont... |
python | def get_all(self, path, data=None, limit=100):
"""Encapsulates GET all requests"""
return ListResultSet(path=path, data=data or {}, limit=limit) |
python | def open(self, number=0):
"""
Open the FaderPort and register a callback so we can send and
receive MIDI messages.
:param number: 0 unless you've got more than one FaderPort attached.
In which case 0 is the first, 1 is the second etc
I only h... |
java | public void connectToLink(Link link) throws ShanksException {
if (!this.linksList.contains(link)) {
this.linksList.add(link);
logger.finer("Device " + this.getID()
+ " is now connected to Link " + link.getID());
link.connectDevice(this);
}
} |
python | def polygon_scale(polygon):
"""
For a Polygon object, return the diagonal length of the AABB.
Parameters
------------
polygon: shapely.geometry.Polygon object
Returns
------------
scale: float, length of AABB diagonal
"""
extents = np.reshape(polygon.bounds, (2, 2)).ptp(axis=0)... |
python | def _update_usage_for_alb(self, conn, alb_arn, alb_name):
"""
Update usage for a single ALB.
:param conn: elbv2 API connection
:type conn: :py:class:`ElasticLoadBalancing.Client`
:param alb_arn: Load Balancer ARN
:type alb_arn: str
:param alb_name: Load Balancer ... |
java | public void append2SQLWhere(final SQLSelect _select)
throws EFapsException
{
for (final ISelectPart part : this.selectParts) {
part.add2Where(this, _select);
}
} |
python | def _as_rescale(self, get, targetbitdepth):
"""Helper used by :meth:`asRGB8` and :meth:`asRGBA8`."""
width,height,pixels,meta = get()
maxval = 2**meta['bitdepth'] - 1
targetmaxval = 2**targetbitdepth - 1
factor = float(targetmaxval) / float(maxval)
meta['bitdepth'] = tar... |
python | def _slice_vcf_chr21(vcf_file, out_dir):
"""
Slice chr21 of qsignature SNPs to reduce computation time
"""
tmp_file = os.path.join(out_dir, "chr21_qsignature.vcf")
if not utils.file_exists(tmp_file):
cmd = ("grep chr21 {vcf_file} > {tmp_file}").format(**locals())
out = subprocess.che... |
python | def render(template, extra={}, **kwargs):
"""Return the template rendered using Python's str.format()."""
context = hookenv.execution_environment()
context.update(extra)
context.update(kwargs)
return template.format(**context) |
python | def exists(self):
"""Check whether the cluster already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_cluster_exists]
:end-before: [END bigtable_check_cluster_exists]
:rtype: bool
:returns: True if the table exi... |
python | def nextValidComment(self, text, start=0):
"""Return the next actual comment.
"""
m = min([self.lineComment(text, start),
self.blockComment(text, start)],
key=lambda m: m.start(0) if m else len(text))
return m |
java | public void setExcludedMobileDevices(com.google.api.ads.admanager.axis.v201902.Technology[] excludedMobileDevices) {
this.excludedMobileDevices = excludedMobileDevices;
} |
python | def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
Parameters
----------
batch_size: int
Size of data split
update_freq: int
Update Frequency for calculating full gradients
Returns
----------
di: mx.io.NDA... |
java | protected void removeWorkspace(ManageableRepository mr, String workspaceName) throws RepositoryException
{
boolean isExists = false;
for (String wsName : mr.getWorkspaceNames())
if (workspaceName.equals(wsName))
{
isExists = true;
break;
}
if (is... |
java | public void close() {
// make sure that we close only once
if (!this.closed.compareAndSet(false, true)) {
return;
}
// clear the current probe side channel, if there is one
if (this.currentSpilledProbeSide != null) {
try {
this.currentSpilledProbeSide.getChannel().closeAndDelete();
} catch (Thro... |
java | public void followedIdentifierInvalid(final String followedId) {
this.addStatusMessage(
ProtocolConstants.StatusCodes.Create.Follow.FOLLOWED_NOT_EXISTING,
"there is no user with the identifier \"" + followedId
+ "\". Please provide a valid user identifier.");
} |
java | public static int argMax(final double[] x) {
checkArgument(x.length > 0);
double maxValue = Double.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < x.length; ++i) {
final double val = x[i];
if (val > maxValue) {
maxIndex = i;
maxValue = val;
}
}
return maxIndex... |
java | public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
int index = 0;
while (buf.length() > index) {
if (Character.isWhitespace(buf.charAt(index))) {
buf.deleteC... |
java | public static InstrumentedThreadFactory defaultThreadFactory(MetricRegistry registry, String name) {
return new InstrumentedThreadFactory(Executors.defaultThreadFactory(), registry, name);
} |
java | public final String getTags(final Priority priority) {
if (priority == Priority.HIGH) {
return high;
}
else if (priority == Priority.NORMAL) {
return normal;
}
else {
return low;
}
} |
python | def splits(cls, text_field, label_field, parse_field=None,
extra_fields={}, root='.data', train='train.jsonl',
validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
A... |
python | def normprob(d, snrs, inds=None, version=2):
""" Uses observed SNR distribution to calculate normal probability SNR
Uses state dict to calculate number of trials.
snrs is list of all snrs in distribution.
version used to toggle for tests. version 2 is fastest and returns zeros for filtered snr values.
... |
java | public Action0 getStartAction() {
return new Action0() {
@Override
public void call() {
if (startTime == null) {
startTime = new Date().getTime();
}
}
};
} |
python | def check_actors(self, actors):
"""
Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list
"""
super(Sequence, self).check_actors(actors)
actor = self.first_active
if ... |
java | private void rollback(Node<ColumnName> row) {
Node<ColumnName> node = row.left;
while (node != row) {
uncoverColumn(node.head);
node = node.left;
}
uncoverColumn(row.head);
} |
python | def set_pan(self, pan_x, pan_y, coord='data', no_reset=False):
"""Set pan position.
Parameters
----------
pan_x, pan_y : float
Pan positions in X and Y.
coord : {'data', 'wcs'}
Indicates whether the given pan positions are in data or WCS space.
... |
python | def _matrix_integration(q, h, t):
''' Returns the dp metric for a single horsetail
curve at a given value of the epistemic uncertainties'''
N = len(q)
# correction if CDF has gone out of trapezium range
if h[-1] < 0.9: h[-1] = 1.0
W = np.zeros([N, N])
for i in range(N):
W[i, i] = ... |
java | public boolean hasNodeType(InternalQName nodeTypeName) throws RepositoryException
{
if (!validatate())
{
return false;
}
NodeData nodeTypeData =
(NodeData)dataManager.getItemData(nodeTypeStorageRoot, new QPathEntry(nodeTypeName, 1), ItemType.NODE);
return nodeTypeDat... |
java | public boolean isExtensionEnabled(String extensionName) {
if (extensionName == null) {
throw new IllegalArgumentException("Parameter extensionName must not be null.");
}
Extension extension = getExtension(extensionName);
if (extension == null) {
return fal... |
java | @Override
public synchronized boolean isChainRunning(String chainName) {
boolean rc = false;
if (null != chainName) {
Chain c = this.chainRunningMap.get(chainName);
if (null != c) {
rc = c.getState().equals(RuntimeState.STARTED) || c.getState().equals(RuntimeS... |
python | def hexstr(x, onlyasc=0, onlyhex=0, color=False):
"""Build a fancy tcpdump like hex from bytes."""
x = bytes_encode(x)
_sane_func = sane_color if color else sane
s = []
if not onlyasc:
s.append(" ".join("%02X" % orb(b) for b in x))
if not onlyhex:
s.append(_sane_func(x))
retu... |
python | def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
if master.linkerror:
print("link %u down" % (master.linknum+1))
else:
print("lin... |
python | def _get_previous_assessment_section(self, assessment_section_id):
"""Gets the previous section before section_id.
Assumes that section list exists in taken and section_id is in section list.
Assumes that Section parts only exist as children of Assessments
"""
if self._my_map['... |
python | def maximumCanEqual(self):
"""Flag indicating if the minimum value is inclusive or exclusive."""
if self.maximum is None:
raise SchemaError("maximumCanEqual requires presence of maximum")
value = self._schema.get("maximumCanEqual", True)
if value is not True and value is not ... |
python | def process_cbn_jgif_file(file_name):
"""Return a PybelProcessor by processing a CBN JGIF JSON file.
Parameters
----------
file_name : str
The path to a CBN JGIF JSON file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
... |
java | public Observable<VirtualMachineScaleSetInner> updateAsync(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetUpdate parameters) {
return updateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, parameters).map(new Func1<ServiceResponse<VirtualMachineScaleSetInner>, VirtualMachineSc... |
python | def shutdown(self):
"""Shutdown internal workers by pushing terminate signals."""
if not self._shutdown:
# send shutdown signal to the fetcher and join data queue first
# Remark: loop_fetcher need to be joined prior to the workers.
# otherwise, the the fet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.