language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public void onSaveItems(ItemStateChangesLog itemStates)
{
try
{
ChangesItem changesItem = new ChangesItem();
for (ItemState state : itemStates.getAllStates())
{
if (!state.getData().isNode())
{
String nodePath = getPath(state.getData().getQPath().makeParentPath());
Set<String> parentsWithQuota = quotaPersister.getAllParentNodesWithQuota(rName, wsName, nodePath);
for (String parent : parentsWithQuota)
{
changesItem.updateNodeChangedSize(parent, state.getChangedSize());
addPathsWithAsyncUpdate(changesItem, parent);
}
changesItem.updateWorkspaceChangedSize(state.getChangedSize());
}
else
{
addPathsWithUnknownChangedSize(changesItem, state);
}
}
validatePendingChanges(changesItem);
pendingChanges.set(changesItem);
}
catch (ExceededQuotaLimitException e)
{
throw new IllegalStateException(e.getMessage(), e);
}
} |
python | def calc_requiredrelease_v2(self):
"""Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
Basic equation:
:math:`RequiredRelease = NearDischargeMinimumThreshold`
Examples:
As in the examples above, define a short simulation time period first:
>>> from hydpy import pub
>>> pub.timegrids = '2001.03.30', '2001.04.03', '1d'
Prepare the dam model:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> derived.toy.update()
Define a minimum discharge value for a cross section immediately
downstream of 4 mยณ/s for the summer months and of 0 mยณ/s for the
winter months:
>>> neardischargeminimumthreshold(_11_1_12=0.0, _03_31_12=0.0,
... _04_1_12=4.0, _10_31_12=4.0)
As to be expected, the calculated required release is 0.0 mยณ/s
on May 31 and 4.0 mยณ/s on April 1:
>>> model.idx_sim = pub.timegrids.init['2001.03.31']
>>> model.calc_requiredrelease_v2()
>>> fluxes.requiredrelease
requiredrelease(0.0)
>>> model.idx_sim = pub.timegrids.init['2001.04.01']
>>> model.calc_requiredrelease_v2()
>>> fluxes.requiredrelease
requiredrelease(4.0)
"""
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
flu.requiredrelease = con.neardischargeminimumthreshold[
der.toy[self.idx_sim]] |
python | def get_output(self, worker_metadatas):
"""
Build the output entry of the metadata.
:return: list, containing dicts of partial metadata
"""
outputs = []
has_pulp_pull = PLUGIN_PULP_PULL_KEY in self.workflow.exit_results
try:
pulp_sync_results = self.workflow.postbuild_results[PLUGIN_PULP_SYNC_KEY]
crane_registry = pulp_sync_results[0]
except (KeyError, IndexError):
crane_registry = None
for platform in worker_metadatas:
for instance in worker_metadatas[platform]['output']:
instance['buildroot_id'] = '{}-{}'.format(platform, instance['buildroot_id'])
if instance['type'] == 'docker-image':
# update image ID with pulp_pull results;
# necessary when using Pulp < 2.14. Only do this
# when building for a single architecture -- if
# building for many, we know Pulp has schema 2
# support.
if len(worker_metadatas) == 1 and has_pulp_pull:
if self.workflow.builder.image_id is not None:
instance['extra']['docker']['id'] = self.workflow.builder.image_id
# update repositories to point to Crane
if crane_registry:
pulp_pullspecs = []
docker = instance['extra']['docker']
for pullspec in docker['repositories']:
image = ImageName.parse(pullspec)
image.registry = crane_registry.registry
pulp_pullspecs.append(image.to_str())
docker['repositories'] = pulp_pullspecs
outputs.append(instance)
return outputs |
python | def check_deleted_nodes(self):
""" delete imported nodes that are not present in the old database """
imported_nodes = Node.objects.filter(data__contains=['imported'])
deleted_nodes = []
for node in imported_nodes:
if OldNode.objects.filter(pk=node.pk).count() == 0:
user = node.user
deleted_nodes.append(node)
node.delete()
# delete user if there are no other nodes assigned to her
if user.node_set.count() == 0:
user.delete()
if len(deleted_nodes) > 0:
self.message('deleted %d imported nodes from local DB' % len(deleted_nodes))
self.deleted_nodes = deleted_nodes |
java | protected boolean isBNodeReferenced(BNode object) {
Collection<HashMap<QualifiedName, List<Statement>>> contexts = collators.values();
for (HashMap<QualifiedName, List<Statement>> context : contexts) {
for (QualifiedName subject : context.keySet()) {
List<Statement> statements = context.get(subject);
for (Statement statement : statements) {
Value value = statement.getObject();
QualifiedName pred = convertURIToQualifiedName(statement.getPredicate());
if (QUAL_PREDS.contains(pred)) {
continue;
}
if (value instanceof BNode) {
if (value.equals(object)) {
return true;
}
} /* else if (value instanceof javax.xml.namespace.qualifiedName) {
javax.xml.namespace.qualifiedName qualifiedName = (javax.xml.namespace.qualifiedName) value;
if (qualifiedName.getNamespaceURI().equals(BNODE_NS)
&& qualifiedName.getLocalPart().equals(object.getID())) {
return true;
}
} */ else if (value instanceof QualifiedName) {
QualifiedName qualifiedName = (QualifiedName) value;
if (qualifiedName.getNamespaceURI().equals(BNODE_NS)
&& qualifiedName.getLocalPart().equals(object.getID())) {
return true;
}
} else if (value instanceof Resource) {
QualifiedName qualifiedName = convertResourceToQualifiedName((Resource) value);
if (qualifiedName.getNamespaceURI().equals(BNODE_NS)
&& qualifiedName.getLocalPart().equals(object.getID())) {
return true;
}
} else {
}
}
}
}
return false;
} |
java | public static double universalThreshold(ImageGray image , double noiseSigma ) {
int w = image.width;
int h = image.height;
return noiseSigma*Math.sqrt(2*Math.log(Math.max(w,h)));
} |
java | public static <E> void pipe(Iterable<E> iterable, OutputIterator<E> outputIterator) {
dbc.precondition(iterable != null, "cannot call pipe with a null iterable");
new ConsumeIntoOutputIterator<>(outputIterator).apply(iterable.iterator());
} |
python | def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
'''
Waits wrapper that'll wait for the condition to become true, but will
not error if the condition isn't met.
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
timeout (number) : Maximum number of seconds to wait.
sleep (number) : Sleep time to wait between iterations.
Example::
wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(),
timeout=30,
sleep=0.5)
is equivalent to::
end_time = datetime.now() + timedelta(seconds=30)
while datetime.now() < end_time:
try:
if driver.find_element_by_id("success").is_displayed():
break;
except:
pass
time.sleep(0.5)
'''
try:
return wait_until(condition, timeout, sleep)
except:
pass |
python | def init():
"""Initialize the pipeline in maya so everything works
Init environment and load plugins.
This also creates the initial Jukebox Menu entry.
:returns: None
:rtype: None
:raises: None
"""
main.init_environment()
pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN_PATH', ''), BUILTIN_PLUGIN_PATH))
os.environ['JUKEBOX_PLUGIN_PATH'] = pluginpath
try:
maya.standalone.initialize()
jukeboxmaya.STANDALONE_INITIALIZED = True
except RuntimeError as e:
jukeboxmaya.STANDALONE_INITIALIZED = False
if str(e) == "maya.standalone may only be used from an external Python interpreter":
mm = MenuManager.get()
mainmenu = mm.create_menu("Jukebox", tearOff=True)
mm.create_menu("Help", parent=mainmenu, command=show_help)
# load plugins
pmanager = MayaPluginManager.get()
pmanager.load_plugins()
load_mayaplugins() |
java | public HttpResponse doHttpCall(final String urlString,
final String stringToSend) throws IOException {
return this.doHttpCall(urlString, stringToSend, "", "", "", 0,
Collections.<String, String> emptyMap());
} |
python | def _touch_checkpoint(self, check_file):
"""
Alternative way for a pipeline to designate a checkpoint.
:param str check_file: Name or path of file to use as checkpoint.
:return bool: Whether a file was written (equivalent to whether the
checkpoint file already existed).
:raise ValueError: Raise a ValueError if the argument provided as the
checkpoint file is an absolute path and that doesn't correspond
to a location within the main output folder.
"""
if os.path.isabs(check_file):
folder, _ = os.path.split(check_file)
# For raw string comparison, ensure that each path
# bears the final path separator.
other_folder = os.path.join(folder, "")
this_folder = os.path.join(self.outfolder, "")
if other_folder != this_folder:
errmsg = "Path provided as checkpoint file isn't in pipeline " \
"output folder. '{}' is not in '{}'".format(
check_file, self.outfolder)
raise ValueError(errmsg)
fpath = check_file
else:
fpath = pipeline_filepath(self, filename=check_file)
# Create/update timestamp for checkpoint, but base return value on
# whether the action was a simple update or a novel creation.
already_exists = os.path.isfile(fpath)
open(fpath, 'w').close()
action = "Updated" if already_exists else "Created"
print("{} checkpoint file: '{}'".format(action, fpath))
return already_exists |
java | private static Class<?>[] convert(Class<?>[] classes) {
Class<?>[] types = new Class<?>[classes.length];
for (int i = 0; i < types.length; i++) {
types[i] = convert(classes[i]);
}
return types;
} |
python | def load_images(self, search_file, source_file):
"""ๅ ่ฝฝๅพ
ๅน้
ๅพ็."""
self.search_file, self.source_file = search_file, source_file
self.im_search, self.im_source = imread(self.search_file), imread(self.source_file)
# ๅๅงๅๅฏน่ฑก
self.check_macthing_object = CheckKeypointResult(self.im_search, self.im_source) |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case TypesPackage.JVM_SHORT_ANNOTATION_VALUE__VALUES:
getValues().clear();
getValues().addAll((Collection<? extends Short>)newValue);
return;
}
super.eSet(featureID, newValue);
} |
java | protected final String renderTagId(HttpServletRequest request, String tagId, AbstractHtmlState state)
{
assert(_trs.tagId != null);
state.id = getIdForTagId(tagId);
String script = renderDefaultJavaScript(request, state.id);
return script;
} |
java | @Override
public ResultSet getExportedKeys( String catalog,
String schema,
String table ) throws SQLException {
return getImportedKeys(catalog, schema, table); // empty, but same resultsetmetadata
} |
java | public boolean isCallerInRole(String roleName, Object bean)
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
{
Tr.entry(tc, "isCallerInRole, role = " + roleName
+ " EJB = " + bean); //182011
}
// Check whether security is enabled or not. Note, the subclasses
// do override this method to do additional processing and then they
// call super.isCallerInRole which usually causes this code to
// execute. However, the subclass will throw IllegalStateException
// (e.g. MessageDrivenBeanO) if not valid to call isCallerInRole.
boolean inRole; //d444696.2
EJBSecurityCollaborator<?> securityCollaborator = container.ivSecurityCollaborator;
if (securityCollaborator == null) //d444696.2
{
// Security is disabled, so return false for 1.x and 2.x modules to
// ensure pre EJB 3 applications see no behavior change. For EJB 3 modules
// or later, return true so that we are consistent with web container.
BeanMetaData bmd = home.beanMetaData;
if (isTraceOn && tc.isDebugEnabled())
{
Tr.debug(tc, "isCallerInRole called with security disabled for EJB module version = "
+ bmd.ivModuleVersion);
}
inRole = (bmd.ivModuleVersion >= BeanMetaData.J2EE_EJB_VERSION_3_0);
}
else //d444696.2
{
// Pass null EJSDeployedSupport for callback methods. d739835
EJSDeployedSupport s = bean == null ? null : EJSContainer.getMethodContext();
try
{
inRole = isCallerInRole(securityCollaborator, roleName, s);
} catch (RuntimeException ex)
{
FFDCFilter.processException(ex, CLASS_NAME + ".isCallerInRole", "982", this);
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "isCallerInRole collaborator throwing", ex);
throw ex;
}
}
if (isTraceOn && tc.isEntryEnabled()) //d444696.2
{
Tr.exit(tc, "isCallerInRole returning " + inRole);
}
return inRole; //d444696.2
} |
java | public void marshall(StartFlowRequest startFlowRequest, ProtocolMarshaller protocolMarshaller) {
if (startFlowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startFlowRequest.getFlowArn(), FLOWARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public ResourceFormatParser getParserForFormat(final String format) throws UnsupportedFormatException {
try {
return providerOfType(format);
} catch (ExecutionServiceException e) {
throw new UnsupportedFormatException("No provider available to parse format: " + format,e);
}
} |
java | public Waiter<DescribeKeyPairsRequest> keyPairExists() {
return new WaiterBuilder<DescribeKeyPairsRequest, DescribeKeyPairsResult>().withSdkFunction(new DescribeKeyPairsFunction(client))
.withAcceptors(new KeyPairExists.IsTrueMatcher(), new KeyPairExists.IsInvalidKeyPairNotFoundMatcher())
.withDefaultPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(6), new FixedDelayStrategy(5)))
.withExecutorService(executorService).build();
} |
java | public void start() {
if(this.isActive)
return;
if (clock == null) {
throw new IllegalStateException("Clock is not set");
}
this.isActive = true;
logger.info("Starting ");
coreThread.activate();
criticalThread.activate();
for(int i=0;i<workerThreads.length;i++)
workerThreads[i].activate();
for(int i=0;i<criticalWorkerThreads.length;i++)
criticalWorkerThreads[i].activate();
logger.info("Started ");
} |
python | def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the test set
train_sizes : array-like
Relative or absolute numbers of training examples used to generate
the learning curve
ax : matplotlib Axes
Axes object to draw the plot onto, otherwise uses current Axes
Returns
-------
ax: matplotlib Axes
Axes containing the plot
Examples
--------
.. plot:: ../../examples/learning_curve.py
"""
if ax is None:
ax = plt.gca()
ax.grid()
ax.set_title("Learning Curve")
ax.set_xlabel("Training examples")
ax.set_ylabel("Score mean")
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.legend(loc="best")
ax.margins(0.05)
return ax |
python | def get_nodes(self, request, *args, **kwargs):
""" this method might be overridden by other modules (eg: nodeshot.interop.sync) """
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *args, **kwargs)).data |
java | public static int priorityOf(Class<?> someClass) {
while (someClass != null) {
Priority annotation = someClass.getAnnotation(Priority.class);
if (annotation != null) {
return annotation.value();
}
someClass = someClass.getSuperclass();
}
return 0;
} |
java | public Attribute removeAttributeByLocalName(CharSequence name) {
for (Iterator<Attribute> it = event.attributes.iterator(); it.hasNext(); ) {
Attribute attr = it.next();
if (attr.localName.equals(name)) {
it.remove();
return attr;
}
}
return null;
} |
python | def getBalance(self, CorpNum):
""" ํ๋น ํ์ ์์ฌํฌ์ธํธ ํ์ธ
args
CorpNum : ํ์ธํ๊ณ ์ ํ๋ ํ์ ์ฌ์
์๋ฒํธ
return
์์ฌํฌ์ธํธ by float
raise
PopbillException
"""
try:
return linkhub.getBalance(self._getToken(CorpNum))
except LinkhubException as LE:
raise PopbillException(LE.code, LE.message) |
java | private void addExtraHeaders(final ByteBuffer bb,
final Object... extraHeaders) {
for (Object o : extraHeaders) {
if (o instanceof Integer) {
bb.putInt((Integer) o);
} else if (o instanceof byte[]) {
bb.put((byte[]) o);
} else if (o instanceof Long) {
bb.putLong((Long) o);
} else if (o instanceof Short) {
bb.putShort((Short) o);
} else {
assert false : "Unhandled extra header type: " + o.getClass();
}
} |
java | private boolean isNewStep(RouteProgress routeProgress) {
boolean isNewStep = currentStep == null || !currentStep.equals(routeProgress.currentLegProgress().currentStep());
currentStep = routeProgress.currentLegProgress().currentStep();
resetAlertLevels(isNewStep);
return isNewStep;
} |
java | static DeploymentContent of(final URL url) {
return new DeploymentContent() {
@Override
void addContentToOperation(final OperationBuilder builder, final ModelNode op) {
final ModelNode contentNode = op.get(CONTENT);
final ModelNode contentItem = contentNode.get(0);
contentItem.get("url").set(url.toExternalForm());
}
@Override
String resolvedName() {
final String path = url.getPath();
final int index = path.lastIndexOf('/');
if (index >= 0) {
return path.substring(index + 1);
}
return path;
}
@Override
public String toString() {
return String.format("%s(%s)", DeploymentContent.class.getName(), url.toExternalForm());
}
};
} |
python | def comb_jit(N, k):
"""
Numba jitted function that computes N choose k. Return `0` if the
outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0,
or k > N.
Parameters
----------
N : scalar(int)
k : scalar(int)
Returns
-------
val : scalar(int)
"""
# From scipy.special._comb_int_long
# github.com/scipy/scipy/blob/v1.0.0/scipy/special/_comb.pyx
INTP_MAX = np.iinfo(np.intp).max
if N < 0 or k < 0 or k > N:
return 0
if k == 0:
return 1
if k == 1:
return N
if N == INTP_MAX:
return 0
M = N + 1
nterms = min(k, N - k)
val = 1
for j in range(1, nterms + 1):
# Overflow check
if val > INTP_MAX // (M - j):
return 0
val *= M - j
val //= j
return val |
python | def value(self):
"""
Returns the current load average as a value between 0.0 (representing
the *min_load_average* value) and 1.0 (representing the
*max_load_average* value). These default to 0.0 and 1.0 respectively.
"""
load_average_range = self.max_load_average - self.min_load_average
return (self.load_average - self.min_load_average) / load_average_range |
java | public static String getParamTypesString(Class<?>... paramTypes) {
StringBuilder paramTypesList = new StringBuilder("(");
for (int i = 0; i < paramTypes.length; i++) {
paramTypesList.append(paramTypes[i].getSimpleName());
if (i + 1 < paramTypes.length) {
paramTypesList.append(", ");
}
}
return paramTypesList.append(")").toString();
} |
python | def get_unit(unit_id, **kwargs):
"""
Returns a single unit
"""
try:
unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
return JSONObject(unit)
except NoResultFound:
# The dimension does not exist
raise ResourceNotFoundError("Unit %s not found"%(unit_id)) |
java | @Override
protected void searchStep() {
// more solutions to generate ?
if(solutionIterator.hasNext()){
// generate next solution
SolutionType sol = solutionIterator.next();
// update best solution
updateBestSolution(sol);
} else {
// done
stop();
}
} |
python | def login(credentials=None, app_name=None, services=None, client_id=None, make_clients=True,
clear_old_tokens=False, token_dir=DEFAULT_CRED_PATH, **kwargs):
"""Log in to Globus services
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with credential and config information.
By default, looks in ``~/mdf/credentials/globus_login.json``.
Contains ``app_name``, ``services``, and ``client_id`` as described below.
app_name (str): Name of script/client. This will form the name of the token cache file.
**Default**: ``'UNKNOWN'``.
services (list of str): Services to authenticate with.
**Default**: ``[]``.
client_id (str): The ID of the client, given when registered with Globus.
**Default**: The MDF Native Clients ID.
make_clients (bool): If ``True``, will make and return appropriate clients with
generated tokens. If ``False``, will only return authorizers.
**Default**: ``True``.
clear_old_tokens (bool): If ``True``, delete old token file if it exists,
forcing user to re-login. If ``False``, use existing token file if there is one.
**Default**: ``False``.
token_dir (str): The path to the directory to save tokens in and look for
credentials by default. **Default**: ``DEFAULT_CRED_PATH``.
Returns:
dict: The clients and authorizers requested, indexed by service name.
For example, if ``login()`` is told to auth with ``'search'``
then the search client will be in the ``'search'`` field.
Note:
Previously requested tokens (which are cached) will be returned alongside
explicitly requested ones.
"""
NATIVE_CLIENT_ID = "98bfc684-977f-4670-8669-71f8337688e4"
DEFAULT_CRED_FILENAME = "globus_login.json"
def _get_tokens(client, scopes, app_name, force_refresh=False):
token_path = os.path.join(token_dir, app_name + "_tokens.json")
if force_refresh:
if os.path.exists(token_path):
os.remove(token_path)
if os.path.exists(token_path):
with open(token_path, "r") as tf:
try:
tokens = json.load(tf)
# Check that requested scopes are present
# :all scopes should override any scopes with lesser permissions
# Some scopes are returned in multiples and should be separated
existing_scopes = []
for sc in [val["scope"] for val in tokens.values()]:
if " " in sc:
existing_scopes += sc.split(" ")
else:
existing_scopes.append(sc)
permissive_scopes = [scope.replace(":all", "")
for scope in existing_scopes
if scope.endswith(":all")]
missing_scopes = [scope for scope in scopes.split(" ")
if scope not in existing_scopes
and not any([scope.startswith(per_sc)
for per_sc in permissive_scopes])
and not scope.strip() == ""]
# If some scopes are missing, regenerate tokens
# Get tokens for existing scopes and new scopes
if len(missing_scopes) > 0:
scopes = " ".join(existing_scopes + missing_scopes)
os.remove(token_path)
except ValueError:
# Tokens corrupted
os.remove(token_path)
if not os.path.exists(token_path):
try:
os.makedirs(token_dir)
except (IOError, OSError):
pass
client.oauth2_start_flow(requested_scopes=scopes, refresh_tokens=True)
authorize_url = client.oauth2_get_authorize_url()
print("It looks like this is the first time you're accessing this service.",
"\nPlease log in to Globus at this link:\n", authorize_url)
auth_code = input("Copy and paste the authorization code here: ").strip()
# Handle 401s
try:
token_response = client.oauth2_exchange_code_for_tokens(auth_code)
except globus_sdk.GlobusAPIError as e:
if e.http_status == 401:
raise ValueError("\nSorry, that code isn't valid."
" You can try again, or contact support.")
else:
raise
tokens = token_response.by_resource_server
os.umask(0o077)
with open(token_path, "w") as tf:
json.dump(tokens, tf)
print("Thanks! You're now logged in.")
return tokens
# If creds supplied in 'credentials', process
if credentials:
if type(credentials) is str:
try:
with open(credentials) as cred_file:
creds = json.load(cred_file)
except IOError:
try:
creds = json.loads(credentials)
except ValueError:
raise ValueError("Credential string unreadable")
elif type(credentials) is dict:
creds = credentials
else:
try:
with open(os.path.join(os.getcwd(), DEFAULT_CRED_FILENAME)) as cred_file:
creds = json.load(cred_file)
except IOError:
try:
with open(os.path.join(token_dir, DEFAULT_CRED_FILENAME)) as cred_file:
creds = json.load(cred_file)
except IOError:
raise ValueError("Credentials/configuration must be passed as a "
+ "filename string, JSON string, or dictionary, "
+ "or provided in '"
+ DEFAULT_CRED_FILENAME
+ "' or '"
+ token_dir
+ "'.")
app_name = creds.get("app_name")
services = creds.get("services", services)
client_id = creds.get("client_id")
if not app_name:
app_name = "UNKNOWN"
if not services:
services = []
elif isinstance(services, str):
services = [services]
if not client_id:
client_id = NATIVE_CLIENT_ID
native_client = globus_sdk.NativeAppAuthClient(client_id, app_name=app_name)
servs = []
for serv in services:
serv = serv.lower().strip()
if type(serv) is str:
servs += serv.split(" ")
else:
servs += list(serv)
# Translate services into scopes as possible
scopes = " ".join([KNOWN_SCOPES.get(sc, sc) for sc in servs])
all_tokens = _get_tokens(native_client, scopes, app_name, force_refresh=clear_old_tokens)
# Make authorizers with every returned token
all_authorizers = {}
for key, tokens in all_tokens.items():
# TODO: Allow non-Refresh authorizers
try:
all_authorizers[key] = globus_sdk.RefreshTokenAuthorizer(tokens["refresh_token"],
native_client)
except KeyError:
print("Error: Unable to retrieve tokens for '{}'.\n"
"You may need to delete your old tokens and retry.".format(key))
returnables = {}
# Populate clients and named services
# Only translate back services - if user provides scope directly, don't translate back
# ex. transfer => urn:transfer.globus.org:all => transfer,
# but urn:transfer.globus.org:all !=> transfer
for service in servs:
token_key = KNOWN_TOKEN_KEYS.get(service)
# If the .by_resource_server key (token key) for the service was returned
if token_key in all_authorizers.keys():
# If there is an applicable client (all clients have known token key)
# Pop from all_authorizers to remove from final return value
if make_clients and KNOWN_CLIENTS.get(service):
try:
returnables[service] = KNOWN_CLIENTS[service](
authorizer=all_authorizers.pop(token_key),
http_timeout=STD_TIMEOUT)
except globus_sdk.GlobusAPIError as e:
print("Error: Unable to create {} client: {}".format(service, e.message))
# If no applicable client, just translate the key
else:
returnables[service] = all_authorizers.pop(token_key)
# Add authorizers not associated with service to returnables
returnables.update(all_authorizers)
return returnables |
java | protected static SQLEnum value(Class<? extends SQLEnum> clazz,String value) {
if (value == null) {
return null;
}
value=value.trim();
if (valuesCache.containsKey(clazz)){
Map<String,SQLEnum> map2=valuesCache.get(clazz);
if (map2.containsKey(value)){
return map2.get(value);
}
}
return null;
} |
java | public synchronized ArrayList<MapTaskStatistics>
getMapTaskList(Enum mapTaskSortKey, KeyDataType dataType) {
/*
* If mapTaskSortKey is null then use the task id as a key.
*/
if (mapTaskSortKey == null) {
mapTaskSortKey = MapTaskKeys.TASK_ID;
}
if (this._sortedMapTaskListsByKey.get(mapTaskSortKey) == null) {
ArrayList<MapTaskStatistics> newList = (ArrayList<MapTaskStatistics>)this._mapTaskList.clone();
this._sortedMapTaskListsByKey.put(mapTaskSortKey, this.sortMapTasksByKey(newList, mapTaskSortKey, dataType));
}
return this._sortedMapTaskListsByKey.get(mapTaskSortKey);
} |
python | def find(cls, device=None):
"""
Factory method that returns the requested :py:class:`USBDevice` device, or the
first device.
:param device: Tuple describing the USB device to open, as returned
by find_all().
:type device: tuple
:returns: :py:class:`USBDevice` object utilizing the specified device
:raises: :py:class:`~alarmdecoder.util.NoDeviceError`
"""
if not have_pyftdi:
raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.')
cls.find_all()
if len(cls.__devices) == 0:
raise NoDeviceError('No AD2USB devices present.')
if device is None:
device = cls.__devices[0]
vendor, product, sernum, ifcount, description = device
return USBDevice(interface=sernum, vid=vendor, pid=product) |
java | public <E> E get(PartitionKey key, EntityMapper<E> entityMapper) {
return get(key, null, entityMapper);
} |
java | @Override
protected void openConnectionInternal() throws ConnectionException, AuthenticationException {
if (checkoutDirectory == null) {
checkoutDirectory = createCheckoutDirectory();
}
if (checkoutDirectory.exists() && safeCheckout) {
removeCheckoutDirectory();
}
checkoutDirectory.mkdirs();
} |
java | public Observable<ServiceResponse<OcrResult>> recognizePrintedTextWithServiceResponseAsync(boolean detectOrientation, String url, RecognizePrintedTextOptionalParameter recognizePrintedTextOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (url == null) {
throw new IllegalArgumentException("Parameter url is required and cannot be null.");
}
final OcrLanguages language = recognizePrintedTextOptionalParameter != null ? recognizePrintedTextOptionalParameter.language() : null;
return recognizePrintedTextWithServiceResponseAsync(detectOrientation, url, language);
} |
java | public void setSize(int width, int height) {
final float r = width * 0.75f / SIN;
final float y = COS * r;
final float h = r - y;
final float or = height * 0.75f / SIN;
final float oy = COS * or;
final float oh = or - oy;
mRadius = r;
mBaseGlowScale = h > 0 ? Math.min(oh / h, 1.f) : 1.f;
mBounds.set(mBounds.left, mBounds.top, width, (int) Math.min(height, h));
} |
java | private void getMatchingEECerts(ForwardState currentState,
List<CertStore> certStores,
Collection<X509Certificate> eeCerts)
throws IOException
{
if (debug != null) {
debug.println("ForwardBuilder.getMatchingEECerts()...");
}
/*
* Compose a certificate matching rule to filter out
* certs which don't satisfy constraints
*
* First, retrieve clone of current target cert constraints,
* and then add more selection criteria based on current validation
* state. Since selector never changes, cache local copy & reuse.
*/
if (eeSelector == null) {
eeSelector = (X509CertSelector) targetCertConstraints.clone();
/*
* Match on certificate validity date
*/
eeSelector.setCertificateValid(buildParams.date());
/*
* Policy processing optimizations
*/
if (buildParams.explicitPolicyRequired()) {
eeSelector.setPolicy(getMatchingPolicies());
}
/*
* Require EE certs
*/
eeSelector.setBasicConstraints(-2);
}
/* Retrieve matching EE certs from CertStores */
addMatchingCerts(eeSelector, certStores, eeCerts, searchAllCertStores);
} |
python | def run_command_async(self, msg):
'''
:type message_generator: generator of dict
:param message_generator: Generates messages from slack that should be run
:type fire_all: bool
:param fire_all: Whether to also fire messages to the event bus
:type tag: str
:param tag: The tag to send to use to send to the event bus
:type interval: int
:param interval: time to wait between ending a loop and beginning the next
'''
log.debug('Going to run a command asynchronous')
runner_functions = sorted(salt.runner.Runner(__opts__).functions)
# Parse args and kwargs
cmd = msg['cmdline'][0]
args, kwargs = self.parse_args_and_kwargs(msg['cmdline'])
# Check for pillar string representation of dict and convert it to dict
if 'pillar' in kwargs:
kwargs.update(pillar=ast.literal_eval(kwargs['pillar']))
# Check for target. Otherwise assume None
target = msg['target']['target']
# Check for tgt_type. Otherwise assume glob
tgt_type = msg['target']['tgt_type']
log.debug('target_type is: %s', tgt_type)
if cmd in runner_functions:
runner = salt.runner.RunnerClient(__opts__)
log.debug('Command %s will run via runner_functions', cmd)
# pylint is tripping
# pylint: disable=missing-whitespace-after-comma
job_id_dict = runner.asynchronous(cmd, {'args': args, 'kwargs': kwargs})
job_id = job_id_dict['jid']
# Default to trying to run as a client module.
else:
local = salt.client.LocalClient()
log.debug('Command %s will run via local.cmd_async, targeting %s', cmd, target)
log.debug('Running %s, %s, %s, %s, %s', target, cmd, args, kwargs, tgt_type)
# according to https://github.com/saltstack/salt-api/issues/164, tgt_type has changed to expr_form
job_id = local.cmd_async(six.text_type(target), cmd, arg=args, kwarg=kwargs, tgt_type=six.text_type(tgt_type))
log.info('ret from local.cmd_async is %s', job_id)
return job_id |
java | public V remove(Object key) {
clean();
ValueRef<K, V> valueRef = mValues.remove(key);
V value;
if (valueRef != null && (value = valueRef.get()) != null) {
valueRef.clear();
return value;
}
return null;
} |
python | def splitstring(string, splitcharacter=' ', part=None):
"""
Split a string based on a character and get the parts as a list.
:type string: string
:param string: The string to split.
:type splitcharacter: string
:param splitcharacter: The character to split for the string.
:type part: integer
:param part: Get a specific part of the list.
:return: The split string or a specific part of it
:rtype: list or string
>>> splitstring('hello world !')
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', None)
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', None)
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', 0)
'hello'
"""
# If the part is empty
if part in [None, '']:
# Return an array of the splitted text
return str(string).split(splitcharacter)
# Return an array of the splitted text with a specific part
return str(string).split(splitcharacter)[part] |
python | def _get_named_patterns():
"""Returns list of (pattern-name, pattern) tuples"""
resolver = urlresolvers.get_resolver(None)
patterns = sorted([(key, value[0][0][0])
for key, value in resolver.reverse_dict.items()
if isinstance(key, string_types)
])
return patterns |
python | def structure_results(res):
"""Format Elasticsearch result as Python dictionary"""
out = {'hits': {'hits': []}}
keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code',
u'alternativenames', u'asciiname', u'cc2', u'coordinates',
u'country_code2', u'country_code3', u'dem', u'elevation',
u'feature_class', u'feature_code', u'geonameid',
u'modification_date', u'name', u'population', u'timezone']
for i in res:
i_out = {}
for k in keys:
i_out[k] = i[k]
out['hits']['hits'].append(i_out)
return out |
python | def main():
"""The main function."""
# Prepare and run cmdline-parser.
cmdlineParser = argparse.ArgumentParser(
description="Fixes the input files used for pre-processing of Boost.MPL headers.")
cmdlineParser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
help="Be a little bit more verbose.")
cmdlineParser.add_argument("--check-only", dest='checkonly', action='store_true',
help="Only checks if fixing is required.")
cmdlineParser.add_argument(dest='sourceDir', metavar="<source-dir>",
type=to_existing_absolute_path,
help="The source-directory of Boost.")
args = cmdlineParser.parse_args()
# Some verbose debug output.
if args.verbose:
print "Arguments extracted from command-line:"
print " verbose = ", args.verbose
print " check-only = ", args.checkonly
print " source directory = ", args.sourceDir
# The directories for header- and source files of Boost.MPL.
# NOTE: Assuming 'args.sourceDir' is the source-directory of the entire boost project.
headerDir = os.path.join( args.sourceDir, "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "libs", "mpl", "preprocessed" )
# Check that the header/source-directories exist.
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
# Maybe 'args.sourceDir' is not the source-directory of the entire boost project
# but instead of the Boost.MPL git-directory, only?
headerDir = os.path.join( args.sourceDir, "include", "boost", "mpl" )
sourceDir = os.path.join( args.sourceDir, "preprocessed" )
if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
cmdlineParser.print_usage()
print "error: Cannot find Boost.MPL header/source files in given Boost source-directory!"
sys.exit(0)
# Some verbose debug output.
if args.verbose:
print "Chosen header-directory: ", headerDir
print "Chosen source-directory: ", sourceDir
if args.checkonly:
# Check input files for generating pre-processed headers.
result = check_input_files(headerDir, sourceDir, verbose = args.verbose)
if result:
print "Fixing the input-files used for pre-processing of Boost.MPL headers IS required."
else:
print "Fixing the input-files used for pre-processing of Boost.MPL headers is NOT required."
else:
# Fix input files for generating pre-processed headers.
fix_input_files(headerDir, sourceDir, verbose = args.verbose) |
java | @Override
public String getTrimmedPath(String path)
{
if (path == null)
{
return "/";
}
if (!path.startsWith("/"))
{
try
{
path = new URL(path).getPath();
}
catch (MalformedURLException ex)
{
// ignore
Logger.getLogger(JBossWSDestinationRegistryImpl.class).trace(ex);
}
if (!path.startsWith("/")) {
path = "/" + path;
}
}
return path;
} |
java | public static void writeHtmlImagePreloadJavaScript(String url, Appendable out) throws IOException {
out.append("<script type='text/javascript'>\n"
+ " var img=new Image();\n"
+ " img.src=\"");
// Escape for javascript
StringBuilder javascript = new StringBuilder(url.length());
encodeTextInJavaScript(url, javascript);
// Encode for XML attribute
encodeJavaScriptInXhtmlAttribute(javascript, out);
out.append("\";\n"
+ "</script>");
} |
java | public String getSQLColumn(String tabalis, String fieldname) {
return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname))
: (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname)));
} |
java | public static void channelOperationFactory(AbstractBootstrap<?, ?> b,
ChannelOperations.OnSetup opsFactory) {
Objects.requireNonNull(b, "bootstrap");
Objects.requireNonNull(opsFactory, "opsFactory");
b.option(OPS_OPTION, opsFactory);
} |
python | def sample(self, sampling_period, start=None, end=None,
interpolate='previous'):
"""Sampling at regular time periods.
"""
start, end, mask = self._check_boundaries(start, end)
sampling_period = \
self._check_regularization(start, end, sampling_period)
result = []
current_time = start
while current_time <= end:
value = self.get(current_time, interpolate=interpolate)
result.append((current_time, value))
current_time += sampling_period
return result |
python | def request_data(cls, time, site_id, derived=False):
"""Retreive IGRA version 2 data for one station.
Parameters
--------
site_id : str
11-character IGRA2 station identifier.
time : datetime
The date and time of the desired observation. If list of two times is given,
dataframes for all dates within the two dates will be returned.
Returns
-------
:class: `pandas.DataFrame` containing the data.
"""
igra2 = cls()
# Set parameters for data query
if derived:
igra2.ftpsite = igra2.ftpsite + 'derived/derived-por/'
igra2.suffix = igra2.suffix + '-drvd.txt'
else:
igra2.ftpsite = igra2.ftpsite + 'data/data-por/'
igra2.suffix = igra2.suffix + '-data.txt'
if type(time) == datetime.datetime:
igra2.begin_date = time
igra2.end_date = time
else:
igra2.begin_date, igra2.end_date = time
igra2.site_id = site_id
df, headers = igra2._get_data()
return df, headers |
java | public TableRow getRow(final String pos) throws FastOdsException, IOException {
return this.builder.getRow(this, this.appender, pos);
} |
python | def from_file(cls, fn, *args, **kwargs):
"""Constructor to build an AmiraHeader object from a file
:param str fn: Amira file
:return ah: object of class ``AmiraHeader`` containing header metadata
:rtype: ah: :py:class:`ahds.header.AmiraHeader`
"""
return AmiraHeader(get_parsed_data(fn, *args, **kwargs)) |
java | @Override
public String getConnectedMEName() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getConnectedMEName");
String meName = coreConnection.getMeName();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "getConnectedMEName", meName);
return meName;
} |
java | public void updateRowId(int columnIndex, RowId x) throws SQLException {
try {
rsetImpl.updateRowId(columnIndex, x);
} catch (SQLException sqlX) {
FFDCFilter.processException(
sqlX, getClass().getName() + ".updateRowId", "5064", this);
throw WSJdbcUtil.mapException(this, sqlX);
} catch (NullPointerException nullX) {
// No FFDC code needed; we might be closed.
throw runtimeXIfNotClosed(nullX);
} catch (AbstractMethodError methError) {
// No FFDC code needed; wrong JDBC level.
throw AdapterUtil.notSupportedX("ResultSet.updateRowId", methError);
} catch (RuntimeException runX) {
FFDCFilter.processException(
runX, getClass().getName() + ".updateRowId", "5080", this);
if (tc.isDebugEnabled())
Tr.debug(this, tc, "updateRowId", runX);
throw runX;
} catch (Error err) {
FFDCFilter.processException(
err, getClass().getName() + ".updateRowId", "5087", this);
if (tc.isDebugEnabled())
Tr.debug(this, tc, "updateRowId", err);
throw err;
}
} |
python | def get_for(self, query_type, value):
"""
Create a query and run it for the given arg if it doesn't exist, and
return the tweets for the query.
"""
from yacms.twitter.models import Query
lookup = {"type": query_type, "value": value}
query, created = Query.objects.get_or_create(**lookup)
if created:
query.run()
elif not query.interested:
query.interested = True
query.save()
return query.tweets.all() |
java | public static String toHexString(byte[] bytes, boolean isHNF) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex =
String.format("%2s", Integer.toHexString(b & 0xFF)).replace(' ', '0');
if (isHNF)
sb.append(hex);
else
sb.append(new StringBuilder(hex).reverse());
}
return sb.toString();
} |
java | @Subscribe
public void onFailure(Throwable t) {
Toast.makeText(this, t.getMessage(), LENGTH_LONG).show();
} |
python | def clientConnectionFailed(self, connector, reason):
"""Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
_legacy_twisted_log.msg(
"Connection to the AMQP broker failed ({reason})",
reason=reason.value,
logLevel=logging.WARNING,
)
protocol.ReconnectingClientFactory.clientConnectionFailed(
self, connector, reason
) |
java | public Observable<AppServiceCertificateOrderInner> createOrUpdateAsync(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).map(new Func1<ServiceResponse<AppServiceCertificateOrderInner>, AppServiceCertificateOrderInner>() {
@Override
public AppServiceCertificateOrderInner call(ServiceResponse<AppServiceCertificateOrderInner> response) {
return response.body();
}
});
} |
python | def region_interface_areas(regions, areas, voxel_size=1, strel=None):
r"""
Calculates the interfacial area between all pairs of adjecent regions
Parameters
----------
regions : ND-array
An image of the pore space partitioned into individual pore regions.
Note that zeros in the image will not be considered for area
calculation.
areas : array_like
A list containing the areas of each regions, as determined by
``region_surface_area``. Note that the region number and list index
are offset by 1, such that the area for region 1 is stored in
``areas[0]``.
voxel_size : scalar
The resolution of the image, expressed as the length of one side of a
voxel, so the volume of a voxel would be **voxel_size**-cubed. The
default is 1.
strel : array_like
The structuring element used to blur the region. If not provided,
then a spherical element (or disk) with radius 1 is used. See the
docstring for ``mesh_region`` for more details, as this argument is
passed to there.
Returns
-------
result : named_tuple
A named-tuple containing 2 arrays. ``conns`` holds the connectivity
information and ``area`` holds the result for each pair. ``conns`` is
a N-regions by 2 array with each row containing the region number of an
adjacent pair of regions. For instance, if ``conns[0, 0]`` is 0 and
``conns[0, 1]`` is 5, then row 0 of ``area`` contains the interfacial
area shared by regions 0 and 5.
"""
print('_'*60)
print('Finding interfacial areas between each region')
from skimage.morphology import disk, square, ball, cube
im = regions.copy()
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if im.ndim == 2:
cube = square
ball = disk
# Get 'slices' into im for each region
slices = spim.find_objects(im)
# Initialize arrays
Ps = sp.arange(1, sp.amax(im)+1)
sa = sp.zeros_like(Ps, dtype=float)
sa_combined = [] # Difficult to preallocate since number of conns unknown
cn = []
# Start extracting area from im
for i in tqdm(Ps):
reg = i - 1
if slices[reg] is not None:
s = extend_slice(slices[reg], im.shape)
sub_im = im[s]
mask_im = sub_im == i
sa[reg] = areas[reg]
im_w_throats = spim.binary_dilation(input=mask_im,
structure=ball(1))
im_w_throats = im_w_throats*sub_im
Pn = sp.unique(im_w_throats)[1:] - 1
for j in Pn:
if j > reg:
cn.append([reg, j])
merged_region = im[(min(slices[reg][0].start,
slices[j][0].start)):
max(slices[reg][0].stop,
slices[j][0].stop),
(min(slices[reg][1].start,
slices[j][1].start)):
max(slices[reg][1].stop,
slices[j][1].stop)]
merged_region = ((merged_region == reg + 1) +
(merged_region == j + 1))
mesh = mesh_region(region=merged_region, strel=strel)
sa_combined.append(mesh_surface_area(mesh))
# Interfacial area calculation
cn = sp.array(cn)
ia = 0.5 * (sa[cn[:, 0]] + sa[cn[:, 1]] - sa_combined)
ia[ia <= 0] = 1
result = namedtuple('interfacial_areas', ('conns', 'area'))
result.conns = cn
result.area = ia * voxel_size**2
return result |
java | @Override
@FFDCIgnore(value = { RejectedExecutionException.class })
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, PolicyTaskCallback[] callbacks) throws InterruptedException, ExecutionException {
int taskCount = tasks.size();
// Special case to run a single task on the current thread if we can acquire a permit, if a permit is required
if (taskCount == 1) {
boolean havePermit = false;
if (maxPolicy == MaxPolicy.loose || (havePermit = maxConcurrencyConstraint.tryAcquire())) // use current thread
try {
if (state.get() != State.ACTIVE)
throw new RejectedExecutionException(Tr.formatMessage(tc, "CWWKE1202.submit.after.shutdown", identifier));
// startTimeout does not apply because the task starts immediately
PolicyTaskFutureImpl<T> taskFuture = new PolicyTaskFutureImpl<T>(this, tasks.iterator().next(), callbacks == null ? null : callbacks[0], -1);
taskFuture.accept(true);
runTask(taskFuture);
// raise InterruptedException if current thread is interrupted
taskFuture.throwIfInterrupted();
return taskFuture.get();
} finally {
if (havePermit)
transferOrReleasePermit();
}
} else if (taskCount == 0)
throw new IllegalArgumentException();
InvokeAnyLatch latch = new InvokeAnyLatch(taskCount);
ArrayList<PolicyTaskFutureImpl<T>> futures = new ArrayList<PolicyTaskFutureImpl<T>>(taskCount);
try {
// create futures in advance, which gives the callback an opportunity to reject
int t = 0;
for (Callable<T> task : tasks) {
PolicyTaskCallback callback = callbacks == null ? null : callbacks[t++];
PolicyExecutorImpl executor = callback == null ? this : (PolicyExecutorImpl) callback.getExecutor(this);
long startTimeoutNS = callback == null ? startTimeout : callback.getStartTimeout(executor.startTimeout);
futures.add(new PolicyTaskFutureImpl<T>(executor, task, callback, startTimeoutNS, latch));
}
// enqueue all tasks
for (PolicyTaskFutureImpl<T> taskFuture : futures) {
// check if done before enqueuing more tasks
if (latch.getCount() == 0)
break;
taskFuture.executor.enqueue(taskFuture, taskFuture.executor.maxWaitForEnqueueNS.get(), false); // never run on the current thread because it would prevent timeout
}
// wait for completion
return latch.await(-1, futures);
} catch (RejectedExecutionException x) {
if (x.getCause() instanceof InterruptedException) {
throw (InterruptedException) x.getCause();
} else
throw x;
} catch (TimeoutException x) {
throw new RuntimeException(x); // should be unreachable with infinite timeout
} finally {
for (Future<?> f : futures)
f.cancel(true);
}
} |
java | public void deleteSnapshot(DeleteSnapshotRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getSnapshotId(), "request snapshotId should no be empty.");
InternalRequest internalRequest =
this.createRequest(request, HttpMethodName.DELETE, SNAPSHOT_PREFIX, request.getSnapshotId());
invokeHttpClient(internalRequest, AbstractBceResponse.class);
} |
python | def supports_heading_type(self, heading_type):
"""Tests if the given heading type is supported.
arg: heading_type (osid.type.Type): a heading Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``HEADING``
raise: NullArgument - ``heading_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.Metadata.supports_coordinate_type
if self._kwargs['syntax'] not in ['``HEADING``']:
raise errors.IllegalState()
return heading_type in self.get_heading_types |
java | public static boolean isSupportedJDKType(TypeName typeName) {
if (typeName.isPrimitive()) {
return getPrimitiveTransform(typeName) != null;
}
String name = typeName.toString();
if (name.startsWith("java.lang")) {
return getLanguageTransform(typeName) != null;
}
if (name.startsWith("java.util")) {
return getUtilTransform(typeName) != null;
}
if (name.startsWith("java.math")) {
return getMathTransform(typeName) != null;
}
if (name.startsWith("java.net")) {
return getNetTransform(typeName) != null;
}
if (name.startsWith("java.sql")) {
return getSqlTransform(typeName) != null;
}
return false;
} |
java | private void readMbean() {
if (clazz == null) {
return;
}
try {
if (isUnixOS) {
long openFiles = getValue("OpenFileDescriptorCount");
long maxOpenFiles = getValue("MaxFileDescriptorCount");
long freePhysicalMemorySize = getValue("FreePhysicalMemorySize");
long totalPhysicalMemorySize = getValue("TotalPhysicalMemorySize");
long processTime = getValue("ProcessCpuTime");
double processCPULoad = getDoubleValue("ProcessCpuLoad");
double systemCPULoad = getDoubleValue("SystemCpuLoad");
long processors = getValue("AvailableProcessors");
stats.update((int) openFiles, (int) maxOpenFiles, freePhysicalMemorySize, totalPhysicalMemorySize, processTime, (int) processors, processCPULoad, systemCPULoad);
} else if (isWindowsOS) {
long processors = getValue("AvailableProcessors");
double systemCPULoad = readWindowsCPULoad();
long totalPhysicalMemorySize = readWindowsTotalMemory();
long freePhysicalMemorySize = readWindowsFreeMemory();
stats.update(-1, -1, freePhysicalMemorySize, totalPhysicalMemorySize, -1, (int) processors, -1, systemCPULoad);
} else {
long processors = getValue("AvailableProcessors");
stats.update(-1, -1, -1, -1, -1, (int) processors, -1, -1);
}
} catch (Exception e) {
log.warn("Couldn't read value due to", e);
}
} |
python | def performance_measure(y_true, y_pred):
"""
Compute the performance metrics: TP, FP, FN, TN
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
performance_dict : dict
Example:
>>> from seqeval.metrics import performance_measure
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'O', 'B-ORG'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O', 'O'], ['B-PER', 'I-PER', 'O']]
>>> performance_measure(y_true, y_pred)
(3, 3, 1, 4)
"""
performace_dict = dict()
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
performace_dict['TP'] = sum(y_t == y_p for y_t, y_p in zip(y_true, y_pred)
if ((y_t != 'O') or (y_p != 'O')))
performace_dict['FP'] = sum(y_t != y_p for y_t, y_p in zip(y_true, y_pred))
performace_dict['FN'] = sum(((y_t != 'O') and (y_p == 'O'))
for y_t, y_p in zip(y_true, y_pred))
performace_dict['TN'] = sum((y_t == y_p == 'O')
for y_t, y_p in zip(y_true, y_pred))
return performace_dict |
java | public static String deidentifyRight(String str, int size) {
int end = str.length();
int repeat;
if (size > str.length()) {
repeat = str.length();
} else {
repeat = size;
}
return StringUtils.overlay(str, StringUtils.repeat('*', repeat), end - size, end);
} |
python | def _to_power_basis_degree8(nodes1, nodes2):
r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that B |eacute| zout's
`theorem`_ tells us the **intersection polynomial** is degree
:math:`8`. This happens if the two curves have degrees one and eight
or have degrees two and four.
.. note::
This uses a least-squares fit to the function evaluated at the
Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the
coefficients may be less stable than those produced for smaller
degrees.
Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
nodes2 (numpy.ndarray): The nodes in the second curve.
Returns:
numpy.ndarray: ``9``-array of coefficients.
"""
evaluated = [
eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB9
]
return polynomial.polyfit(_CHEB9, evaluated, 8) |
python | def set_tag(self, key, value):
"""
:param key:
:param value:
"""
with self.update_lock:
if key == ext_tags.SAMPLING_PRIORITY and not self._set_sampling_priority(value):
return self
if self.is_sampled():
tag = thrift.make_tag(
key=key,
value=value,
max_length=self.tracer.max_tag_value_length, )
self.tags.append(tag)
return self |
python | def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if isinstance(algorithm, (str, unicode)):
algorithm = dns.name.from_text(algorithm)
if sys.hexversion < 0x02050200 and \
(algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512):
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" requires Python 2.5.2 or later")
try:
return (algorithm.to_digestable(), _hashes[algorithm])
except KeyError:
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" is not supported") |
java | public void choosePathString(String path, boolean resetCallstack, Object[] arguments) throws Exception {
ifAsyncWeCant("call ChoosePathString right now");
if (resetCallstack) {
resetCallstack();
} else {
// ChoosePathString is potentially dangerous since you can call it when the
// stack is
// pretty much in any state. Let's catch one of the worst offenders.
if (state.getCallStack().getCurrentElement().type == PushPopType.Function) {
String funcDetail = "";
Container container = state.getCallStack().getCurrentElement().currentPointer.container;
if (container != null) {
funcDetail = "(" + container.getPath().toString() + ") ";
}
throw new Exception("Story was running a function " + funcDetail + "when you called ChoosePathString("
+ path + ") - this is almost certainly not not what you want! Full stack trace: \n"
+ state.getCallStack().getCallStackTrace());
}
}
state.passArgumentsToEvaluationStack(arguments);
choosePath(new Path(path));
} |
python | def is_static(*p):
""" A static value (does not change at runtime)
which is known at compile time
"""
return all(is_CONST(x) or
is_number(x) or
is_const(x)
for x in p) |
python | def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = Process(
target=subprocess.call,
args=(cmd,),
kwargs={"cwd": cwd, "shell": True, "env": new_environ},
)
worker_process.start()
return worker_process |
python | def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size',
'time_healpy', 'time_self', 'ratio'],
dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in results:
table.add_row(row)
table['time_self'].format = '10.7f'
if HEALPY_INSTALLED:
table['ratio'] = table['time_self'] / table['time_healpy']
table['time_healpy'].format = '10.7f'
table['ratio'].format = '7.2f'
table.pprint(max_lines=-1) |
python | def _check_cpd_inputs(X, rank):
"""Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for CP decomposition.
"""
if X.ndim < 3:
raise ValueError("Array with X.ndim > 2 expected.")
if rank <= 0 or not isinstance(rank, int):
raise ValueError("Rank is invalid.") |
python | def to_rst_(self) -> str:
"""Convert the main dataframe to restructured text
:return: rst data
:rtype: str
:example: ``ds.to_rst_()``
"""
try:
renderer = pytablewriter.RstGridTableWriter
data = self._build_export(renderer)
return data
except Exception as e:
self.err(e, "Can not convert data to restructured text") |
java | @SuppressWarnings("unused")
public static void initialize(Class<?> type, int identification) throws Exception {
Object typeInitializer = TYPE_INITIALIZERS.remove(new Nexus(type, identification));
if (typeInitializer != null) {
typeInitializer.getClass().getMethod("onLoad", Class.class).invoke(typeInitializer, type);
}
} |
python | def add_task(self, task, parent_task_result):
"""
Add a task to run with the specified result from this tasks parent(can be None)
:param task: Task: task that should be run
:param parent_task_result: object: value to be passed to task for setup
"""
self.tasks.append((task, parent_task_result))
self.task_id_to_task[task.id] = task |
java | public ServiceFuture<VirtualMachineScaleSetInner> updateAsync(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetUpdate parameters, final ServiceCallback<VirtualMachineScaleSetInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, parameters), serviceCallback);
} |
java | public Pixel[][] patches(int patchWidth, int patchHeight) {
Pixel[][] patches = new Pixel[(height - patchHeight) * (width - patchWidth)][];
int k = 0;
for (int row = 0; row < height - patchHeight; row++) {
for (int col = 0; col < width - patchWidth; col++) {
patches[k] = patch(col, row, patchWidth, patchHeight);
}
}
return patches;
} |
java | protected void setProcessor(final Processor processor) throws BuildException, NullPointerException {
if (processor == null) {
throw new NullPointerException("processor");
}
if (isReference()) {
throw super.tooManyAttributes();
}
if (this.env == null && !this.newEnvironment) {
this.processor = processor;
} else {
this.processor = processor.changeEnvironment(this.newEnvironment, this.env);
}
} |
python | def send(sms_to, sms_body, **kwargs):
"""
Site: http://iqsms.ru/
API: http://iqsms.ru/api/
"""
headers = {
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD
)).decode("ascii")
}
kwargs.update({
'phone': sms_to,
'text': from_unicode(sms_body),
'sender': kwargs.pop('sms_from', settings.IQSMS_FROM)
})
http = HTTPConnection(kwargs.pop("api_url", "gate.iqsms.ru"))
http.request("GET", "/send/?" + urlencode(kwargs), headers=headers)
response = http.getresponse()
if response.status != 200:
raise IQSMSError(response.reason)
body = response.read().strip()
if '=accepted' not in body:
raise IQSMSError(body)
return int(body.split('=')[0]) |
python | def access_labels(self):
"""List of labels used to access the Port
Returns
-------
list of str
Strings that can be used to access this Port relative to self.root
"""
access_labels = []
for referrer in self.referrers:
referrer_labels = [key for key, val in self.root.labels.items()
if val == referrer]
port_labels = [key for key, val in referrer.labels.items()
if val == self]
if referrer is self.root:
for label in port_labels:
access_labels.append("['{}']".format(label))
for label in itertools.product(referrer_labels, port_labels):
access_labels.append("['{}']".format("']['".join(label)))
return access_labels |
java | public Audio getOgg(String ref) throws IOException {
return getOgg(ref, ResourceLoader.getResourceAsStream(ref));
} |
python | def get_section(file_name, section, separator='='):
'''
Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name
'''
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for key, value in six.iteritems(inifile.get(section, {})):
if key[0] != '#':
ret.update({key: value})
return ret |
python | def bwar_pitch(return_all=False):
"""
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True.
"""
url = "http://www.baseball-reference.com/data/war_daily_pitch.txt"
s = requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
if return_all:
return c
else:
cols_to_keep = ['name_common', 'mlb_ID', 'player_ID', 'year_ID', 'team_ID', 'stint_ID', 'lg_ID',
'G', 'GS', 'RA','xRA', 'BIP', 'BIP_perc','salary', 'ERA_plus', 'WAR_rep', 'WAA',
'WAA_adj','WAR']
return c[cols_to_keep] |
java | public static void d(String msg, Throwable tr) {
assertInitialization();
sLogger.d(msg, tr);
} |
python | def decorate_cls_with_validation(cls,
field_name, # type: str
*validation_func, # type: ValidationFuncs
**kwargs):
# type: (...) -> Type[Any]
"""
This method is equivalent to decorating a class with the `@validate_field` decorator but can be used a posteriori.
:param cls: the class to decorate
:param field_name: the name of the argument to validate or _OUT_KEY for output validation
:param validation_func: the validation function or
list of validation functions to use. A validation function may be a callable, a tuple(callable, help_msg_str),
a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an
implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`.
[mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they
will be transformed to functions automatically.
:param error_type: a subclass of ValidationError to raise in case of validation failure. By default a
ValidationError will be raised with the provided help_msg
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param none_policy: describes how None values should be handled. See `NoneArgPolicy` for the various possibilities.
Default is `NoneArgPolicy.ACCEPT_IF_OPTIONAl_ELSE_REJECT`.
:param kw_context_args: optional contextual information to store in the exception, and that may be also used
to format the help message
:return: the decorated function, that will perform input validation (using `_assert_input_is_valid`) before
executing the function's code everytime it is executed.
"""
error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None),
('help_msg', None),
('none_policy', None)], allow_others=True)
# the rest of keyword arguments is used as context.
kw_context_args = kwargs
if not isclass(cls):
raise TypeError('decorated cls should be a class')
if hasattr(cls, field_name):
# ** A class field with that name exist. Is it a descriptor ?
var = cls.__dict__[field_name] # note: we cannot use getattr here
if hasattr(var, '__set__') and callable(var.__set__):
if isinstance(var, property):
# *** OLD WAY which was losing type hints and default values (see var.__set__ signature) ***
# properties are special beasts: their methods are method-wrappers (CPython) and can not have properties
# so we have to create a wrapper (sic) before sending it to the main wrapping function
# def func(inst, value):
# var.__set__(inst, value)
# *** NEW WAY : more elegant, use directly the setter provided by the user ***
func = var.fset
nb_args = 2
elif ismethod(var.__set__):
# bound method: normal. Let's access to the underlying function
func = var.__set__.__func__
nb_args = 3
else:
# strange.. but lets try to continue
func = var.__set__
nb_args = 3
# retrieve target function signature, check it and retrieve the 3d param
# since signature is "def __set__(self, obj, val)"
func_sig = signature(func)
if len(func_sig.parameters) != nb_args:
raise ValueError("Class field '{}' is a valid class descriptor for class '{}' but it does not implement"
" __set__ with the correct number of parameters, so it is not possible to add "
"validation to it. See https://docs.python.org/3.6/howto/descriptor.html".
format(field_name, cls.__name__))
# extract the correct name
descriptor_arg_name = list(func_sig.parameters.items())[-1][0]
# do the same than in decorate_with_validation but with a class field validator
# new_setter = decorate_with_validation(func, descriptor_arg_name, *validation_func, help_msg=help_msg,
# error_type=error_type, none_policy=none_policy,
# _clazz_field_name_=field_name, **kw_context_args)
# --create the new validator
none_policy = none_policy or NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE
new_validator = _create_function_validator(func, func_sig, descriptor_arg_name, *validation_func,
none_policy=none_policy, error_type=error_type,
help_msg=help_msg,
validated_class=cls, validated_class_field_name=field_name,
**kw_context_args)
# -- create the new setter with validation
new_setter = decorate_with_validators(func, func_signature=func_sig, **{descriptor_arg_name: new_validator})
# replace the old one
if isinstance(var, property):
# properties are special beasts 2
setattr(cls, field_name, var.setter(new_setter))
else:
# do not use type() for python 2 compat
var.__class__.__set__ = new_setter
elif (hasattr(var, '__get__') and callable(var.__get__)) \
or (hasattr(var, '__delete__') and callable(var.__delete__)):
# this is a descriptor but it does not have any setter method: impossible to validate
raise ValueError("Class field '{}' is a valid class descriptor for class '{}' but it does not implement "
"__set__ so it is not possible to add validation to it. See "
"https://docs.python.org/3.6/howto/descriptor.html".format(field_name, cls.__name__))
else:
# this is not a descriptor: unsupported
raise ValueError("Class field '{}.{}' is not a valid class descriptor, see "
"https://docs.python.org/3.6/howto/descriptor.html".format(cls.__name__, field_name))
else:
# ** No class field with that name exist
# ? check for attrs ? > no specific need anymore, this is the same than annotating the constructor
# if hasattr(cls, '__attrs_attrs__'): this was a proof of attrs-defined class
# try to annotate the generated constructor
try:
init_func = cls.__init__
if sys.version_info < (3, 0):
try:
# python 2 - we have to access the inner `im_func`
init_func = cls.__init__.im_func
except AttributeError:
pass
cls.__init__ = decorate_with_validation(init_func, field_name, *validation_func, help_msg=help_msg,
_constructor_of_cls_=cls,
error_type=error_type, none_policy=none_policy, **kw_context_args)
except InvalidNameError:
# the field was not found
# TODO should we also check if a __setattr__ is defined ?
# (for __setattr__ see https://stackoverflow.com/questions/15750522/class-properties-and-setattr/15751159)
# finally raise an error
raise ValueError("@validate_field definition exception: field '{}' can not be found in class '{}', and it "
"is also not an input argument of the __init__ method.".format(field_name, cls.__name__))
return cls |
java | public static void verifySnapshots(
final List<String> directories, final Set<String> snapshotNames) {
FileFilter filter = new SnapshotFilter();
if (!snapshotNames.isEmpty()) {
filter = new SpecificSnapshotFilter(snapshotNames);
}
Map<String, Snapshot> snapshots = new HashMap<String, Snapshot>();
for (String directory : directories) {
SnapshotUtil.retrieveSnapshotFiles(new File(directory), snapshots, filter, true, SnapshotPathType.SNAP_PATH, CONSOLE_LOG);
}
if (snapshots.isEmpty()) {
System.out.println("Snapshot corrupted");
System.out.println("No files found");
}
for (Snapshot s : snapshots.values()) {
System.out.println(SnapshotUtil.generateSnapshotReport(s.getTxnId(), s).getSecond());
}
} |
java | public static AbstractExpression eliminateDuplicates(Collection<AbstractExpression> exprList) {
// Eliminate duplicates by building the map of expression's ids, values.
Map<String, AbstractExpression> subExprMap = new HashMap<String, AbstractExpression>();
for (AbstractExpression subExpr : exprList) {
subExprMap.put(subExpr.m_id, subExpr);
}
// Now reconstruct the expression
return ExpressionUtil.combinePredicates(subExprMap.values());
} |
python | def safe_split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]:
"""
Split long text
:param text:
:param length:
:return:
"""
# TODO: More informative description
temp_text = text
parts = []
while temp_text:
if len(temp_text) > length:
try:
split_pos = temp_text[:length].rindex(' ')
except ValueError:
split_pos = length
if split_pos < length // 4 * 3:
split_pos = length
parts.append(temp_text[:split_pos])
temp_text = temp_text[split_pos:].lstrip()
else:
parts.append(temp_text)
break
return parts |
java | public static <T, E> MultiKindFeedParser<T> create(HttpResponse response,
XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses)
throws IOException, XmlPullParserException {
InputStream content = response.getContent();
try {
Atom.checkContentType(response.getContentType());
XmlPullParser parser = Xml.createParser();
parser.setInput(content, null);
MultiKindFeedParser<T> result =
new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass);
result.setEntryClasses(entryClasses);
return result;
} finally {
content.close();
}
} |
python | def get_status(self):
"""Returns a dictionary containing all relevant status information to be
broadcast across the network."""
return {
"host": self.__hostid,
"status": self._service_status_announced,
"statustext": CommonService.human_readable_state.get(
self._service_status_announced
),
"service": self._service_name,
"serviceclass": self._service_class_name,
"utilization": self._utilization.report(),
"workflows": workflows.version(),
} |
java | private static List<DiscoveryIncomingMessage> collectIncomingMessages(int pTimeout, List<Future<List<DiscoveryIncomingMessage>>> pFutures, LogHandler pLogHandler) throws UnknownHostException {
List<DiscoveryIncomingMessage> ret = new ArrayList<DiscoveryIncomingMessage>();
Set<String> seen = new HashSet<String>();
int nrCouldntSend = 0;
for (Future<List<DiscoveryIncomingMessage>> future : pFutures) {
try {
List<DiscoveryIncomingMessage> inMsgs = future.get(pTimeout + 500 /* some additional buffer */, TimeUnit.MILLISECONDS);
for (DiscoveryIncomingMessage inMsg : inMsgs) {
AgentDetails details = inMsg.getAgentDetails();
String id = details.getAgentId();
// There can be multiples answers with the same message id
if (!seen.contains(id)) {
ret.add(inMsg);
seen.add(id);
}
}
} catch (InterruptedException exp) {
// Try next one ...
} catch (ExecutionException e) {
Throwable exp = e.getCause();
if (exp instanceof CouldntSendDiscoveryPacketException) {
nrCouldntSend++;
pLogHandler.debug("--> Couldnt send discovery message from " +
((CouldntSendDiscoveryPacketException) exp).getAddress() + ": " + exp.getCause());
}
// Didn't worked a given address, which can happen e.g. when multicast is not routed or in other cases
// throw new IOException("Error while performing a discovery call " + e,e);
pLogHandler.debug("--> Exception during lookup: " + e);
} catch (TimeoutException e) {
// Timeout occurred while waiting for the results. So we go to the next one ...
}
}
if (nrCouldntSend == pFutures.size()) {
// No a single discovery message could be send out
throw new UnknownHostException("Cannot send a single multicast recovery request on any multicast enabled interface");
}
return ret;
} |
python | def set_server(self, wsgi_app, fnc_serve=None):
"""
figures out how the wsgi application is to be served
according to config
"""
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
if ssl_config.get("enabled"):
ssl_context["certfile"] = ssl_config.get("cert")
ssl_context["keyfile"] = ssl_config.get("key")
from gevent.pywsgi import WSGIServer
http_server = WSGIServer(
(self.host, self.port),
wsgi_app,
**ssl_context
)
self.log.debug("Serving WSGI via gevent.pywsgi.WSGIServer")
fnc_serve = http_server.serve_forever
elif self.get_config("server") == "uwsgi":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "gunicorn":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "self":
fnc_serve = self.run
# figure out async handler
if self.get_config("async") == "gevent":
# handle async via gevent
import gevent
self.log.debug("Handling wsgi on gevent")
self.worker = gevent.spawn(fnc_serve)
elif self.get_config("async") == "thread":
self.worker = fnc_serve
else:
self.worker = fnc_serve |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.