language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def load_eggs(entry_point_name):
"""Loader that loads any eggs in `sys.path`."""
def _load_eggs(env):
distributions, errors = working_set.find_plugins(
pkg_resources.Environment()
)
for dist in distributions:
if dist not in working_set:
env.log.debug('Adding plugin %s from %s', dist, dist.location)
working_set.add(dist)
def _log_error(item, e):
ue = exception_to_unicode(e)
if isinstance(e, DistributionNotFound):
env.log.debug('Skipping "%s": ("%s" not found)', item, ue)
elif isinstance(e, VersionConflict):
env.log.error('Skipping "%s": (version conflict "%s")',
item, ue)
elif isinstance(e, UnknownExtra):
env.log.error('Skipping "%s": (unknown extra "%s")', item, ue)
else:
env.log.error('Skipping "%s": %s', item,
exception_to_unicode(e, traceback=True))
for dist, e in errors.iteritems():
_log_error(dist, e)
for entry in sorted(working_set.iter_entry_points(entry_point_name),
key=lambda entry: entry.name):
env.log.debug(
'Loading %s from %s',
entry.name,
entry.dist.location
)
try:
entry.load(require=True)
except Exception as exc:
_log_error(entry, exc)
else:
_enable_plugin(env, entry.module_name)
return _load_eggs |
python | def _average_genome_coverage(data, bam_file):
"""Quickly calculate average coverage for whole genome files using indices.
Includes all reads, with duplicates. Uses sampling of 10M reads.
"""
total = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
read_counts = sum(x.aligned for x in bam.idxstats(bam_file, data))
with pysam.Samfile(bam_file, "rb") as pysam_bam:
read_size = np.median(list(itertools.islice((a.query_length for a in pysam_bam.fetch()), int(1e7))))
avg_cov = float(read_counts * read_size) / total
return avg_cov |
java | private void addObjectIfNotFound(Object obj, Vector v)
{
int n = v.size();
boolean addIt = true;
for (int i = 0; i < n; i++)
{
if (v.elementAt(i) == obj)
{
addIt = false;
break;
}
}
if (addIt)
{
v.addElement(obj);
}
} |
java | final void addTaskAndWakeup(Runnable task) {
// in this loop we are going to either send the task to the owner
// or store the delayed task to be picked up as soon as the migration
// completes
for (; ; ) {
NioThread localOwner = owner;
if (localOwner != null) {
// there is an owner, lets send the task.
localOwner.addTaskAndWakeup(task);
return;
}
// there is no owner, so we put the task on the delayedTaskStack
TaskNode old = delayedTaskStack.get();
TaskNode update = new TaskNode(task, old);
if (delayedTaskStack.compareAndSet(old, update)) {
break;
}
}
NioThread localOwner = owner;
if (localOwner != null) {
// an owner was set, but we have no guarantee that he has seen our task.
// So lets try to reschedule the delayed tasks to make sure they get executed.
restoreTasks(localOwner, delayedTaskStack.getAndSet(null), true);
}
} |
python | def build_configuration(self):
"""Parse the haproxy config file
Raises:
Exception: when there are unsupported section
Returns:
config.Configuration: haproxy config object
"""
configuration = config.Configuration()
pegtree = pegnode.parse(self.filestring)
for section_node in pegtree:
if isinstance(section_node, pegnode.GlobalSection):
configuration.globall = self.build_global(section_node)
elif isinstance(section_node, pegnode.FrontendSection):
configuration.frontends.append(
self.build_frontend(section_node))
elif isinstance(section_node, pegnode.DefaultsSection):
configuration.defaults.append(
self.build_defaults(section_node))
elif isinstance(section_node, pegnode.ListenSection):
configuration.listens.append(
self.build_listen(section_node))
elif isinstance(section_node, pegnode.UserlistSection):
configuration.userlists.append(
self.build_userlist(section_node))
elif isinstance(section_node, pegnode.BackendSection):
configuration.backends.append(
self.build_backend(section_node))
return configuration |
java | private URL getRequiredUrlParameter(String keyword,
Map<String, String> parms) {
String urlString = getRequiredParameter(keyword, parms);
try {
return new URL(urlString);
} catch (MalformedURLException e) {
throw new ValidatorProcessUsageException("Value '" + urlString
+ "' for parameter '" + keyword + "' is not a valid URL: "
+ e.getMessage());
}
} |
python | def match_replace_regex(regex, src_namespace, dest_namespace):
"""Return the new mapped namespace if the src_namespace matches the
regex."""
match = regex.match(src_namespace)
if match:
return dest_namespace.replace("*", match.group(1))
return None |
python | def highest_expr_genes(
adata, n_top=30, show=None, save=None,
ax=None, gene_symbols=None, **kwds
):
"""\
Fraction of counts assigned to each gene over all cells.
Computes, for each gene, the fraction of counts assigned to that gene within
a cell. The `n_top` genes with the highest mean fraction over all cells are
plotted as boxplots.
This plot is similar to the `scater` package function `plotHighestExprs(type
= "highest-expression")`, see `here
<https://bioconductor.org/packages/devel/bioc/vignettes/scater/inst/doc/vignette-qc.html>`__. Quoting
from there:
*We expect to see the “usual suspects”, i.e., mitochondrial genes, actin,
ribosomal protein, MALAT1. A few spike-in transcripts may also be
present here, though if all of the spike-ins are in the top 50, it
suggests that too much spike-in RNA was added. A large number of
pseudo-genes or predicted genes may indicate problems with alignment.*
-- Davis McCarthy and Aaron Lun
Parameters
----------
adata : :class:`~anndata.AnnData`
Annotated data matrix.
n_top : `int`, optional (default:30)
Number of top
{show_save_ax}
gene_symbols : `str`, optional (default:None)
Key for field in .var that stores gene symbols if you do not want to use .var_names.
**kwds : keyword arguments
Are passed to `seaborn.boxplot`.
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes`.
"""
from scipy.sparse import issparse
# compute the percentage of each gene per cell
dat = normalize_per_cell(adata, counts_per_cell_after=100, copy=True)
# identify the genes with the highest mean
if issparse(dat.X):
dat.var['mean_percent'] = dat.X.mean(axis=0).A1
else:
dat.var['mean_percent'] = dat.X.mean(axis=0)
top = dat.var.sort_values('mean_percent', ascending=False).index[:n_top]
dat = dat[:, top]
columns = dat.var_names if gene_symbols is None else dat.var[gene_symbols]
dat = pd.DataFrame(dat.X.toarray(), index=dat.obs_names, columns=columns)
if not ax:
# figsize is hardcoded to produce a tall image. To change the fig size,
# a matplotlib.axes.Axes object needs to be passed.
height = (n_top * 0.2) + 1.5
fig, ax = plt.subplots(figsize=(5, height))
sns.boxplot(data=dat, orient='h', ax=ax, fliersize=1, **kwds)
ax.set_xlabel('% of total counts')
utils.savefig_or_show('highest_expr_genes', show=show, save=save)
return ax if show == False else None |
java | protected void process(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
WebOperation operation = null;
try{
operation = getOperation(request);
}catch (WebOperationNotFoundException e){
LOG.warn("WebOperation found problems: "+e.getMessage(),e);
response.setStatus(404);
return;
}
String method = getMethod(request);
operation.request(method, request, response);
} |
python | def safe_eval(source, *args, **kwargs):
""" eval without import """
source = source.replace('import', '') # import is not allowed
return eval(source, *args, **kwargs) |
java | public static ExtensionElement parseExtensionElement(String elementName, String namespace,
XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
ParserUtils.assertAtStartTag(parser);
// See if a provider is registered to handle the extension.
ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getExtensionProvider(elementName, namespace);
if (provider != null) {
return provider.parse(parser, outerXmlEnvironment);
}
// No providers registered, so use a default extension.
return StandardExtensionElementProvider.INSTANCE.parse(parser, outerXmlEnvironment);
} |
python | def check_calling_sequence(name, function_name, function, possible_variables):
"""
Check the calling sequence for the function looking for the variables specified.
One or more of the variables can be in the calling sequence. Note that the
order of the variables will be enforced.
It will also enforce that the first parameter in the calling sequence is called 'self'.
:param function: the function to check
:param possible_variables: a list of variables to check, The order is important, and will be enforced
:return: a tuple containing the list of found variables, and the name of the other parameters in the calling
sequence
"""
# Get calling sequence
# If the function has been memoized, it will have a "input_object" member
try:
calling_sequence = inspect.getargspec(function.input_object).args
except AttributeError:
# This might happen if the function is with memoization
calling_sequence = inspect.getargspec(function).args
assert calling_sequence[0] == 'self', "Wrong syntax for 'evaluate' in %s. The first argument " \
"should be called 'self'." % name
# Figure out how many variables are used
variables = filter(lambda var: var in possible_variables, calling_sequence)
# Check that they actually make sense. They must be used in the same order
# as specified in possible_variables
assert len(variables) > 0, "The name of the variables for 'evaluate' in %s must be one or more " \
"among %s, instead of %s" % (name, ','.join(possible_variables), ",".join(variables))
if variables != possible_variables[:len(variables)]:
raise AssertionError("The variables %s are out of order in '%s' of %s. Should be %s."
% (",".join(variables), function_name, name, possible_variables[:len(variables)]))
other_parameters = filter(lambda var: var not in variables and var != 'self', calling_sequence)
return variables, other_parameters |
java | public void decode(AsnInputStream ais) throws ParseException {
this.dialogTermitationPermission = false;
this.originatingTransactionId = null;
this.dp = null;
this.component = null;
try {
if (ais.getTag() == TCQueryMessage._TAG_QUERY_WITH_PERM)
dialogTermitationPermission = true;
else
dialogTermitationPermission = false;
AsnInputStream localAis = ais.readSequenceStream();
// transaction portion
TransactionID tid = TcapFactory.readTransactionID(localAis);
if (tid.getFirstElem() == null || tid.getSecondElem() != null) {
throw new ParseException(PAbortCause.BadlyStructuredTransactionPortion,
"Error decoding TCQueryMessage: transactionId must contain only one transactionId");
}
this.originatingTransactionId = tid.getFirstElem();
// dialog portion
if (localAis.available() == 0) {
throw new ParseException(PAbortCause.UnrecognizedDialoguePortionID,
"Error decoding TCQueryMessage: neither dialog no component portion is found");
}
int tag = localAis.readTag();
if (tag == DialogPortion._TAG_DIALOG_PORTION) {
this.dp = TcapFactory.createDialogPortion(localAis);
if (localAis.available() == 0)
return;
tag = localAis.readTag();
}
// component portion
this.component = TcapFactory.readComponents(localAis);
} catch (IOException e) {
throw new ParseException(PAbortCause.BadlyStructuredDialoguePortion, "IOException while decoding TCQueryMessage: " + e.getMessage(), e);
} catch (AsnException e) {
throw new ParseException(PAbortCause.BadlyStructuredDialoguePortion, "AsnException while decoding TCQueryMessage: " + e.getMessage(), e);
}
} |
java | @Override
public void releaseJsMessage()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.entry(this, tc, "releaseJsMessage");
}
// We check to see if it is safe to remove a non persistent msg now. i.e. the asynchronous
// gap between the commit add and the spilling to disk for store_maybe.
// A best effort nonpersistent msg wil never get spilled to disk so we need to
// check that we don't remove a reference to one.
if (getReliability().compareTo(Reliability.BEST_EFFORT_NONPERSISTENT) > 0 && isPersistentRepresentationStable())
{
synchronized (this) // we don't want to take the msg away from underneath someone
{
softReferenceMsg = new SoftReference<JsMessage>(msg);
msg = null;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.exit(this, tc, "releaseJsMessage");
}
} |
java | protected void computePsiDataPsiGradient(GrayF32 image1, GrayF32 image2,
GrayF32 deriv1x, GrayF32 deriv1y,
GrayF32 deriv2x, GrayF32 deriv2y,
GrayF32 deriv2xx, GrayF32 deriv2yy, GrayF32 deriv2xy,
GrayF32 du, GrayF32 dv,
GrayF32 psiData, GrayF32 psiGradient ) {
int N = image1.width * image1.height;
for( int i = 0; i < N; i++ ) {
float du_ = du.data[i];
float dv_ = dv.data[i];
// compute Psi-data
float taylor2 = image2.data[i] + deriv2x.data[i]*du_ + deriv2y.data[i]*dv_;
float v = taylor2 - image1.data[i];
psiData.data[i] = (float)(1.0/(2.0*Math.sqrt(v*v + EPSILON*EPSILON)));
// compute Psi-gradient
float dIx = deriv2x.data[i] + deriv2xx.data[i]*du_ + deriv2xy.data[i]*dv_ - deriv1x.data[i];
float dIy = deriv2y.data[i] + deriv2xy.data[i]*du_ + deriv2yy.data[i]*dv_ - deriv1y.data[i];
float dI2 = dIx*dIx + dIy*dIy;
psiGradient.data[i] = (float)(1.0/(2.0*Math.sqrt(dI2 + EPSILON*EPSILON)));
}
} |
java | public static Structure readStructure(String pdbId, int bioAssemblyId) {
// pre-computed files use lower case PDB IDs
pdbId = pdbId.toLowerCase();
// we just need this to track where to store PDB files
// this checks the PDB_DIR property (and uses a tmp location if not set)
AtomCache cache = new AtomCache();
cache.setUseMmCif(true);
FileParsingParameters p = cache.getFileParsingParams();
// some bio assemblies are large, we want an all atom representation and avoid
// switching to a Calpha-only representation for large molecules
// note, this requires several GB of memory for some of the largest assemblies, such a 1MX4
p.setAtomCaThreshold(Integer.MAX_VALUE);
// parse remark 350
p.setParseBioAssembly(true);
// download missing files
Structure structure = null;
try {
structure = StructureIO.getBiologicalAssembly(pdbId,bioAssemblyId);
} catch (Exception e){
e.printStackTrace();
return null;
}
return structure;
} |
java | public static CommerceWarehouseItem fetchByCPI_CPIU_First(long CProductId,
String CPInstanceUuid,
OrderByComparator<CommerceWarehouseItem> orderByComparator) {
return getPersistence()
.fetchByCPI_CPIU_First(CProductId, CPInstanceUuid,
orderByComparator);
} |
java | private static RuleList parseRuleChain(String description)
throws ParseException {
RuleList result = new RuleList();
// remove trailing ;
if (description.endsWith(";")) {
description = description.substring(0,description.length()-1);
}
String[] rules = SEMI_SEPARATED.split(description);
for (int i = 0; i < rules.length; ++i) {
Rule rule = parseRule(rules[i].trim());
result.hasExplicitBoundingInfo |= rule.integerSamples != null || rule.decimalSamples != null;
result.addRule(rule);
}
return result.finish();
} |
java | protected void addCommand(String label, String help, Command cmd, boolean needsAuth) {
commands.put(label.toUpperCase(), new CommandInfo(cmd, help, needsAuth));
} |
java | @Override
public boolean isDeepMemberOf(IEntityGroup group) throws GroupsException {
return isMemberOf(group) ? true : group.deepContains(this);
} |
python | async def get_initial_offset_async(self): # throws InterruptedException, ExecutionException
"""
Gets the initial offset for processing the partition.
:rtype: str
"""
_logger.info("Calling user-provided initial offset provider %r %r",
self.host.guid, self.partition_id)
starting_checkpoint = await self.host.storage_manager.get_checkpoint_async(self.partition_id)
if not starting_checkpoint:
# No checkpoint was ever stored. Use the initialOffsetProvider instead
# defaults to "-1"
self.offset = self.host.eph_options.initial_offset_provider
self.sequence_number = -1
else:
self.offset = starting_checkpoint.offset
self.sequence_number = starting_checkpoint.sequence_number
_logger.info("%r %r Initial offset/sequenceNumber provided %r/%r",
self.host.guid, self.partition_id, self.offset, self.sequence_number)
return self.offset |
java | private Class<?> resolveClassWithCL(String name) throws ClassNotFoundException {
SecurityManager security = System.getSecurityManager();
if (security != null) {
return Class.forName(name, false, getClassLoader(thisClass));
}
// The platform classloader is null if we failed to get it when using java 9, or if we are
// running with a java level below 9. In those cases, the bootstrap classloader
// is used to resolve the needed class.
// Note that this change is being made to account for the fact that in java 9, classes
// such as java.sql.* (java.sql module) are no longer discoverable through the bootstrap
// classloader. Those classes are now discoverable through the java 9 platform classloader.
// The platform classloader is between the bootstrap classloader and the app classloader.
return Class.forName(name, false, platformClassloader);
} |
python | def get_html(self):
""" Downloads HTML content of page given the page_url"""
if self.use_ghost:
self.url = urljoin("http://", self.url)
import selenium
import selenium.webdriver
driver = selenium.webdriver.PhantomJS(
service_log_path=os.path.devnull)
driver.get(self.url)
page_html = driver.page_source
page_url = driver.current_url
driver.quit()
else:
if self.proxy_url:
print("Using proxy: " + self.proxy_url + "\n")
try:
page = requests.get(self.url, proxies=self.proxies)
if page.status_code != 200:
raise PageLoadError(page.status_code)
except requests.exceptions.MissingSchema:
self.url = "http://" + self.url
page = requests.get(self.url, proxies=self.proxies)
if page.status_code != 200:
raise PageLoadError(page.status_code)
except requests.exceptions.ConnectionError:
raise PageLoadError(None)
try:
page_html = page.text
page_url = page.url
except UnboundLocalError:
raise PageLoadError(None)
self.page_html = page_html
self.page_url = page_url
return (self.page_html, self.page_url) |
python | def check():
""" Checks the long description. """
dist_path = Path(DIST_PATH)
if not dist_path.exists() or not list(dist_path.glob('*')):
print("No distribution files found. Please run 'build' command first")
return
subprocess.check_call(['twine', 'check', 'dist/*']) |
python | def _trade(self, event):
"内部函数"
print('==================================market enging: trade')
print(self.order_handler.order_queue.pending)
print('==================================')
self.order_handler._trade()
print('done') |
java | public Properties appendProperties(Properties properties, File configFile) {
if(!configFile.exists()) {
return properties;
}
return reader.appendProperties(properties, configFile, log);
} |
java | public static byte[] serialize(final Serializable object) {
val outBytes = new ByteArrayOutputStream();
serialize(object, outBytes);
return outBytes.toByteArray();
} |
python | def find_module_defining_flag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: str, name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
registered_flag = self._flags().get(flagname)
if registered_flag is None:
return default
for module, flags in six.iteritems(self.flags_by_module_dict()):
for flag in flags:
# It must compare the flag with the one in _flags. This is because a
# flag might be overridden only for its long name (or short name),
# and only its short name (or long name) is considered registered.
if (flag.name == registered_flag.name and
flag.short_name == registered_flag.short_name):
return module
return default |
java | private void computeCBLOFs(Relation<O> relation, NumberVectorDistanceFunction<? super O> distance, WritableDoubleDataStore cblofs, DoubleMinMax cblofMinMax, List<? extends Cluster<MeanModel>> largeClusters, List<? extends Cluster<MeanModel>> smallClusters) {
List<NumberVector> largeClusterMeans = new ArrayList<>(largeClusters.size());
for(Cluster<MeanModel> largeCluster : largeClusters) {
NumberVector mean = ModelUtil.getPrototypeOrCentroid(largeCluster.getModel(), relation, largeCluster.getIDs());
largeClusterMeans.add(mean);
// Compute CBLOF scores for members of large clusters
for(DBIDIter iter = largeCluster.getIDs().iter(); iter.valid(); iter.advance()) {
double cblof = computeLargeClusterCBLOF(relation.get(iter), distance, mean, largeCluster);
storeCBLOFScore(cblofs, cblofMinMax, cblof, iter);
}
}
for(Cluster<MeanModel> smallCluster : smallClusters) {
for(DBIDIter iter = smallCluster.getIDs().iter(); iter.valid(); iter.advance()) {
double cblof = computeSmallClusterCBLOF(relation.get(iter), distance, largeClusterMeans, smallCluster);
storeCBLOFScore(cblofs, cblofMinMax, cblof, iter);
}
}
} |
java | @Override
public boolean onTouchEvent(MotionEvent ev) {
if (null != mGestureDetector) {
return mGestureDetector.onTouchEvent(ev);
} else {
return super.onTouchEvent(ev);
}
} |
python | def create_gemini_db_orig(gemini_vcf, data, gemini_db=None, ped_file=None):
"""Original GEMINI specific data loader, only works with hg19/GRCh37.
"""
if not gemini_db:
gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0]
if not utils.file_exists(gemini_db):
if not vcfutils.vcf_has_variants(gemini_vcf):
return None
with file_transaction(data, gemini_db) as tx_gemini_db:
gemini = config_utils.get_program("gemini", data["config"])
load_opts = ""
if "gemini_allvariants" not in dd.get_tools_on(data):
load_opts += " --passonly"
# For small test files, skip gene table loading which takes a long time
if _is_small_vcf(gemini_vcf):
load_opts += " --skip-gene-tables"
if "/test_automated_output/" in gemini_vcf:
load_opts += " --test-mode"
# Skip CADD or gerp-bp if neither are loaded
gemini_dir = install.get_gemini_dir(data)
for skip_cmd, check_file in [("--skip-cadd", "whole_genome_SNVs.tsv.compressed.gz")]:
if not os.path.exists(os.path.join(gemini_dir, check_file)):
load_opts += " %s" % skip_cmd
# skip gerp-bp which slows down loading
load_opts += " --skip-gerp-bp "
num_cores = data["config"]["algorithm"].get("num_cores", 1)
tmpdir = os.path.dirname(tx_gemini_db)
eanns = _get_effects_flag(data)
# Apply custom resource specifications, allowing use of alternative annotation_dir
resources = config_utils.get_resources("gemini", data["config"])
gemini_opts = " ".join([str(x) for x in resources["options"]]) if resources.get("options") else ""
exports = utils.local_path_export()
cmd = ("{exports} {gemini} {gemini_opts} load {load_opts} "
"-v {gemini_vcf} {eanns} --cores {num_cores} "
"--tempdir {tmpdir} {tx_gemini_db}")
cmd = cmd.format(**locals())
do.run(cmd, "Create gemini database for %s" % gemini_vcf, data)
if ped_file:
cmd = [gemini, "amend", "--sample", ped_file, tx_gemini_db]
do.run(cmd, "Add PED file to gemini database", data)
return gemini_db |
python | def set_handler(self, handler):
"""
set the callback processing object to be used by the receiving thread after receiving the data.User should set
their own callback object setting in order to achieve event driven.
:param handler:the object in callback handler base
:return: ret_error or ret_ok
"""
set_flag = False
for protoc in self._handler_table:
if isinstance(handler, self._handler_table[protoc]["type"]):
self._handler_table[protoc]["obj"] = handler
return RET_OK
if set_flag is False:
return RET_ERROR |
java | public static Project readProject(String argument) throws IOException {
String projectFileName = argument;
File projectFile = new File(projectFileName);
if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) {
try {
return Project.readXML(projectFile);
} catch (SAXException e) {
IOException ioe = new IOException("Couldn't read saved FindBugs project");
ioe.initCause(e);
throw ioe;
}
}
throw new IllegalArgumentException("Can't read project from " + argument);
} |
python | def ACC_calc(TP, TN, FP, FN):
"""
Calculate accuracy.
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: accuracy as float
"""
try:
result = (TP + TN) / (TP + TN + FN + FP)
return result
except ZeroDivisionError:
return "None" |
python | def _convert_reftype_to_jaeger_reftype(ref):
"""Convert opencensus reference types to jaeger reference types."""
if ref == link_module.Type.CHILD_LINKED_SPAN:
return jaeger.SpanRefType.CHILD_OF
if ref == link_module.Type.PARENT_LINKED_SPAN:
return jaeger.SpanRefType.FOLLOWS_FROM
return None |
python | def rm_filesystems(name, device, config='/etc/filesystems'):
'''
.. versionadded:: 2018.3.3
Remove the mount point from the filesystems
CLI Example:
.. code-block:: bash
salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
'''
modified = False
view_lines = []
if 'AIX' not in __grains__['kernel']:
return modified
criteria = _FileSystemsEntry(name=name, dev=device)
try:
fsys_filedict = _filesystems(config, False)
for fsys_view in six.viewitems(fsys_filedict):
try:
if criteria.match(fsys_view):
modified = True
else:
view_lines.append(fsys_view)
except _FileSystemsEntry.ParseError:
view_lines.append(fsys_view)
except (IOError, OSError) as exc:
raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc))
if modified:
try:
with salt.utils.files.fopen(config, 'wb') as ofile:
for fsys_view in view_lines:
entry = fsys_view[1]
mystrg = _FileSystemsEntry.dict_to_lines(entry)
ofile.writelines(salt.utils.data.encode(mystrg))
except (IOError, OSError) as exc:
raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc))
return modified |
java | public static String mask(WildcardPattern pattern, CharSequence input) {
char[] tokens = pattern.getTokens();
int[] types = pattern.getTypes();
char separator = pattern.getSeparator();
int tlen = tokens.length;
int clen = input.length();
char[] masks = new char[clen];
char c;
int tidx = 0;
int cidx = 0;
int trng1;
int trng2;
int ttemp;
int crng1;
int crng2;
int ctmp;
int scnt1;
int scnt2;
while (tidx < tlen && cidx < clen) {
if (types[tidx] == WildcardPattern.LITERAL_TYPE) {
if (tokens[tidx++] != input.charAt(cidx++)) {
return null;
}
} else if (types[tidx] == WildcardPattern.STAR_TYPE) {
trng1 = tidx + 1;
if (trng1 < tlen) {
trng2 = trng1;
for (; trng2 < tlen; trng2++) {
if (types[trng2] == WildcardPattern.EOT_TYPE
|| types[trng2] != WildcardPattern.LITERAL_TYPE) {
break;
}
}
if (trng1 == trng2) {
// prefix*
for (; cidx < clen; cidx++) {
c = input.charAt(cidx);
if (c == separator) {
break;
}
masks[cidx] = c;
}
tidx++;
} else {
// *suffix
ttemp = trng1;
do {
c = input.charAt(cidx);
if (c == separator) {
return null;
}
if (tokens[ttemp] != c) {
ttemp = trng1;
masks[cidx] = c;
} else {
ttemp++;
}
cidx++;
} while (ttemp < trng2 && cidx < clen);
if (ttemp < trng2) {
return null;
}
tidx = trng2;
}
} else {
for (; cidx < clen; cidx++) {
c = input.charAt(cidx);
if (c == separator) {
break;
}
masks[cidx] = c;
}
tidx++;
}
} else if (types[tidx] == WildcardPattern.STAR_STAR_TYPE) {
if (separator != Character.MIN_VALUE) {
trng1 = -1;
trng2 = -1;
for (ttemp = tidx + 1; ttemp < tlen; ttemp++) {
if (trng1 == -1) {
if (types[ttemp] == WildcardPattern.LITERAL_TYPE) {
trng1 = ttemp;
}
} else {
if (types[ttemp] != WildcardPattern.LITERAL_TYPE) {
trng2 = ttemp - 1;
break;
}
}
}
if (trng1 > -1 && trng2 > -1) {
crng2 = cidx;
ttemp = trng1;
while (ttemp <= trng2 && crng2 < clen) {
c = input.charAt(crng2);
if (c != tokens[ttemp]) {
ttemp = trng1;
masks[crng2] = c;
} else {
ttemp++;
}
crng2++;
}
if (ttemp <= trng2) {
tidx = trng2;
if (cidx > 0) {
cidx--;
masks[cidx] = 0; //erase
}
} else {
cidx = crng2;
tidx = trng2 + 1;
}
} else {
tidx++;
scnt1 = 0;
for (ttemp = tidx; ttemp < tlen; ttemp++) {
if (types[ttemp] == WildcardPattern.SEPARATOR_TYPE) {
scnt1++;
}
}
if (scnt1 > 0) {
crng1 = cidx;
crng2 = clen;
scnt2 = 0;
while (crng2 > 0 && crng1 <= crng2--) {
if (input.charAt(crng2) == separator) {
scnt2++;
}
if (scnt1 == scnt2) {
break;
}
}
if (scnt1 == scnt2) {
cidx = crng2;
for (ctmp = crng1; ctmp < crng2; ctmp++) {
masks[ctmp] = input.charAt(ctmp);
}
}
} else {
for (; cidx < clen; cidx++) {
masks[cidx] = input.charAt(cidx);
}
}
}
} else {
for (ctmp = cidx; ctmp < clen; ctmp++) {
masks[ctmp] = input.charAt(ctmp);
}
cidx = clen; //complete
tidx++;
}
} else if (types[tidx] == WildcardPattern.QUESTION_TYPE) {
if (tidx > tlen - 1
|| types[tidx + 1] != WildcardPattern.LITERAL_TYPE
|| tokens[tidx + 1] != input.charAt(cidx)) {
if (separator != Character.MIN_VALUE) {
if (input.charAt(cidx) != separator) {
masks[cidx] = input.charAt(cidx);
cidx++;
}
} else {
masks[cidx] = input.charAt(cidx);
cidx++;
}
}
tidx++;
} else if (types[tidx] == WildcardPattern.PLUS_TYPE) {
if (separator != Character.MIN_VALUE) {
if (input.charAt(cidx) == separator) {
return null;
}
}
masks[cidx] = input.charAt(cidx);
cidx++;
tidx++;
} else if (types[tidx] == WildcardPattern.SEPARATOR_TYPE) {
if (tokens[tidx] != input.charAt(cidx)) {
return null;
}
if (tidx > 0 && cidx > 0 && masks[cidx - 1] > 0
&& (types[tidx - 1] == WildcardPattern.STAR_STAR_TYPE
|| types[tidx - 1] == WildcardPattern.STAR_TYPE)) {
masks[cidx] = input.charAt(cidx);
}
tidx++;
cidx++;
} else if (types[tidx] == WildcardPattern.EOT_TYPE) {
break;
} else {
tidx++;
}
}
if (cidx < clen) {
if (cidx == 0 && tlen > 0 && types[0] == WildcardPattern.STAR_STAR_TYPE) {
for (int end = 0; end < clen; end++) {
if (input.charAt(end) != separator) {
if (end > 0) {
return input.subSequence(end, clen).toString();
}
break;
}
}
return input.toString();
}
return null;
}
if (tidx < tlen) {
for (ttemp = tidx; ttemp < tlen; ttemp++) {
if (types[ttemp] == WildcardPattern.LITERAL_TYPE
|| types[ttemp] == WildcardPattern.PLUS_TYPE
|| types[ttemp] == WildcardPattern.SEPARATOR_TYPE) {
return null;
}
}
}
StringBuilder sb = new StringBuilder(masks.length);
for (char mask : masks) {
if (mask > 0) {
sb.append(mask);
}
}
if (types[0] == WildcardPattern.STAR_STAR_TYPE || types[0] == WildcardPattern.STAR_TYPE) {
for (int end = 0; end < sb.length(); end++) {
if (sb.charAt(end) != separator) {
if (end > 0) {
sb.delete(0, end);
}
break;
}
}
}
return sb.toString();
} |
python | def tsv_import(self, xsv_source, encoding="UTF-8", transforms=None, row_class=DataObject, **kwargs):
"""Imports the contents of a tab-separated data file into this table.
@param xsv_source: tab-separated data file - if a string is given, the file with that name will be
opened, read, and closed; if a file object is given, then that object
will be read as-is, and left for the caller to be closed.
@type xsv_source: string or file
@param transforms: dict of functions by attribute name; if given, each
attribute will be transformed using the corresponding transform; if there is no
matching transform, the attribute will be read as a string (default); the
transform function can also be defined as a (function, default-value) tuple; if
there is an Exception raised by the transform function, then the attribute will
be set to the given default value
@type transforms: dict (optional)
"""
return self._xsv_import(xsv_source, encoding, transforms=transforms, delimiter="\t", row_class=row_class, **kwargs) |
python | def target_heating_level(self):
"""Return target heating level."""
try:
if self.side == 'left':
level = self.device.device_data['leftTargetHeatingLevel']
elif self.side == 'right':
level = self.device.device_data['rightTargetHeatingLevel']
return level
except TypeError:
return None |
java | public void initialize(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger) {
initialize(language, typeToProcess, outputType, configPath, posTagger, false);
} |
java | public static Object getAs(Map<String,Object> properties, String strKey, Class<?> classData, Object objDefault)
{
if (properties == null)
return objDefault;
Object objData = properties.get(strKey);
try {
return Converter.convertObjectToDatatype(objData, classData, objDefault);
} catch (Exception ex) {
return null;
}
} |
java | public TransportApiResult<List<FareProduct>> getFareProducts(FareProductQueryOptions options)
{
if (options == null)
{
options = FareProductQueryOptions.defaultQueryOptions();
}
return TransportApiClientCalls.getFareProducts(tokenComponent, settings, options);
} |
java | @Override
public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inChain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) inRequest;
Principal principal = servletRequest.getUserPrincipal();
HttpSession session = servletRequest.getSession(false);
if (principal != null && session != null) {
String[] roleNames;
synchronized (session) {
roleNames = (String[]) session.getAttribute("roles");
if (roleNames == null) {
roleNames = getRoles(principal, inRequest);
session.setAttribute("roles", roleNames);
}
}
HttpServletRequest wrappedRequest = new RolesRequestWrapper(
servletRequest, principal, roleNames);
inChain.doFilter(wrappedRequest, inResponse);
} else {
inChain.doFilter(inRequest, inResponse);
}
} |
python | def load_module(self, filename):
'''Load a benchmark module from file'''
if not isinstance(filename, string_types):
return filename
basename = os.path.splitext(os.path.basename(filename))[0]
basename = basename.replace('.bench', '')
modulename = 'benchmarks.{0}'.format(basename)
return load_module(modulename, filename) |
java | public Observable<KeyBundle> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) {
return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).map(new Func1<ServiceResponse<KeyBundle>, KeyBundle>() {
@Override
public KeyBundle call(ServiceResponse<KeyBundle> response) {
return response.body();
}
});
} |
java | public void marshall(DecisionTaskCompletedEventAttributes decisionTaskCompletedEventAttributes, ProtocolMarshaller protocolMarshaller) {
if (decisionTaskCompletedEventAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(decisionTaskCompletedEventAttributes.getExecutionContext(), EXECUTIONCONTEXT_BINDING);
protocolMarshaller.marshall(decisionTaskCompletedEventAttributes.getScheduledEventId(), SCHEDULEDEVENTID_BINDING);
protocolMarshaller.marshall(decisionTaskCompletedEventAttributes.getStartedEventId(), STARTEDEVENTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @Override
public <K, V> Cache<K, V> getCache(String name) {
final org.apache.shiro.cache.Cache<K, V> shiroCache = SHIRO_CACHE_MANAGER.getCache(name);
return new ShiroCache<K, V>(shiroCache);
} |
java | private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate,
boolean announce) {
mTimePicker.setCurrentItemShowing(index, animateCircle);
TextView labelToAnimate;
switch(index) {
case HOUR_INDEX:
int hours = mTimePicker.getHours();
if (!mIs24HourMode) {
hours = hours % 12;
}
mTimePicker.setContentDescription(mHourPickerDescription + ": " + hours);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, mSelectHours);
}
labelToAnimate = mHourView;
break;
case MINUTE_INDEX:
int minutes = mTimePicker.getMinutes();
mTimePicker.setContentDescription(mMinutePickerDescription + ": " + minutes);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, mSelectMinutes);
}
labelToAnimate = mMinuteView;
break;
default:
int seconds = mTimePicker.getSeconds();
mTimePicker.setContentDescription(mSecondPickerDescription + ": " + seconds);
if (announce) {
Utils.tryAccessibilityAnnounce(mTimePicker, mSelectSeconds);
}
labelToAnimate = mSecondView;
}
int hourColor = (index == HOUR_INDEX) ? mSelectedColor : mUnselectedColor;
int minuteColor = (index == MINUTE_INDEX) ? mSelectedColor : mUnselectedColor;
int secondColor = (index == SECOND_INDEX) ? mSelectedColor : mUnselectedColor;
mHourView.setTextColor(hourColor);
mMinuteView.setTextColor(minuteColor);
mSecondView.setTextColor(secondColor);
ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate, 0.85f, 1.1f);
if (delayLabelAnimate) {
pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY);
}
pulseAnimator.start();
} |
java | public boolean fbml_refreshImgSrc(URL imageUrl)
throws FacebookException, IOException {
return extractBoolean(this.callMethod(FacebookMethod.FBML_REFRESH_IMG_SRC,
new Pair<String, CharSequence>("url",
imageUrl.toString())));
} |
java | private ObjectMapper createObjectMapperWithRootUnWrap() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.addHandler(new CustomDeserializationProblemHandler());
mapper.registerModule(new JodaModule());
return mapper;
} |
java | public static LongGene of(final long min, final long max) {
return of(nextLong(getRandom(), min, max), min, max);
} |
java | public double approximationDistancePAA(double[] ts, int winSize, int paaSize,
double normThreshold) throws Exception {
double resDistance = 0d;
int windowCounter = 0;
double pointsPerWindow = (double) winSize / (double) paaSize;
for (int i = 0; i < ts.length - winSize + 1; i++) {
double[] subseries = Arrays.copyOfRange(ts, i, i + winSize);
if (tsProcessor.stDev(subseries) > normThreshold) {
subseries = tsProcessor.znorm(subseries, normThreshold);
}
double[] paa = tsProcessor.paa(subseries, paaSize);
windowCounter++;
// essentially the distance here is the distance between the segment's
// PAA value and the real TS value
//
double subsequenceDistance = 0.;
for (int j = 0; j < subseries.length; j++) {
int paaIdx = (int) Math.floor(((double) j + 0.5) / (double) pointsPerWindow);
if (paaIdx < 0) {
paaIdx = 0;
}
if (paaIdx > paa.length) {
paaIdx = paa.length - 1;
}
subsequenceDistance = subsequenceDistance + ed.distance(paa[paaIdx], subseries[j]);
}
resDistance = resDistance + subsequenceDistance / subseries.length;
}
return resDistance / (double) windowCounter;
} |
python | def disable_key(key_id, region=None, key=None, keyid=None, profile=None):
'''
Mark key as disabled.
CLI example::
salt myminion boto_kms.disable_key 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.disable_key(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r |
python | def create(cls, name, iplist=None, comment=None):
"""
Create an IP List. It is also possible to add entries by supplying
a list of IPs/networks, although this is optional. You can also
use upload/download to add to the iplist.
:param str name: name of ip list
:param list iplist: list of ipaddress
:param str comment: optional comment
:raises CreateElementFailed: element creation failed with reason
:return: instance with meta
:rtype: IPList
"""
json = {'name': name, 'comment': comment}
result = ElementCreator(cls, json)
if result and iplist is not None:
element = IPList(name)
element.make_request(
CreateElementFailed,
method='create',
resource='ip_address_list',
json={'ip': iplist})
return result |
python | def convolve_hrf(stimfunction,
tr_duration,
hrf_type='double_gamma',
scale_function=True,
temporal_resolution=100.0,
):
""" Convolve the specified hrf with the timecourse.
The output of this is a downsampled convolution of the stimfunction and
the HRF function. If temporal_resolution is 1 / tr_duration then the
output will be the same length as stimfunction. This time course assumes
that slice time correction has occurred and all slices have been aligned
to the middle time point in the TR.
Be aware that if scaling is on and event durations are less than the
duration of a TR then the hrf may or may not come out as anticipated.
This is because very short events would evoke a small absolute response
after convolution but if there are only short events and you scale then
this will look similar to a convolution with longer events. In general
scaling is useful, which is why it is the default, but be aware of this
edge case and if it is a concern, set the scale_function to false.
Parameters
----------
stimfunction : timepoint by feature array
What is the time course of events to be modelled in this
experiment. This can specify one or more timecourses of events.
The events can be weighted or binary
tr_duration : float
How long (in s) between each volume onset
hrf_type : str or list
Takes in a string describing the hrf that ought to be created.
Can instead take in a vector describing the HRF as it was
specified by any function. The default is 'double_gamma' in which
an initial rise and an undershoot are modelled.
scale_function : bool
Do you want to scale the function to a range of 1
temporal_resolution : float
How many elements per second are you modeling for the stimfunction
Returns
----------
signal_function : timepoint by timecourse array
The time course of the HRF convolved with the stimulus function.
This can have multiple time courses specified as different
columns in this array.
"""
# Check if it is timepoint by feature
if stimfunction.shape[0] < stimfunction.shape[1]:
logger.warning('Stimfunction may be the wrong shape')
# How will stimfunction be resized
stride = int(temporal_resolution * tr_duration)
duration = int(stimfunction.shape[0] / stride)
# Generate the hrf to use in the convolution
if hrf_type == 'double_gamma':
hrf = _double_gamma_hrf(temporal_resolution=temporal_resolution)
elif isinstance(hrf_type, list):
hrf = hrf_type
# How many timecourses are there
list_num = stimfunction.shape[1]
# Create signal functions for each list in the stimfunction
for list_counter in range(list_num):
# Perform the convolution
signal_temp = np.convolve(stimfunction[:, list_counter], hrf)
# Down sample the signal function so that it only has one element per
# TR. This assumes that all slices are collected at the same time,
# which is often the result of slice time correction. In other
# words, the output assumes slice time correction
signal_temp = signal_temp[:duration * stride]
signal_vox = signal_temp[int(stride / 2)::stride]
# Scale the function so that the peak response is 1
if scale_function:
signal_vox = signal_vox / np.max(signal_vox)
# Add this function to the stack
if list_counter == 0:
signal_function = np.zeros((len(signal_vox), list_num))
signal_function[:, list_counter] = signal_vox
return signal_function |
java | public PdfTemplate createTemplateWithBarcode(PdfContentByte cb, Color barColor, Color textColor) {
PdfTemplate tp = cb.createTemplate(0, 0);
Rectangle rect = placeBarcode(tp, barColor, textColor);
tp.setBoundingBox(rect);
return tp;
} |
python | def from_user_config(cls):
"""
Initialize the :class:`TaskManager` from the YAML file 'manager.yaml'.
Search first in the working directory and then in the AbiPy configuration directory.
Raises:
RuntimeError if file is not found.
"""
global _USER_CONFIG_TASKMANAGER
if _USER_CONFIG_TASKMANAGER is not None:
return _USER_CONFIG_TASKMANAGER
# Try in the current directory then in user configuration directory.
path = os.path.join(os.getcwd(), cls.YAML_FILE)
if not os.path.exists(path):
path = os.path.join(cls.USER_CONFIG_DIR, cls.YAML_FILE)
if not os.path.exists(path):
raise RuntimeError(colored(
"\nCannot locate %s neither in current directory nor in %s\n"
"!!! PLEASE READ THIS: !!!\n"
"To use AbiPy to run jobs this file must be present\n"
"It provides a description of the cluster/computer you are running on\n"
"Examples are provided in abipy/data/managers." % (cls.YAML_FILE, path), color="red"))
_USER_CONFIG_TASKMANAGER = cls.from_file(path)
return _USER_CONFIG_TASKMANAGER |
python | def format_currency(value, decimals=2):
"""
Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999.95'
>>> format_currency(99.95)
'99.95'
>>> format_currency(100000)
'100,000'
>>> format_currency(1000.00)
'1,000'
>>> format_currency(1000.41)
'1,000.41'
>>> format_currency(23.21, decimals=3)
'23.210'
>>> format_currency(1000, decimals=3)
'1,000'
>>> format_currency(123456789.123456789)
'123,456,789.12'
"""
number, decimal = ((u'%%.%df' % decimals) % value).split(u'.')
parts = []
while len(number) > 3:
part, number = number[-3:], number[:-3]
parts.append(part)
parts.append(number)
parts.reverse()
if int(decimal) == 0:
return u','.join(parts)
else:
return u','.join(parts) + u'.' + decimal |
java | public List<FeatureTileLink> queryForFeatureTableName(
String featureTableName) {
List<FeatureTileLink> results = null;
try {
results = queryForEq(FeatureTileLink.COLUMN_FEATURE_TABLE_NAME,
featureTableName);
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to query for Feature Tile Link objects by Feature Table Name: "
+ featureTableName);
}
return results;
} |
python | def present(
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the cloudwatch alarm exists.
name
Name of the alarm
attributes
A dict of key/value cloudwatch alarm attributes.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
alarm_details = __salt__['boto_cloudwatch.get_alarm'](
name, region, key, keyid, profile
)
# Convert to arn's
for k in ["alarm_actions", "insufficient_data_actions", "ok_actions"]:
if k in attributes:
attributes[k] = __salt__['boto_cloudwatch.convert_to_arn'](
attributes[k], region, key, keyid, profile
)
# Diff the alarm_details with the passed-in attributes, allowing for the
# AWS type transformations
difference = []
if alarm_details:
for k, v in six.iteritems(attributes):
if k not in alarm_details:
difference.append("{0}={1} (new)".format(k, v))
continue
v = salt.utils.data.decode(v)
v2 = salt.utils.data.decode(alarm_details[k])
if v == v2:
continue
if isinstance(v, six.string_types) and v == v2:
continue
if isinstance(v, float) and v == float(v2):
continue
if isinstance(v, int) and v == int(v2):
continue
if isinstance(v, list) and sorted(v) == sorted(v2):
continue
difference.append("{0}='{1}' was: '{2}'".format(k, v, v2))
else:
difference.append("new alarm")
create_or_update_alarm_args = {
"name": name,
"region": region,
"key": key,
"keyid": keyid,
"profile": profile
}
create_or_update_alarm_args.update(attributes)
if alarm_details: # alarm is present. update, or do nothing
# check to see if attributes matches is_present. If so, do nothing.
if not difference:
ret['comment'] = "alarm {0} present and matching".format(name)
return ret
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['diff'] = difference
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
else: # alarm is absent. create it.
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['new'] = attributes
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
return ret |
java | public Request sendRequest(String requestData, RequestCallback callback)
throws RequestException {
StringValidator.throwIfNull("callback", callback);
return doSend(requestData, callback);
} |
python | def componentSelection(self, comp):
"""Toggles the selection of *comp* from the currently active parameter"""
# current row which is selected in auto parameters to all component selection to
indexes = self.selectedIndexes()
index = indexes[0]
self.model().toggleSelection(index, comp) |
java | public static int [] createRemapTable(String [] controlFields, String [] remappedFields) {
// create hash map with remapped fields
HashMap<String,Integer> map = new HashMap<String, Integer>();
for (int index = 0; index < remappedFields.length; index++) {
String field = remappedFields[index];
map.put(field, index);
}
// create remap table
int remap [] = new int[controlFields.length];
for (int index = 0; index < controlFields.length; index++) {
Integer remapIndex = map.get(controlFields[index]);
if(remapIndex == null) {
// no match
remapIndex = -1;
}
remap[index] = remapIndex;
}
return remap;
} |
java | private void removeField(OpcodeStack.Item itm) {
XField xf = itm.getXField();
if (xf != null) {
mapFields.remove(xf.getName());
xf = (XField) itm.getUserValue();
if (xf != null) {
mapFields.remove(xf.getName());
}
if (mapFields.isEmpty()) {
throw new StopOpcodeParsingException();
}
}
} |
python | def unwrap(self, value, session=None):
''' Validates ``value`` and then returns a dictionary with each key in
``value`` mapped to its value unwrapped using ``DictField.value_type``
'''
self.validate_unwrap(value)
ret = {}
for k, v in value.items():
ret[k] = self.value_type.unwrap(v, session=session)
return ret |
java | public Class<?> getRelationshipMetaType(Class<?> clazz, String relationshipName) {
return relationshipMetaTypeMap.get(clazz).get(relationshipName);
} |
java | @Override
public T addAsDirectory(final String path) throws IllegalArgumentException {
// Precondition check
Validate.notNullOrEmpty(path, "path must be specified");
// Delegate and return
return this.addAsDirectory(ArchivePaths.create(path));
} |
java | private void postProcess(ProcessMethodCallback callback, TransactionContext txContext,
InputDatum input, ProcessMethod.ProcessResult result) {
InputContext inputContext = input.getInputContext();
Throwable failureCause = null;
FailureReason.Type failureType = FailureReason.Type.IO_ERROR;
try {
if (result.isSuccess()) {
// If it is a retry input, force the dequeued entries into current transaction.
if (input.getRetry() > 0) {
input.reclaim();
}
txContext.finish();
} else {
failureCause = result.getCause();
failureType = FailureReason.Type.USER;
txContext.abort();
}
} catch (Throwable e) {
LOG.error("Transaction operation failed: {}", e.getMessage(), e);
failureType = FailureReason.Type.IO_ERROR;
if (failureCause == null) {
failureCause = e;
}
try {
if (result.isSuccess()) {
txContext.abort();
}
} catch (Throwable ex) {
LOG.error("Fail to abort transaction: {}", inputContext, ex);
}
}
try {
if (failureCause == null) {
callback.onSuccess(result.getEvent(), inputContext);
} else {
callback.onFailure(result.getEvent(), inputContext,
new FailureReason(failureType, failureCause.getMessage(), failureCause),
createInputAcknowledger(input));
}
} catch (Throwable t) {
LOG.error("Failed to invoke callback.", t);
}
} |
java | public float[] get(int x, int y, float[] storage) {
if (!isInBounds(x, y))
throw new ImageAccessException("Requested pixel is out of bounds");
if (storage == null) {
storage = new float[numBands];
}
int index = getIndex(x, y, 0);
for (int i = 0; i < numBands; i++, index++) {
storage[i] = data[index];
}
return storage;
} |
python | def get_class_members(self, cls_name, cls):
"""Returns the list of class members to document in `cls`.
This function filters the class member to ONLY return those
defined by the class. It drops the inherited ones.
Args:
cls_name: Qualified name of `cls`.
cls: An inspect object of type 'class'.
Yields:
name, member tuples.
"""
for name, member in inspect.getmembers(cls):
# Only show methods and properties presently. In Python 3,
# methods register as isfunction.
is_method = inspect.ismethod(member) or inspect.isfunction(member)
if not (is_method or isinstance(member, property)):
continue
if ((is_method and member.__name__ == "__init__")
or self._should_include_member(name, member)):
yield name, ("%s.%s" % (cls_name, name), member) |
python | def get_items(self, page=1, order_by=None, filters=None):
"""
Fetch database for items matching.
Args:
page (int):
which page will be sliced
slice size is ``self.per_page``.
order_by (str):
a field name to order query by.
filters (dict):
a ``filter name``: ``value`` dict.
Returns:
tuple with:
items, sliced by page*self.per_page
total items without slice
"""
start = (page-1)*self.per_page
query = self.get_query()
if order_by is not None:
query = query.order_by(self._get_field(order_by))
if filters is not None:
query = self._filter(query, filters)
return query.offset(start).limit(self.per_page), self.count(query) |
python | def cytoscape(namespace,command="",PARAMS={},host=cytoscape_host,port=cytoscape_port,method="POST",verbose=False):
"""
General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:param commnand: command to execute. eg. "protein query"
:param PARAMs: a dictionary with the parameters. Check your swagger normaly running on
http://localhost:1234/v1/swaggerUI/swagger-ui/index.html?url=http://localhost:1234/v1/commands/swagger.json
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:param method: type of http call, ie. "POST" or "GET" or "HELP".
:param verbose: print more information
:returns: For "POST" the data in the content's response. For "GET" None.
eg.
cytoscape("string","pubmed query",{"pubmed":"p53 p21","limit":"50"})
"""
if (method == "GET") or (method == "G"):
P=[]
for p in PARAMS.keys():
v=str(PARAMS[p])
v=v.replace(" ","%20")
P.append(str(p)+"="+str(PARAMS[p]))
P="&".join(P)
URL="http://"+str(host)+":"+str(port)+"/v1/commands/"+str(namespace)+"/"+str(command)+"?"+P
if verbose:
print("'"+URL+"'")
sys.stdout.flush()
r = requests.get(url = URL)
CheckResponse(r)
res=None
elif (method == "POST") or (method == "P"):
URL="http://"+str(host)+":"+str(port)+"/v1/commands/"+str(namespace)+"/"+str(command)
r = requests.post(url = URL, json = PARAMS)
CheckResponse(r)
res=r.content
if verbose:
print(res)
res=json.loads(res)
res=res["data"]
elif (method=="HTML") or (method == "H") or (method=="HELP"):
P=[]
for p in PARAMS.keys():
v=str(PARAMS[p])
v=v.replace(" ","%20")
P.append(str(p)+"="+str(PARAMS[p]))
P="&".join(P)
URL="http://"+str(host)+":"+str(port)+"/v1/commands/"+str(namespace)+"/"+str(command)+"?"+P
if verbose:
print("'"+URL+"'")
sys.stdout.flush()
response = urllib2.urlopen(URL)
#print response
res = response.read()
print(res)
sys.stdout.flush()
return res |
java | protected void handleSimpleCORS(
final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain)
throws IOException, ServletException {
CorsFilter.CORSRequestType requestType = checkRequestType(request);
if (!(requestType == CorsFilter.CORSRequestType.SIMPLE
|| requestType == CorsFilter.CORSRequestType.ACTUAL)) {
throw new IllegalArgumentException(
"Expects a HttpServletRequest object of type "
+ CorsFilter.CORSRequestType.SIMPLE
+ " or "
+ CorsFilter.CORSRequestType.ACTUAL);
}
final String originOrNull = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
log.debug("Request origin: {}", originOrNull);
final String origin = originOrNull == null ? "" : originOrNull.toLowerCase(Locale.ENGLISH);
final String methodOrNull = request.getMethod();
log.debug("Request method: {}", methodOrNull);
final String method = methodOrNull == null ? "" : methodOrNull.toUpperCase(Locale.ENGLISH);
// Section 6.1.2
if (!isOriginAllowed(origin)) {
handleInvalidCORS(request, response, filterChain);
return;
}
if (!allowedHttpMethods.contains(method)) {
handleInvalidCORS(request, response, filterChain);
return;
}
// Section 6.1.3
// Add a single Access-Control-Allow-Origin header.
if (anyOriginAllowed && !supportsCredentials) {
// If resource doesn't support credentials and if any origin is
// allowed
// to make CORS request, return header with '*'.
response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, "*");
} else {
// If the resource supports credentials add a single
// Access-Control-Allow-Origin header, with the value of the Origin
// header as value.
response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, origin);
}
// Section 6.1.3
// If the resource supports credentials, add a single
// Access-Control-Allow-Credentials header with the case-sensitive
// string "true" as value.
if (supportsCredentials) {
response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
// Section 6.1.4
// If the list of exposed headers is not empty add one or more
// Access-Control-Expose-Headers headers, with as values the header
// field names given in the list of exposed headers.
if ((exposedHeaders != null) && (exposedHeaders.size() > 0)) {
String exposedHeadersString = join(exposedHeaders, ",");
response.addHeader(
CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString);
}
// Indicate the response depends on the origin
response.addHeader(CorsFilter.REQUEST_HEADER_VARY, CorsFilter.REQUEST_HEADER_ORIGIN);
// Forward the request down the filter chain.
filterChain.doFilter(request, response);
} |
java | protected int hamming(short[] a, short[] b) {
int distance = 0;
for (int i = 0; i < a.length; i++) {
distance += DescriptorDistance.hamming((a[i]&0xFFFF) ^ (b[i]&0xFFFF));
}
return distance;
} |
java | public synchronized void remove(Entry entry)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "remove", new Object[] { entry });
super.remove(entry);
DestinationHandler dh = (DestinationHandler) entry.data;
if(dh.isMQLink()) removeFromMQLinkIndex(dh);
DestinationEntry destEntry = (DestinationEntry) nameIndex.get(dh.getName());
if(destEntry == entry)
{
nameIndex.remove(dh.getName());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "remove");
} |
java | public LocalDate minusWeeks(int weeks) {
if (weeks == 0) {
return this;
}
long instant = getChronology().weeks().subtract(getLocalMillis(), weeks);
return withLocalMillis(instant);
} |
python | def _update_centers(X, membs, n_clusters, distance):
""" Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable.
"""
centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float)
sse = np.empty(shape=n_clusters, dtype=float)
for clust_id in range(n_clusters):
memb_ids = np.where(membs == clust_id)[0]
X_clust = X[memb_ids,:]
dist = np.empty(shape=memb_ids.shape[0], dtype=float)
for i,x in enumerate(X_clust):
dist[i] = np.sum(scipy.spatial.distance.cdist(X_clust, np.array([x]), distance))
inx_min = np.argmin(dist)
centers[clust_id,:] = X_clust[inx_min,:]
sse[clust_id] = dist[inx_min]
return(centers, sse) |
java | public void setResourceKeys(java.util.Collection<ResourceKey> resourceKeys) {
if (resourceKeys == null) {
this.resourceKeys = null;
return;
}
this.resourceKeys = new com.amazonaws.internal.SdkInternalList<ResourceKey>(resourceKeys);
} |
python | def draw_graph(matrix, clusters, **kwargs):
"""
Visualize the clustering
:param matrix: The unprocessed adjacency matrix
:param clusters: list of tuples containing clusters as returned
by 'get_clusters'
:param kwargs: Additional keyword arguments to be passed to
networkx.draw_networkx
"""
# make a networkx graph from the adjacency matrix
graph = nx.Graph(matrix)
# map node to cluster id for colors
cluster_map = {node: i for i, cluster in enumerate(clusters) for node in cluster}
colors = [cluster_map[i] for i in range(len(graph.nodes()))]
# if colormap not specified in kwargs, use a default
if not kwargs.get("cmap", False):
kwargs["cmap"] = cm.tab20
# draw
nx.draw_networkx(graph, node_color=colors, **kwargs)
axis("off")
show(block=False) |
java | @Override
protected void onNonComplyingFile(File file, String formatted) throws IOException {
CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
sink.write(formatted);
} |
python | def _add_potential(self, potential, parent_tag):
"""
Adds Potentials to the ProbModelXML.
Parameters
----------
potential: dict
Dictionary containing Potential data.
For example: {'role': 'Utility',
'Variables': ['D0', 'D1', 'C0', 'C1'],
'type': 'Tree/ADD',
'UtilityVaribale': 'U1'}
parent_tag: etree Element
etree element which would contain potential tag
For example: <Element Potentials at 0x7f315fc44b08>
<Element Branch at 0x7f315fc44c88>
<Element Branch at 0x7f315fc44d88>
<Element Subpotentials at 0x7f315fc44e48>
Examples
--------
>>> writer = ProbModelXMLWriter(model)
>>> writer._add_potential(potential, parent_tag)
"""
potential_type = potential['type']
try:
potential_tag = etree.SubElement(parent_tag, 'Potential', attrib={
'type': potential['type'], 'role': potential['role']})
except KeyError:
potential_tag = etree.SubElement(parent_tag, 'Potential', attrib={
'type': potential['type']})
self._add_element(potential, 'Comment', potential_tag)
if 'AdditionalProperties' in potential:
self._add_additional_properties(potential_tag, potential['AdditionalProperties'])
if potential_type == "delta":
etree.SubElement(potential_tag, 'Variable', attrib={'name': potential['Variable']})
self._add_element(potential, 'State', potential_tag)
self._add_element(potential, 'StateIndex', potential_tag)
self._add_element(potential, 'NumericValue', potential_tag)
else:
if 'UtilityVariable' in potential:
etree.SubElement(potential_tag, 'UtilityVariable', attrib={
'name': potential['UtilityVariable']})
if 'Variables' in potential:
variable_tag = etree.SubElement(potential_tag, 'Variables')
for var in sorted(potential['Variables']):
etree.SubElement(variable_tag, 'Variable', attrib={'name': var})
for child in sorted(potential['Variables'][var]):
etree.SubElement(variable_tag, 'Variable', attrib={'name': child})
self._add_element(potential, 'Values', potential_tag)
if 'UncertainValues' in potential:
value_tag = etree.SubElement(potential_tag, 'UncertainValues', attrib={})
for value in sorted(potential['UncertainValues']):
try:
etree.SubElement(value_tag, 'Value', attrib={
'distribution': value['distribution'],
'name': value['name']}).text = value['value']
except KeyError:
etree.SubElement(value_tag, 'Value', attrib={
'distribution': value['distribution']}).text = value['value']
if 'TopVariable' in potential:
etree.SubElement(potential_tag, 'TopVariable', attrib={'name': potential['TopVariable']})
if 'Branches' in potential:
branches_tag = etree.SubElement(potential_tag, 'Branches')
for branch in potential['Branches']:
branch_tag = etree.SubElement(branches_tag, 'Branch')
if 'States' in branch:
states_tag = etree.SubElement(branch_tag, 'States')
for state in sorted(branch['States']):
etree.SubElement(states_tag, 'State', attrib={'name': state['name']})
if 'Potential' in branch:
self._add_potential(branch['Potential'], branch_tag)
self._add_element(potential, 'Label', potential_tag)
self._add_element(potential, 'Reference', potential_tag)
if 'Thresholds' in branch:
thresholds_tag = etree.SubElement(branch_tag, 'Thresholds')
for threshold in branch['Thresholds']:
try:
etree.SubElement(thresholds_tag, 'Threshold', attrib={
'value': threshold['value'], 'belongsTo': threshold['belongsTo']})
except KeyError:
etree.SubElement(thresholds_tag, 'Threshold', attrib={
'value': threshold['value']})
self._add_element(potential, 'Model', potential_tag)
self._add_element(potential, 'Coefficients', potential_tag)
self._add_element(potential, 'CovarianceMatrix', potential_tag)
if 'Subpotentials' in potential:
subpotentials = etree.SubElement(potential_tag, 'Subpotentials')
for subpotential in potential['Subpotentials']:
self._add_potential(subpotential, subpotentials)
if 'Potential' in potential:
self._add_potential(potential['Potential'], potential_tag)
if 'NumericVariables' in potential:
numvar_tag = etree.SubElement(potential_tag, 'NumericVariables')
for var in sorted(potential['NumericVariables']):
etree.SubElement(numvar_tag, 'Variable', attrib={'name': var}) |
python | def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
"""
Find the indices of a set of angles into a set of pixels
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels
"""
pix = ang2pix(nside,lon,lat)
return index_pix_in_pixels(pix,pixels,sort,outside) |
java | public synchronized void clear() {
peers.clear();
for(Future<?> timeout : timeouts.values()) {
timeout.cancel(true);
}
timeouts.clear();
} |
java | private void setTypeString(final String type) {
if (type == null) {
this.type = null;
} else if (type.equalsIgnoreCase("WARN")) {
this.type = Type.WARN;
} else if (type.equalsIgnoreCase("ERROR")) {
this.type = Type.ERROR;
} else if (type.equalsIgnoreCase("DEBUG")) {
this.type = Type.DEBUG;
} else if (type.equalsIgnoreCase("INFO")) {
this.type = Type.INFO;
}
} |
python | def get_db_prep_value(self, value, connection=None, prepared=False):
"""Returns field's value prepared for interacting with the database
backend.
Used by the default implementations of ``get_db_prep_save``and
`get_db_prep_lookup```
"""
if not value:
return
if prepared:
return value
else:
assert(isinstance(value, list) or isinstance(value, tuple))
return self.separator.join([unicode(s) for s in value]) |
java | public void excludeStandardObjectNames() {
String[] names = { "Object", "Object.prototype",
"Function", "Function.prototype",
"String", "String.prototype",
"Math", // no Math.prototype
"Array", "Array.prototype",
"Error", "Error.prototype",
"Number", "Number.prototype",
"Date", "Date.prototype",
"RegExp", "RegExp.prototype",
"Script", "Script.prototype",
"Continuation", "Continuation.prototype",
};
for (int i=0; i < names.length; i++) {
addExcludedName(names[i]);
}
String[] optionalNames = {
"XML", "XML.prototype",
"XMLList", "XMLList.prototype",
};
for (int i=0; i < optionalNames.length; i++) {
addOptionalExcludedName(optionalNames[i]);
}
} |
java | public void onClose(Session session, CloseReason closeReason) {
if (getOnCloseHandle() != null) {
callMethod(getOnCloseHandle(), getOnCloseParameters(), session, true, closeReason);
}
} |
python | def transit_export_key(self, name, key_type, version=None, mount_point='transit'):
"""GET /<mount_point>/export/<key_type>/<name>(/<version>)
:param name:
:type name:
:param key_type:
:type key_type:
:param version:
:type version:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
if version is not None:
url = '/v1/{0}/export/{1}/{2}/{3}'.format(mount_point, key_type, name, version)
else:
url = '/v1/{0}/export/{1}/{2}'.format(mount_point, key_type, name)
return self._adapter.get(url).json() |
java | public ListTopicsResult withTopics(Topic... topics) {
if (this.topics == null) {
setTopics(new com.amazonaws.internal.SdkInternalList<Topic>(topics.length));
}
for (Topic ele : topics) {
this.topics.add(ele);
}
return this;
} |
python | def get_relationships_by_genus_type_for_source(self, source_id=None, relationship_genus_type=None):
"""Gets a ``RelationshipList`` corresponding to the given peer ``Id`` and relationship genus ``Type.
Relationships`` of any genus derived from the given genus are
returned.
In plenary mode, the returned list contains all of the
relationships corresponding to the given peer, including
duplicates, or an error results if a relationship is
inaccessible. Otherwise, inaccessible ``Relationships`` may be
omitted from the list and may present the elements in any order
including returning a unique set.
In effective mode, relationships are returned that are currently
effective. In any effective mode, effective relationships and
those currently expired are returned.
arg: source_id (osid.id.Id): a peer ``Id``
arg: relationship_genus_type (osid.type.Type): a relationship
genus type
return: (osid.relationship.RelationshipList) - the relationships
raise: NullArgument - ``source_id`` or
``relationship_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
if source_id is None or relationship_genus_type is None:
raise NullArgument()
url_path = ('/handcar/services/relationship/families/' +
self._catalog_idstr + '/relationships?genustypeid=' +
relationship_genus_type.get_identifier + '?sourceid=' +
str(source_id))
return objects.RelationshipList(self._get_request(url_path)) |
python | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_all_data()[dest] = contents |
java | @Override
public synchronized void upload(File fileToUpload, String filename,
String contents, String comment) throws Exception {
this.upload(new FileInputStream(fileToUpload), filename, contents, comment);
} |
python | def to_xarray(input):
'''Convert climlab input to xarray format.
If input is a climlab.Field object, return xarray.DataArray
If input is a dictionary (e.g. process.state or process.diagnostics),
return xarray.Dataset object with all spatial axes,
including 'bounds' axes indicating cell boundaries in each spatial dimension.
Any items in the dictionary that are not instances of climlab.Field
are ignored.'''
from climlab.domain.field import Field
if isinstance(input, Field):
return Field_to_xarray(input)
elif isinstance(input, dict):
return state_to_xarray(input)
else:
raise TypeError('input must be Field object or dictionary of Field objects') |
java | public ServiceFuture<List<ResourceMetricInner>> listMultiRolePoolInstanceMetricsAsync(final String resourceGroupName, final String name, final String instance, final Boolean details, final ListOperationCallback<ResourceMetricInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listMultiRolePoolInstanceMetricsSinglePageAsync(resourceGroupName, name, instance, details),
new Func1<String, Observable<ServiceResponse<Page<ResourceMetricInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceMetricInner>>> call(String nextPageLink) {
return listMultiRolePoolInstanceMetricsNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
} |
java | public void dissociateConnections() throws ResourceException
{
// We don't call cleanup(), as cleanup() could be doing additional contracts
// with the physical connection
for (HelloWorldConnectionImpl connection : connections)
{
connection.setManagedConnection(null);
}
connections.clear();
} |
python | def _metaconfigure(self, argv=None):
"""Initialize metaconfig for provisioning self."""
metaconfig = self._get_metaconfig_class()
if not metaconfig:
return
if self.__class__ is metaconfig:
# don't get too meta
return
override = {
'conflict_handler': 'resolve',
'add_help': False,
'prog': self._parser_kwargs.get('prog'),
}
self._metaconf = metaconfig(**override)
metaparser = self._metaconf.build_parser(
options=self._metaconf._options, permissive=False, **override)
self._parser_kwargs.setdefault('parents', [])
self._parser_kwargs['parents'].append(metaparser)
self._metaconf._values = self._metaconf.load_options(
argv=argv)
self._metaconf.provision(self) |
python | def get_project_export(self, project_id):
""" Get project info for export """
try:
result = self._request('/getprojectexport/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] |
java | void start(CmdArgs args) {
String graphLocation = args.get("graph.location", "");
String propLocation = args.get("measurement.location", "");
boolean cleanGraph = args.getBool("measurement.clean", false);
String summaryLocation = args.get("measurement.summaryfile", "");
String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(new Date());
put("measurement.timestamp", timeStamp);
if (isEmpty(propLocation)) {
propLocation = "measurement" + timeStamp + ".properties";
}
seed = args.getLong("measurement.seed", 123);
put("measurement.gitinfo", args.get("measurement.gitinfo", ""));
int count = args.getInt("measurement.count", 5000);
GraphHopper hopper = new GraphHopperOSM() {
@Override
protected void prepareCH() {
StopWatch sw = new StopWatch().start();
super.prepareCH();
// note that we measure the total time of all (possibly edge&node) CH preparations
put(Parameters.CH.PREPARE + "time", sw.stop().getMillis());
int edges = getGraphHopperStorage().getEdges();
if (!getCHFactoryDecorator().getNodeBasedWeightings().isEmpty()) {
Weighting weighting = getCHFactoryDecorator().getNodeBasedWeightings().get(0);
int edgesAndShortcuts = getGraphHopperStorage().getGraph(CHGraph.class, weighting).getEdges();
put(Parameters.CH.PREPARE + "node.shortcuts", edgesAndShortcuts - edges);
}
if (!getCHFactoryDecorator().getEdgeBasedWeightings().isEmpty()) {
Weighting weighting = getCHFactoryDecorator().getEdgeBasedWeightings().get(0);
int edgesAndShortcuts = getGraphHopperStorage().getGraph(CHGraph.class, weighting).getEdges();
put(Parameters.CH.PREPARE + "edge.shortcuts", edgesAndShortcuts - edges);
}
}
@Override
protected void loadOrPrepareLM() {
StopWatch sw = new StopWatch().start();
super.loadOrPrepareLM();
put(Landmark.PREPARE + "time", sw.stop().getMillis());
}
@Override
protected DataReader importData() throws IOException {
StopWatch sw = new StopWatch().start();
DataReader dr = super.importData();
put("graph.import_time", sw.stop().getSeconds());
return dr;
}
};
hopper.init(args).
forDesktop();
if (cleanGraph) {
hopper.clean();
}
hopper.getCHFactoryDecorator().setDisablingAllowed(true);
hopper.getLMFactoryDecorator().setDisablingAllowed(true);
hopper.importOrLoad();
GraphHopperStorage g = hopper.getGraphHopperStorage();
EncodingManager encodingManager = hopper.getEncodingManager();
if (encodingManager.fetchEdgeEncoders().size() != 1) {
throw new IllegalArgumentException("There has to be exactly one encoder for each measurement");
}
FlagEncoder encoder = encodingManager.fetchEdgeEncoders().get(0);
String vehicleStr = encoder.toString();
StopWatch sw = new StopWatch().start();
try {
maxNode = g.getNodes();
boolean isCH = false;
boolean isLM = false;
GHBitSet allowedEdges = printGraphDetails(g, vehicleStr);
printMiscUnitPerfTests(g, isCH, encoder, count * 100, allowedEdges);
printLocationIndexQuery(g, hopper.getLocationIndex(), count);
printTimeOfRouteQuery(hopper, isCH, isLM, count / 20, "routing", vehicleStr, true, -1, true, false);
if (hopper.getLMFactoryDecorator().isEnabled()) {
System.gc();
isLM = true;
int activeLMCount = 12;
for (; activeLMCount > 3; activeLMCount -= 4) {
printTimeOfRouteQuery(hopper, isCH, isLM, count / 4, "routingLM" + activeLMCount, vehicleStr, true, activeLMCount, true, false);
}
// compareRouting(hopper, vehicleStr, count / 5);
}
if (hopper.getCHFactoryDecorator().isEnabled()) {
isCH = true;
// compareCHWithAndWithoutSOD(hopper, vehicleStr, count/5);
if (hopper.getLMFactoryDecorator().isEnabled()) {
isLM = true;
System.gc();
// try just one constellation, often ~4-6 is best
int lmCount = 5;
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCHLM" + lmCount, vehicleStr, true, lmCount, true, false);
}
isLM = false;
System.gc();
if (!hopper.getCHFactoryDecorator().getNodeBasedWeightings().isEmpty()) {
Weighting weighting = hopper.getCHFactoryDecorator().getNodeBasedWeightings().get(0);
CHGraph lg = g.getGraph(CHGraph.class, weighting);
fillAllowedEdges(lg.getAllEdges(), allowedEdges);
printMiscUnitPerfTests(lg, isCH, encoder, count * 100, allowedEdges);
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCH", vehicleStr, true, -1, true, false);
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCH_no_sod", vehicleStr, true, -1, false, false);
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCH_no_instr", vehicleStr, false, -1, true, false);
}
if (!hopper.getCHFactoryDecorator().getEdgeBasedWeightings().isEmpty()) {
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCH_edge", vehicleStr, true, -1, false, true);
printTimeOfRouteQuery(hopper, isCH, isLM, count, "routingCH_edge_no_instr", vehicleStr, false, -1, false, true);
}
}
} catch (Exception ex) {
logger.error("Problem while measuring " + graphLocation, ex);
put("error", ex.toString());
} finally {
put("gh.gitinfo", Constants.GIT_INFO);
put("measurement.count", count);
put("measurement.seed", seed);
put("measurement.time", sw.stop().getMillis());
System.gc();
put("measurement.totalMB", getTotalMB());
put("measurement.usedMB", getUsedMB());
if (!summaryLocation.trim().isEmpty()) {
writeSummary(summaryLocation, propLocation);
}
storeProperties(graphLocation, propLocation);
}
} |
java | @Override
public void dereferenceLocalisation(LocalizationPoint ptoPMessageItemStream)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "dereferenceLocalisation", new Object[] { ptoPMessageItemStream, this });
_localisationManager.dereferenceLocalisation(ptoPMessageItemStream);
// Reset the reference to the local messages itemstream if it is being removed.
if (ptoPMessageItemStream
.getLocalizingMEUuid()
.equals(_messageProcessor.getMessagingEngineUuid()))
{
_pToPLocalMsgsItemStream = null;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "dereferenceLocalisation");
} |
java | public static int[] arraySlice(int[] source, int start, int count) {
int[] slice = new int[count];
System.arraycopy(source, start, slice, 0, count);
return slice;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.