language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public void marshall(ListRecordHistorySearchFilter listRecordHistorySearchFilter, ProtocolMarshaller protocolMarshaller) {
if (listRecordHistorySearchFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRecordHistorySearchFilter.getKey(), KEY_BINDING);
protocolMarshaller.marshall(listRecordHistorySearchFilter.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def representative_sample(X, num_samples, save=False):
"""Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
"""
X = X.values if hasattr(X, 'values') else np.array(X)
N, M = X.shape
rownums = np.arange(N)
np.random.shuffle(rownums)
idx = AnnoyIndex(M)
for i, row in enumerate(X):
idx.add_item(i, row)
idx.build(int(np.log2(N)) + 1)
if save:
if isinstance(save, basestring):
idxfilename = save
else:
idxfile = tempfile.NamedTemporaryFile(delete=False)
idxfile.close()
idxfilename = idxfile.name
idx.save(idxfilename)
idx = AnnoyIndex(M)
idx.load(idxfile.name)
samples = -1 * np.ones(shape=(num_samples,), dtype=int)
samples[0] = rownums[0]
# FIXME: some integer determined by N and num_samples and distribution
j, num_nns = 0, min(1000, int(num_samples / 2. + 1))
for i in rownums:
if i in samples:
continue
nns = idx.get_nns_by_item(i, num_nns)
# FIXME: pick vector furthest from past K (K > 1) points or outside of a hypercube
# (sized to uniformly fill the space) around the last sample
samples[j + 1] = np.setdiff1d(nns, samples)[-1]
if len(num_nns) < num_samples / 3.:
num_nns = min(N, 1.3 * num_nns)
j += 1
return samples |
python | def get_baudrate_message(baudrate):
"""
Converts a given baud rate value for GW-001/GW-002 to the appropriate message string.
:param Baudrate baudrate:
Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte
(see enum :class:`Baudrate`)
:return: Baud rate message string.
:rtype: str
"""
baudrate_msgs = {
Baudrate.BAUD_AUTO: "auto baudrate",
Baudrate.BAUD_10kBit: "10 kBit/sec",
Baudrate.BAUD_20kBit: "20 kBit/sec",
Baudrate.BAUD_50kBit: "50 kBit/sec",
Baudrate.BAUD_100kBit: "100 kBit/sec",
Baudrate.BAUD_125kBit: "125 kBit/sec",
Baudrate.BAUD_250kBit: "250 kBit/sec",
Baudrate.BAUD_500kBit: "500 kBit/sec",
Baudrate.BAUD_800kBit: "800 kBit/sec",
Baudrate.BAUD_1MBit: "1 MBit/s",
Baudrate.BAUD_USE_BTREX: "BTR Ext is used",
}
return baudrate_msgs.get(baudrate, "BTR is unknown (user specific)") |
python | def substitution_rate(Nref, Nsubstitutions, eps=numpy.spacing(1)):
"""Substitution rate
Parameters
----------
Nref : int >=0
Number of entries in the reference.
Nsubstitutions : int >=0
Number of substitutions.
eps : float
eps.
Default value numpy.spacing(1)
Returns
-------
substitution_rate: float
Substitution rate
"""
return float(Nsubstitutions / (Nref + eps)) |
java | @SuppressWarnings("unchecked")
static <T extends SAMLObject> MessageContext<T> toSamlObject(
AggregatedHttpMessage msg, String name,
Map<String, SamlIdentityProviderConfig> idpConfigs,
@Nullable SamlIdentityProviderConfig defaultIdpConfig) {
requireNonNull(msg, "msg");
requireNonNull(name, "name");
requireNonNull(idpConfigs, "idpConfigs");
final SamlParameters parameters = new SamlParameters(msg);
final T message = (T) fromDeflatedBase64(parameters.getFirstValue(name));
final MessageContext<T> messageContext = new MessageContext<>();
messageContext.setMessage(message);
final Issuer issuer;
if (message instanceof RequestAbstractType) {
issuer = ((RequestAbstractType) message).getIssuer();
} else if (message instanceof StatusResponseType) {
issuer = ((StatusResponseType) message).getIssuer();
} else {
throw new SamlException("invalid message type: " + message.getClass().getSimpleName());
}
// Use the default identity provider config if there's no issuer.
final SamlIdentityProviderConfig config;
if (issuer != null) {
final String idpEntityId = issuer.getValue();
config = idpConfigs.get(idpEntityId);
if (config == null) {
throw new SamlException("a message from unknown identity provider: " + idpEntityId);
}
} else {
if (defaultIdpConfig == null) {
throw new SamlException("failed to get an Issuer element");
}
config = defaultIdpConfig;
}
// If this message is sent via HTTP-redirect binding protocol, its signature parameter should
// be validated.
validateSignature(config.signingCredential(), parameters, name);
final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
if (relayState != null) {
final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
assert context != null;
context.setRelayState(relayState);
}
return messageContext;
} |
python | def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) ) |
java | public static String jsonObjectToReturnString(JSONObject jsonObj)
{
String strReturn = jsonObj.toString();
if (strReturn != null)
if (!strReturn.startsWith("("))
strReturn = "(" + strReturn + ")";
return strReturn;
} |
python | def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_id: The ID of the location to get crimes for.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:return: A ``list`` of :class:`Crime` objects which were snapped to the
:class:`Location` with the specified ID in the given month.
"""
kwargs = {
'location_id': location_id,
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', 'crimes-at-location', **kwargs):
crimes.append(Crime(self, data=c))
return crimes |
java | @Override
public Future<M> getDataFuture() {
try {
return FutureProcessor.completedFuture(getData());
} catch (NotAvailableException ex) {
CompletableFuture future = new CompletableFuture();
future.completeExceptionally(ex);
return future;
}
} |
python | def Rsync(url, tgt_name, tgt_root=None):
"""
RSync a folder.
Args:
url (str): The url of the SOURCE location.
fname (str): The name of the TARGET.
to (str): Path of the target location.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = str(CFG["tmp_dir"])
from benchbuild.utils.cmd import rsync
tgt_dir = local.path(tgt_root) / tgt_name
if not source_required(tgt_dir):
Copy(tgt_dir, ".")
return
rsync("-a", url, tgt_dir)
update_hash(tgt_dir)
Copy(tgt_dir, ".") |
python | def trigger_actions(self, subsystem):
"""
Refresh all modules which subscribed to the given subsystem.
"""
for py3_module, trigger_action in self.udev_consumers[subsystem]:
if trigger_action in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"%s udev event, refresh consumer %s"
% (subsystem, py3_module.module_full_name)
)
py3_module.force_update() |
java | public static Date getDateParameter (
HttpServletRequest req, String name, String invalidDataMessage)
throws DataValidationException
{
String value = getParameter(req, name, false);
if (StringUtil.isBlank(value) ||
DATE_TEMPLATE.equalsIgnoreCase(value)) {
return null;
}
return parseDateParameter(value, invalidDataMessage);
} |
java | MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) {
ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
String tableName = serverErrorMessage.getTable();
String message = serverErrorMessage.getMessage();
Matcher matcher =
Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint")
.matcher(message);
boolean matches = matcher.matches();
if (matches) {
// exception message when adding data that does not match constraint
String columnName = matcher.group(1);
EntityTypeDescription entityTypeDescription =
entityTypeRegistry.getEntityTypeDescription(tableName);
entityTypeDescription.getAttributeDescriptionMap().get(columnName);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' can not be null.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation));
} else {
// exception message when applying constraint on existing data
matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message);
matches = matcher.matches();
if (!matches) {
throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
}
String columnName = matcher.group(1);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' contains null values.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation));
}
} |
python | def tag(self, name, action='ADD', params=None):
"""
Adds a tag to a Indicator/Group/Victim/Security Label
Args:
params:
action:
name: The name of the tag
"""
if not name:
self._tcex.handle_error(925, ['name', 'tag', 'name', 'name', name])
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if action in ['GET', 'ADD', 'DELETE']:
return self.tc_requests.tag(
self.api_type,
self.api_sub_type,
self.unique_id,
name,
action=action,
owner=self.owner,
params=params,
)
self._tcex.handle_error(925, ['action', 'tag', 'action', 'action', action])
return None |
python | def size(col):
"""
Collection function: returns the length of the array or map stored in the column.
:param col: name of column or expression
>>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data'])
>>> df.select(size(df.data)).collect()
[Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.size(_to_java_column(col))) |
python | def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
if self.file_exists(path) or self.dir_exists(path):
self.fs.rm(path)
else:
self.no_such_entity(path) |
java | public BatchWriteItemResponse batchWriteItem(BatchWriteItemRequest request)
throws BceClientException, BceServiceException {
checkNotNull(request, "request should not be null.");
InternalRequest httpRequest = createRequestUnderInstance(HttpMethodName.POST,
MolaDbConstants.URI_TABLE);
httpRequest.addParameter(MolaDbConstants.URI_BATCH_WRITE, null);
fillInHeadAndBody(request, httpRequest);
BatchWriteItemResponse ret = this.invokeHttpClient(httpRequest, BatchWriteItemResponse.class);
return ret;
} |
python | def request(self, method, url, bearer_auth=True, **req_kwargs):
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url: The resource to be requested.
:type url: str
:param bearer_auth: Whether to use Bearer Authentication or not,
defaults to `True`.
:type bearer_auth: bool
:param \*\*req_kwargs: Keyworded args to be passed down to Requests.
:type \*\*req_kwargs: dict
'''
req_kwargs.setdefault('params', {})
url = self._set_url(url)
if is_basestring(req_kwargs['params']):
req_kwargs['params'] = dict(parse_qsl(req_kwargs['params']))
if bearer_auth and self.access_token is not None:
req_kwargs['auth'] = OAuth2Auth(self.access_token)
else:
req_kwargs['params'].update({self.access_token_key:
self.access_token})
req_kwargs.setdefault('timeout', OAUTH2_DEFAULT_TIMEOUT)
return super(OAuth2Session, self).request(method, url, **req_kwargs) |
python | def _compare_title(self, other):
"""Return False if titles have different gender associations"""
# If title is omitted, assume a match
if not self.title or not other.title:
return True
titles = set(self.title_list + other.title_list)
return not (titles & MALE_TITLES and titles & FEMALE_TITLES) |
java | public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
//enter symbols for all files
if (!taskListener.isEmpty()) {
for (JCCompilationUnit unit: roots) {
TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
taskListener.started(e);
}
}
enter.main(roots);
if (!taskListener.isEmpty()) {
for (JCCompilationUnit unit: roots) {
TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
taskListener.finished(e);
}
}
// If generating source, or if tracking public apis,
// then remember the classes declared in
// the original compilation units listed on the command line.
if (needRootClasses || sourceOutput || stubOutput) {
ListBuffer<JCClassDecl> cdefs = new ListBuffer<>();
for (JCCompilationUnit unit : roots) {
for (List<JCTree> defs = unit.defs;
defs.nonEmpty();
defs = defs.tail) {
if (defs.head instanceof JCClassDecl)
cdefs.append((JCClassDecl)defs.head);
}
}
rootClasses = cdefs.toList();
}
// Ensure the input files have been recorded. Although this is normally
// done by readSource, it may not have been done if the trees were read
// in a prior round of annotation processing, and the trees have been
// cleaned and are being reused.
for (JCCompilationUnit unit : roots) {
inputFiles.add(unit.sourcefile);
}
return roots;
} |
python | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table : object
Astropy Table object of the catalog
"""
# generate catalog
temp_pars = pars.copy()
if pars['output'] == True:
pars['output'] = 'ref_cat.ecsv'
else:
pars['output'] = None
out_catalog = amutils.create_astrometric_catalog(imglist,**pars)
pars = temp_pars.copy()
#if the catalog has contents, write the catalog to ascii text file
if len(out_catalog) > 0 and pars['output']:
catalog_filename = "refcatalog.cat"
out_catalog.write(catalog_filename, format="ascii.fast_commented_header")
log.info("Wrote reference catalog {}.".format(catalog_filename))
return(out_catalog) |
java | public ServerSideEncryptionByDefault withSSEAlgorithm(SSEAlgorithm sseAlgorithm) {
setSSEAlgorithm(sseAlgorithm == null ? null : sseAlgorithm.toString());
return this;
} |
python | def unpack(self, data, namedstruct):
'''
Unpack the struct from specified bytes. If the struct is sub-classed, definitions from the sub type
is not unpacked.
:param data: bytes of the struct, including fields of sub type and "extra" data.
:param namedstruct: a NamedStruct object of this type
:returns: unused bytes from data, which forms data of the sub type and "extra" data.
'''
try:
result = self.struct.unpack(data[0:self.struct.size])
except struct.error as exc:
raise BadFormatError(exc)
start = 0
t = namedstruct._target
for p in self.properties:
if len(p) > 1:
if isinstance(result[start], bytes):
v = [r.rstrip(b'\x00') for r in result[start:start + p[1]]]
else:
v = list(result[start:start + p[1]])
start += p[1]
else:
v = result[start]
if isinstance(v, bytes):
v = v.rstrip(b'\x00')
start += 1
setin = t
for sp in p[0][0:-1]:
if not hasattr(setin, sp):
setin2 = InlineStruct(namedstruct._target)
setattr(setin, sp, setin2)
setin = setin2
else:
setin = getattr(setin, sp)
setattr(setin, p[0][-1], v)
return data[self.struct.size:] |
python | def get_raid_fgi_status(report):
"""Gather fgi(foreground initialization) information of raid configuration
This function returns a fgi status which contains activity status
and its values from the report.
:param report: SCCI report information
:returns: dict of fgi status of logical_drives, such as Initializing (10%)
or Idle. e.g: {'0': 'Idle', '1': 'Initializing (10%)'}
:raises: SCCIInvalidInputError: fail report input.
SCCIRAIDNotReady: waiting for RAID configuration to complete.
"""
fgi_status = {}
raid_path = "./Software/ServerView/ServerViewRaid"
if not report.find(raid_path):
raise SCCIInvalidInputError(
"ServerView RAID not available in Bare metal Server")
if not report.find(raid_path + "/amEMSV/System/Adapter/LogicalDrive"):
raise SCCIRAIDNotReady(
"RAID configuration not configure in Bare metal Server yet")
logical_drives = report.findall(raid_path +
"/amEMSV/System/Adapter/LogicalDrive")
for logical_drive_name in logical_drives:
status = logical_drive_name.find("./Activity").text
name = logical_drive_name.find("./LogDriveNumber").text
fgi_status.update({name: status})
return fgi_status |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
protected void ensureLocalSpaceDefinition(SpaceID id, Object[] initializationParameters) {
synchronized (getSpaceRepositoryMutex()) {
if (!this.spaces.containsKey(id)) {
createSpaceInstance((Class) id.getSpaceSpecification(), id, false, initializationParameters);
}
}
} |
java | public void mainFindBestValEntropy(Node root) {
if (root != null) {
DoubleVector parentClassCL = new DoubleVector();
DoubleVector classCountL = root.classCountsLeft; //class count left
DoubleVector classCountR = root.classCountsRight; //class count left
double numInst = root.classCountsLeft.sumOfValues() + root.classCountsRight.sumOfValues();
double classCountLSum = root.classCountsLeft.sumOfValues();
double classCountRSum = root.classCountsRight.sumOfValues();
double classCountLEntropy = entropy(classCountL);
double classCountREntropy = entropy(classCountR);
this.minEntropyTemp = ( classCountLSum / numInst) * classCountLEntropy
+ (classCountRSum / numInst)* classCountREntropy;
for (int f = 0; f < root.classCountsLeft.numValues(); f++) {
parentClassCL.setValue(f, root.classCountsLeft.getValue(f));
}
findBestValEntropy(root ,classCountL , classCountR, true, this.minEntropyTemp, parentClassCL);
}
} |
java | public static long searchMin(long[] longArray) {
if(longArray.length == 0) {
throw new IllegalArgumentException("The array you provided does not have any elements");
}
long min = longArray[0];
for(int i = 1; i < longArray.length; i++) {
if(longArray[i] < min) {
min = longArray[i];
}
}
return min;
} |
python | def get_arrow(self, likes):
"""
Curses does define constants for symbols (e.g. curses.ACS_BULLET).
However, they rely on using the curses.addch() function, which has been
found to be buggy and a general PITA to work with. By defining them as
unicode points they can be added via the more reliable curses.addstr().
http://bugs.python.org/issue21088
"""
if likes is None:
return self.neutral_arrow, self.attr('NeutralVote')
elif likes:
return self.up_arrow, self.attr('Upvote')
else:
return self.down_arrow, self.attr('Downvote') |
python | def get_percent(self):
"""get_percent()
Returns the weighted percentage of the score from min-max values"""
if not (self.votes and self.score):
return 0
return 100 * (self.get_rating() / self.field.range) |
java | protected void validateSingle(
CmsUUID structureId,
Map<String, String> sitePaths,
String newSitePath,
final AsyncCallback<String> errorCallback) {
Map<String, String> newMap = new HashMap<String, String>(sitePaths);
newMap.put("NEW", newSitePath); //$NON-NLS-1$
AsyncCallback<Map<String, String>> callback = new AsyncCallback<Map<String, String>>() {
public void onFailure(Throwable caught) {
assert false; // should never happen
}
public void onSuccess(Map<String, String> result) {
String newRes = result.get("NEW"); //$NON-NLS-1$
errorCallback.onSuccess(newRes);
}
};
validateAliases(structureId, newMap, callback);
} |
java | @Override
public void open(AudioFormat format, int bufferSize) throws LineUnavailableException {
opening();
sourceDataLine.open(format, bufferSize);
} |
python | def economic_qs_linear(G):
r"""Economic eigen decomposition for symmetric matrices ``dot(G, G.T)``.
It is theoretically equivalent to ``economic_qs(dot(G, G.T))``.
Refer to :func:`numpy_sugar.economic_qs` for further information.
Args:
G (array_like): Matrix.
Returns:
tuple: ``((Q0, Q1), S0)``.
"""
import dask.array as da
if not isinstance(G, da.Array):
G = asarray(G, float)
if G.shape[0] > G.shape[1]:
(Q, Ssq, _) = svd(G, full_matrices=True)
S0 = Ssq ** 2
rank = len(S0)
Q0, Q1 = Q[:, :rank], Q[:, rank:]
return ((Q0, Q1), S0)
return economic_qs(G.dot(G.T)) |
java | public <T> Subscription bind(
Property<T> target,
ObservableValue<? extends T> source) {
return bind(() -> {
target.bind(source);
return target::unbind;
});
} |
java | public final void sendBroadCastVariables(Configuration config) throws IOException {
try {
int broadcastCount = config.getInteger(PLANBINDER_CONFIG_BCVAR_COUNT, 0);
String[] names = new String[broadcastCount];
for (int x = 0; x < names.length; x++) {
names[x] = config.getString(PLANBINDER_CONFIG_BCVAR_NAME_PREFIX + x, null);
}
out.write(new IntSerializer().serializeWithoutTypeInfo(broadcastCount));
StringSerializer stringSerializer = new StringSerializer();
for (String name : names) {
Iterator<byte[]> bcv = function.getRuntimeContext().<byte[]>getBroadcastVariable(name).iterator();
out.write(stringSerializer.serializeWithoutTypeInfo(name));
while (bcv.hasNext()) {
out.writeByte(1);
out.write(bcv.next());
}
out.writeByte(0);
}
} catch (SocketTimeoutException ignored) {
throw new RuntimeException("External process for task " + function.getRuntimeContext().getTaskName() + " stopped responding." + msg);
}
} |
python | def uninstall(cls):
"""Remove the package manager from the system."""
if os.path.exists(cls.home):
shutil.rmtree(cls.home) |
java | protected String[] getRowClasses(PanelGrid grid) {
String rowClasses = grid.getRowClasses();
if (null == rowClasses || rowClasses.trim().length()==0)
return null;
String[] rows = rowClasses.split(",");
return rows;
} |
python | def distinct_on(self, value):
"""Set fields used to group query results.
:type value: str or sequence of strings
:param value: Each value is a string giving the name of a
property to use to group results together.
"""
if isinstance(value, str):
value = [value]
self._distinct_on[:] = value |
java | public <S> S queryOne(Class<S> type, String sql, Object[] params) {
Connection conn = getConn();
try {
Query query = conn.createQuery(sql)
.withParams(params)
.setAutoDeriveColumnNames(true)
.throwOnMappingFailure(false);
return ifReturn(AnimaUtils.isBasicType(type),
() -> query.executeScalar(type),
() -> query.executeAndFetchFirst(type));
} finally {
this.closeConn(conn);
this.clean(null);
}
} |
java | private DateTime providedOrDefaultFromValue(DateTime from, DateTime to,
AggregateCounterResolution resolution) {
if (from != null) {
return from;
}
switch (resolution) {
case minute:
return to.minusMinutes(59);
case hour:
return to.minusHours(23);
case day:
return to.minusDays(6);
case month:
return to.minusMonths(11);
case year:
return to.minusYears(4);
default:
throw new IllegalStateException(
"Shouldn't happen. Unhandled resolution: " + resolution);
}
} |
java | public Location lastKnownLocation() {
final HandlingEvent lastEvent = this.lnkDeliveryHistory.lastEvent();
if (lastEvent != null) {
return lastEvent.getLocation();
} else {
return null;
}
} |
python | def phenotypeAssociationSetsGenerator(self, request):
"""
Returns a generator over the (phenotypeAssociationSet, nextPageToken)
pairs defined by the specified request
"""
dataset = self.getDataRepository().getDataset(request.dataset_id)
return self._topLevelObjectGenerator(
request, dataset.getNumPhenotypeAssociationSets(),
dataset.getPhenotypeAssociationSetByIndex) |
python | async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(query)) |
python | def convert(self, value, view):
"""Ensure that the value is among the choices (and remap if the
choices are a mapping).
"""
if (SUPPORTS_ENUM and isinstance(self.choices, type)
and issubclass(self.choices, enum.Enum)):
try:
return self.choices(value)
except ValueError:
self.fail(
u'must be one of {0!r}, not {1!r}'.format(
[c.value for c in self.choices], value
),
view
)
if value not in self.choices:
self.fail(
u'must be one of {0!r}, not {1!r}'.format(
list(self.choices), value
),
view
)
if isinstance(self.choices, abc.Mapping):
return self.choices[value]
else:
return value |
python | def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
"""
try:
if lazy:
rel_model = getattr(model, name).fetch()
else:
rel_model = getattr(model, name)
except (mongoengine.DoesNotExist, AttributeError) as e:
# custom_field_type_formatters seems to fix the issue of stale references
# crashing pages, since it intercepts the display of all ReferenceField's.
return Markup(
'<span class="label label-danger">Error</span> <small>%s</small>' % e
)
if rel_model is None:
return ''
try:
return Markup(
'<a href="%s">%s</a>'
% (
url_for(
# Flask-Admin creates URL's namespaced w/ model class name, lowercase.
'%s.details_view' % rel_model.__class__.__name__.lower(),
id=rel_model.id,
),
rel_model,
)
)
except werkzeug.routing.BuildError as e:
return Markup(
'<span class="label label-danger">Error</span> <small>%s</small>' % e
) |
python | def _publish_match(self, publish, names=False, name_only=False):
"""
Check if publish name matches list of names or regex patterns
"""
if names:
for name in names:
if not name_only and isinstance(name, re._pattern_type):
if re.match(name, publish.name):
return True
else:
operand = name if name_only else [name, './%s' % name]
if publish in operand:
return True
return False
else:
return True |
python | def _eval_model(self):
"""
Convenience method for evaluating the model with the current parameters
:return: named tuple with results
"""
arguments = self._x_grid.copy()
arguments.update({param: param.value for param in self.model.params})
return self.model(**key2str(arguments)) |
java | public final int getPersistableInMemorySizeApproximation(TransactionState tranState)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getPersistableInMemorySizeApproximation", tranState);
int size;
if ((tranState == TransactionState.STATE_COMMITTED) || (tranState == TransactionState.STATE_COMMITTING_1PC))
{
size = DEFAULT_TASK_PERSISTABLE_SIZE_APPROXIMATION;
}
else
{
throw new IllegalStateException(nls.getFormattedMessage("INVALID_TASK_OPERATION_SIMS1520", new Object[] {tranState}, null));
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getPersistableInMemorySizeApproximation", Integer.valueOf(size));
return size;
} |
python | def config_id_exists(search_id):
"""
Test if a build configuration matching search_id exists
:param search_id: id to test for
:return: True if a build configuration with search_id exists, False otherwise
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_specific', id=search_id)
if not response:
return False
return True |
java | @Override
@FFDCIgnore(SecurityException.class)
public ExtendedConfiguration[] listConfigurations(String filterString) throws InvalidSyntaxException {
if (filterString == null)
filterString = "(" + Constants.SERVICE_PID + "=*)"; //$NON-NLS-1$ //$NON-NLS-2$
try {
this.caFactory.checkConfigurationPermission();
} catch (SecurityException e) {
filterString = "(&(" + ConfigurationAdmin.SERVICE_BUNDLELOCATION + "=" + bundle.getLocation() + ")" + filterString + ")";
}
return caFactory.getConfigurationStore().listConfigurations(FrameworkUtil.createFilter(filterString));
} |
python | def deserialize(self, value, **kwargs):
"""De-serialize the property value from JSON
If no deserializer has been registered, this converts the value
to the wrapper class with given dtype.
"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer is not None:
return self.deserializer(value, **kwargs)
if value is None:
return None
return self.wrapper(value).astype(self.dtype[0]) |
python | def ask(self, question, default=False):
""" Ask a y/n question to the user.
"""
choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N')
while True:
response = raw_input('%s %s' % (question, choices)).strip()
if not response:
return default
elif response in 'yYoO':
return True
elif response in 'nN':
return False |
java | public <T extends Type> T resolve(String typeName, Class<T> clazz) {
Type instance = resolve(typeName);
if (instance == null) {
return null;
}
if (clazz.isAssignableFrom(instance.getClass())) {
return clazz.cast(instance);
} else {
throw new ParserException("Type error: %s of type %s can not be cast to %s",
typeName, instance.getClass(), clazz);
}
} |
java | private Map<String, RouteEntry> getAcceptedMimeTypes(List<RouteEntry> routes) {
Map<String, RouteEntry> acceptedTypes = new HashMap<>();
for (RouteEntry routeEntry : routes) {
if (!acceptedTypes.containsKey(routeEntry.acceptedType)) {
acceptedTypes.put(routeEntry.acceptedType, routeEntry);
}
}
return acceptedTypes;
} |
python | def load_config(files=None, root_path=None, local_path=None):
"""Load the configuration from specified files."""
config = cfg.ConfigOpts()
config.register_opts([
cfg.Opt('root_path', default=root_path),
cfg.Opt('local_path', default=local_path),
])
# XXX register actual config groups here
# theme_group = config_theme.register_config(config)
if files is not None:
config(args=[], default_config_files=files)
return config |
python | def _get_and_assert_slice_param(url_dict, param_name, default_int):
"""Return ``param_str`` converted to an int.
If str cannot be converted to int or int is not zero or positive, raise
InvalidRequest.
"""
param_str = url_dict['query'].get(param_name, default_int)
try:
n = int(param_str)
except ValueError:
raise d1_common.types.exceptions.InvalidRequest(
0,
'Slice parameter is not a valid integer. {}="{}"'.format(
param_name, param_str
),
)
if n < 0:
raise d1_common.types.exceptions.InvalidRequest(
0,
'Slice parameter cannot be a negative number. {}="{}"'.format(
param_name, param_str
),
)
return n |
python | def _load_image_set_index(self, shuffle):
"""
get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices
"""
self.num_images = 0
for db in self.imdbs:
self.num_images += db.num_images
indices = list(range(self.num_images))
if shuffle:
random.shuffle(indices)
return indices |
python | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers', None)
msg_id = message.get('msg_id', None)
if not msg_id and headers:
msg_id = headers.get('message-id', None)
if not msg_id:
msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
obj = Message(
i=message.get('i', 0),
msg_id=msg_id,
topic=message['topic'],
timestamp=timestamp,
username=message.get('username', None),
crypto=message.get('crypto', None),
certificate=message.get('certificate', None),
signature=message.get('signature', None),
)
obj.msg = message['msg']
obj.headers = headers
try:
session.add(obj)
session.flush()
except IntegrityError:
log.warning('Skipping message from %s with duplicate id: %s',
message['topic'], msg_id)
session.rollback()
return
usernames = fedmsg.meta.msg2usernames(message)
packages = fedmsg.meta.msg2packages(message)
# Do a little sanity checking on fedmsg.meta results
if None in usernames:
# Notify developers so they can fix msg2usernames
log.error('NoneType found in usernames of %r' % msg_id)
# And prune out the bad value
usernames = [name for name in usernames if name is not None]
if None in packages:
# Notify developers so they can fix msg2packages
log.error('NoneType found in packages of %r' % msg_id)
# And prune out the bad value
packages = [pkg for pkg in packages if pkg is not None]
# If we've never seen one of these users before, then:
# 1) make sure they exist in the db (create them if necessary)
# 2) mark an in memory cache so we can remember that they exist without
# having to hit the db.
for username in usernames:
if username not in _users_seen:
# Create the user in the DB if necessary
User.get_or_create(username)
# Then just mark an in memory cache noting that we've seen them.
_users_seen.add(username)
for package in packages:
if package not in _packages_seen:
Package.get_or_create(package)
_packages_seen.add(package)
session.flush()
# These two blocks would normally be a simple "obj.users.append(user)" kind
# of statement, but here we drop down out of sqlalchemy's ORM and into the
# sql abstraction in order to gain a little performance boost.
values = [{'username': username, 'msg': obj.id} for username in usernames]
if values:
session.execute(user_assoc_table.insert(), values)
values = [{'package': package, 'msg': obj.id} for package in packages]
if values:
session.execute(pack_assoc_table.insert(), values)
# TODO -- can we avoid committing every time?
session.flush()
session.commit() |
java | protected void handleVersion(
EntityDesc entityDesc, EntityPropertyDesc propertyDesc, ColumnMeta columnMeta) {
if (isVersionAnnotatable(propertyDesc.getPropertyClassName())) {
if (versionColumnNamePattern.matcher(columnMeta.getName()).matches()) {
propertyDesc.setVersion(true);
}
}
} |
java | public Map<String, Monomer> loadMonomerStore(Map<String, Attachment> attachmentDB)
throws IOException, URISyntaxException, EncoderException {
Map<String, Monomer> monomers = new TreeMap<String, Monomer>(String.CASE_INSENSITIVE_ORDER);
CloseableHttpClient httpclient = HttpClients.createDefault();
// There is no need to provide user credentials
// HttpClient will attempt to access current user security context
// through Windows platform specific methods via JNI.
CloseableHttpResponse response = null;
try {
HttpGet httpget = new HttpGet(
new URIBuilder(MonomerStoreConfiguration.getInstance().getWebserviceMonomersFullURL() + polymerType)
.build());
LOG.debug("Executing request " + httpget.getRequestLine());
response = httpclient.execute(httpget);
LOG.debug(response.getStatusLine().toString());
JsonFactory jsonf = new JsonFactory();
InputStream instream = response.getEntity().getContent();
if (response.getStatusLine().getStatusCode() != 200) {
throw new MonomerLoadingException("Response from the Webservice throws an error");
}
JsonParser jsonParser = jsonf.createJsonParser(instream);
monomers = deserializeMonomerStore(jsonParser, attachmentDB);
LOG.debug(monomers.size() + " " + polymerType + " monomers loaded");
EntityUtils.consume(response.getEntity());
} finally {
if (response != null) {
response.close();
}
if (httpclient != null) {
httpclient.close();
}
}
return monomers;
} |
python | def print_summary(self, heading: str) -> None:
"""Print the summary of a graph.
:param str heading: Title of the graph.
"""
logger.info(heading)
logger.info("Number of nodes: {}".format(len(self.graph.vs)))
logger.info("Number of edges: {}".format(len(self.graph.es))) |
python | def write_workflow(self, request, opts, cwd, wftype='cwl'):
"""Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url")
# link the cwl and json into the cwd
if workflow_url.startswith('file://'):
os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype))
workflow_url = os.path.join(cwd, "wes_workflow." + wftype)
os.link(self.input_json, os.path.join(cwd, "wes_input.json"))
self.input_json = os.path.join(cwd, "wes_input.json")
extra_options = self.sort_toil_options(opts.getoptlist("extra"))
if wftype == 'cwl':
command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'wdl':
command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json]
elif wftype == 'py':
command_args = ['python'] + extra_options + [workflow_url]
else:
raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype))
return command_args |
python | def set_(name, target, module_parameter=None, action_parameter=None):
'''
Verify that the given module is set to the given target
name
The name of the module
target
The target to be set for this module
module_parameter
additional params passed to the defined module
action_parameter
additional params passed to the defined action
.. code-block:: yaml
profile:
eselect.set:
- target: hardened/linux/amd64
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
old_target = __salt__['eselect.get_current_target'](name, module_parameter=module_parameter, action_parameter=action_parameter)
if target == old_target:
ret['comment'] = 'Target \'{0}\' is already set on \'{1}\' module.'.format(
target, name
)
elif target not in __salt__['eselect.get_target_list'](name, action_parameter=action_parameter):
ret['comment'] = (
'Target \'{0}\' is not available for \'{1}\' module.'.format(
target, name
)
)
ret['result'] = False
elif __opts__['test']:
ret['comment'] = 'Target \'{0}\' will be set on \'{1}\' module.'.format(
target, name
)
ret['result'] = None
else:
result = __salt__['eselect.set_target'](name, target, module_parameter=module_parameter, action_parameter=action_parameter)
if result:
ret['changes'][name] = {'old': old_target, 'new': target}
ret['comment'] = 'Target \'{0}\' set on \'{1}\' module.'.format(
target, name
)
else:
ret['comment'] = (
'Target \'{0}\' failed to be set on \'{1}\' module.'.format(
target, name
)
)
ret['result'] = False
return ret |
java | public void setIdleMax(int max)
{
if (max == _idleMax) {
// avoid update() overhead if unchanged
return;
}
if (max <= 0) {
max = DEFAULT_IDLE_MAX;
}
if (_threadMax < max)
throw new ConfigException(L.l("IdleMax ({0}) must be less than ThreadMax ({1})", max, _threadMax));
if (max <= 0)
throw new ConfigException(L.l("IdleMax ({0}) must be greater than 0.", max));
_idleMax = max;
update();
} |
python | def load(path, filetype=None, as_df=False, retries=None,
_oid=None, quiet=False, **kwargs):
'''Load multiple files from various file types automatically.
Supports glob paths, eg::
path = 'data/*.csv'
Filetypes are autodetected by common extension strings.
Currently supports loadings from:
* csv (pd.read_csv)
* json (pd.read_json)
:param path: path to config json file
:param filetype: override filetype autodetection
:param kwargs: additional filetype loader method kwargs
'''
is_true(HAS_PANDAS, "`pip install pandas` required")
set_oid = set_oid_func(_oid)
# kwargs are for passing ftype load options (csv.delimiter, etc)
# expect the use of globs; eg, file* might result in fileN (file1,
# file2, file3), etc
if not isinstance(path, basestring):
# assume we're getting a raw dataframe
objects = path
if not isinstance(objects, pd.DataFrame):
raise ValueError("loading raw values must be DataFrames")
elif re.match('https?://', path):
logger.debug('Saving %s to tmp file' % path)
_path = urlretrieve(path, retries)
logger.debug('%s saved to tmp file: %s' % (path, _path))
try:
objects = load_file(_path, filetype, **kwargs)
finally:
remove_file(_path)
else:
path = re.sub('^file://', '', path)
path = os.path.expanduser(path)
# assume relative to cwd if not already absolute path
path = path if os.path.isabs(path) else pjoin(os.getcwd(), path)
files = sorted(glob.glob(os.path.expanduser(path)))
if not files:
raise IOError("failed to load: %s" % path)
# buid up a single dataframe by concatting
# all globbed files together
objects = []
[objects.extend(load_file(ds, filetype, **kwargs))
for ds in files]
if is_empty(objects, except_=False) and not quiet:
raise RuntimeError("no objects extracted!")
else:
logger.debug("Data loaded successfully from %s" % path)
if set_oid:
# set _oids, if we have a _oid generator func defined
objects = [set_oid(o) for o in objects]
if as_df:
return pd.DataFrame(objects)
else:
return objects |
python | def split_df(df):
'''
Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history
'''
envmask = (df['agent_id'] == 'env')
n_env = envmask.sum()
if n_env == len(df):
return df, None
elif n_env == 0:
return None, df
agents, env = [x for _, x in df.groupby(envmask)]
return env, agents |
python | def replace(
self,
accountID,
orderSpecifier,
**kwargs
):
"""
Replace an Order in an Account by simultaneously cancelling it and
creating a replacement Order
Args:
accountID:
Account Identifier
orderSpecifier:
The Order Specifier
order:
Specification of the replacing Order
Returns:
v20.response.Response containing the results from submitting the
request
"""
request = Request(
'PUT',
'/v3/accounts/{accountID}/orders/{orderSpecifier}'
)
request.set_path_param(
'accountID',
accountID
)
request.set_path_param(
'orderSpecifier',
orderSpecifier
)
body = EntityDict()
if 'order' in kwargs:
body.set('order', kwargs['order'])
request.set_body_dict(body.dict)
response = self.ctx.request(request)
if response.content_type is None:
return response
if not response.content_type.startswith("application/json"):
return response
jbody = json.loads(response.raw_body)
parsed_body = {}
#
# Parse responses as defined by the API specification
#
if str(response.status) == "201":
if jbody.get('orderCancelTransaction') is not None:
parsed_body['orderCancelTransaction'] = \
self.ctx.transaction.OrderCancelTransaction.from_dict(
jbody['orderCancelTransaction'],
self.ctx
)
if jbody.get('orderCreateTransaction') is not None:
parsed_body['orderCreateTransaction'] = \
self.ctx.transaction.Transaction.from_dict(
jbody['orderCreateTransaction'],
self.ctx
)
if jbody.get('orderFillTransaction') is not None:
parsed_body['orderFillTransaction'] = \
self.ctx.transaction.OrderFillTransaction.from_dict(
jbody['orderFillTransaction'],
self.ctx
)
if jbody.get('orderReissueTransaction') is not None:
parsed_body['orderReissueTransaction'] = \
self.ctx.transaction.Transaction.from_dict(
jbody['orderReissueTransaction'],
self.ctx
)
if jbody.get('orderReissueRejectTransaction') is not None:
parsed_body['orderReissueRejectTransaction'] = \
self.ctx.transaction.Transaction.from_dict(
jbody['orderReissueRejectTransaction'],
self.ctx
)
if jbody.get('replacingOrderCancelTransaction') is not None:
parsed_body['replacingOrderCancelTransaction'] = \
self.ctx.transaction.OrderCancelTransaction.from_dict(
jbody['replacingOrderCancelTransaction'],
self.ctx
)
if jbody.get('relatedTransactionIDs') is not None:
parsed_body['relatedTransactionIDs'] = \
jbody.get('relatedTransactionIDs')
if jbody.get('lastTransactionID') is not None:
parsed_body['lastTransactionID'] = \
jbody.get('lastTransactionID')
elif str(response.status) == "400":
if jbody.get('orderRejectTransaction') is not None:
parsed_body['orderRejectTransaction'] = \
self.ctx.transaction.Transaction.from_dict(
jbody['orderRejectTransaction'],
self.ctx
)
if jbody.get('relatedTransactionIDs') is not None:
parsed_body['relatedTransactionIDs'] = \
jbody.get('relatedTransactionIDs')
if jbody.get('lastTransactionID') is not None:
parsed_body['lastTransactionID'] = \
jbody.get('lastTransactionID')
if jbody.get('errorCode') is not None:
parsed_body['errorCode'] = \
jbody.get('errorCode')
if jbody.get('errorMessage') is not None:
parsed_body['errorMessage'] = \
jbody.get('errorMessage')
elif str(response.status) == "401":
if jbody.get('errorCode') is not None:
parsed_body['errorCode'] = \
jbody.get('errorCode')
if jbody.get('errorMessage') is not None:
parsed_body['errorMessage'] = \
jbody.get('errorMessage')
elif str(response.status) == "404":
if jbody.get('orderCancelRejectTransaction') is not None:
parsed_body['orderCancelRejectTransaction'] = \
self.ctx.transaction.Transaction.from_dict(
jbody['orderCancelRejectTransaction'],
self.ctx
)
if jbody.get('relatedTransactionIDs') is not None:
parsed_body['relatedTransactionIDs'] = \
jbody.get('relatedTransactionIDs')
if jbody.get('lastTransactionID') is not None:
parsed_body['lastTransactionID'] = \
jbody.get('lastTransactionID')
if jbody.get('errorCode') is not None:
parsed_body['errorCode'] = \
jbody.get('errorCode')
if jbody.get('errorMessage') is not None:
parsed_body['errorMessage'] = \
jbody.get('errorMessage')
elif str(response.status) == "405":
if jbody.get('errorCode') is not None:
parsed_body['errorCode'] = \
jbody.get('errorCode')
if jbody.get('errorMessage') is not None:
parsed_body['errorMessage'] = \
jbody.get('errorMessage')
#
# Unexpected response status
#
else:
parsed_body = jbody
response.body = parsed_body
return response |
java | public boolean removeRunCompression() {
boolean answer = false;
for (int i = 0; i < this.highLowContainer.size(); i++) {
Container c = this.highLowContainer.getContainerAtIndex(i);
if (c instanceof RunContainer) {
Container newc = ((RunContainer) c).toBitmapOrArrayContainer(c.getCardinality());
this.highLowContainer.setContainerAtIndex(i, newc);
answer = true;
}
}
return answer;
} |
java | public String get(String command) throws PHPException {
try {
String s = php.execGet(command);
flushContent();
return s;
} catch (IOException e) {
LOGGER.error("IO Error with PhpDriver : " + e.toString());
throw new IOErrorException(flushContentAndDropIOException());
}
} |
python | def get_report(self):
"""
Return a string containing a report of the result.
This can used to print or save to a text file.
Returns:
str: String containing infos about the result
"""
lines = [
self.name,
'=' * len(self.name)
]
if self.info is not None:
lines.append('')
sorted_info = sorted(self.info.items(), key=lambda x: x[0])
lines.extend(['--> {}: {}'.format(k, v) for k, v in sorted_info])
lines.append('')
lines.append('Result: {}'.format('Passed' if self.passed else 'Failed'))
return '\n'.join(lines) |
java | public static appflowaction[] get(nitro_service service, options option) throws Exception{
appflowaction obj = new appflowaction();
appflowaction[] response = (appflowaction[])obj.get_resources(service,option);
return response;
} |
python | def _set_vlan(self, v, load=False):
"""
Setter method for vlan, mapped from YANG variable /interface_vlan/interface/vlan (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vlan() directly.
YANG Description: The list of vlans in the managed device. Each row
represents a vlan. User can create/delete an entry in
to this list.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",vlan.vlan, yang_name="vlan", rest_name="Vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions={u'tailf-common': {u'info': u'The list of vlans.', u'cli-no-key-completion': None, u'alt-name': u'Vlan', u'cli-suppress-show-path': None, u'cli-suppress-list-no': None, u'cli-custom-range-actionpoint': u'NsmRangeCliActionpoint', u'cli-custom-range-enumerator': u'NsmRangeCliActionpoint', u'cli-suppress-key-abbreviation': None, u'cli-no-match-completion': None, u'cli-full-command': None, u'callpoint': u'interface_vlan'}}), is_container='list', yang_name="vlan", rest_name="Vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'The list of vlans.', u'cli-no-key-completion': None, u'alt-name': u'Vlan', u'cli-suppress-show-path': None, u'cli-suppress-list-no': None, u'cli-custom-range-actionpoint': u'NsmRangeCliActionpoint', u'cli-custom-range-enumerator': u'NsmRangeCliActionpoint', u'cli-suppress-key-abbreviation': None, u'cli-no-match-completion': None, u'cli-full-command': None, u'callpoint': u'interface_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """vlan must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("name",vlan.vlan, yang_name="vlan", rest_name="Vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions={u'tailf-common': {u'info': u'The list of vlans.', u'cli-no-key-completion': None, u'alt-name': u'Vlan', u'cli-suppress-show-path': None, u'cli-suppress-list-no': None, u'cli-custom-range-actionpoint': u'NsmRangeCliActionpoint', u'cli-custom-range-enumerator': u'NsmRangeCliActionpoint', u'cli-suppress-key-abbreviation': None, u'cli-no-match-completion': None, u'cli-full-command': None, u'callpoint': u'interface_vlan'}}), is_container='list', yang_name="vlan", rest_name="Vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'The list of vlans.', u'cli-no-key-completion': None, u'alt-name': u'Vlan', u'cli-suppress-show-path': None, u'cli-suppress-list-no': None, u'cli-custom-range-actionpoint': u'NsmRangeCliActionpoint', u'cli-custom-range-enumerator': u'NsmRangeCliActionpoint', u'cli-suppress-key-abbreviation': None, u'cli-no-match-completion': None, u'cli-full-command': None, u'callpoint': u'interface_vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)""",
})
self.__vlan = t
if hasattr(self, '_set'):
self._set() |
python | def decorator(f):
"""Creates a paramatric decorator from a function. The resulting decorator
will optionally take keyword arguments."""
@functools.wraps(f)
def decoratored_function(*args, **kwargs):
if args and len(args) == 1:
return f(*args, **kwargs)
if args:
raise TypeError(
"This decorator only accepts extra keyword arguments.")
return lambda g: f(g, **kwargs)
return decoratored_function |
java | void addMessageHandler(SubscriptionMessageHandler messageHandler)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "addMessageHandler", messageHandler);
final boolean inserted = _subscriptionMessagePool.add(messageHandler);
// If the message wasn't inserted, then the pool was exceeded
if (!inserted)
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(
tc,
"SubscriptionObjectPool size exceeded");
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addMessageHandler");
} |
python | def _get_value_from_value_pb(value_pb):
"""Given a protobuf for a Value, get the correct value.
The Cloud Datastore Protobuf API returns a Property Protobuf which
has one value set and the rest blank. This function retrieves the
the one value provided.
Some work is done to coerce the return value into a more useful type
(particularly in the case of a timestamp value, or a key value).
:type value_pb: :class:`.entity_pb2.Value`
:param value_pb: The Value Protobuf.
:rtype: object
:returns: The value provided by the Protobuf.
:raises: :class:`ValueError <exceptions.ValueError>` if no value type
has been set.
"""
value_type = value_pb.WhichOneof("value_type")
if value_type == "timestamp_value":
result = _pb_timestamp_to_datetime(value_pb.timestamp_value)
elif value_type == "key_value":
result = key_from_protobuf(value_pb.key_value)
elif value_type == "boolean_value":
result = value_pb.boolean_value
elif value_type == "double_value":
result = value_pb.double_value
elif value_type == "integer_value":
result = value_pb.integer_value
elif value_type == "string_value":
result = value_pb.string_value
elif value_type == "blob_value":
result = value_pb.blob_value
elif value_type == "entity_value":
result = entity_from_protobuf(value_pb.entity_value)
elif value_type == "array_value":
result = [
_get_value_from_value_pb(value) for value in value_pb.array_value.values
]
elif value_type == "geo_point_value":
result = GeoPoint(
value_pb.geo_point_value.latitude, value_pb.geo_point_value.longitude
)
elif value_type == "null_value":
result = None
else:
raise ValueError("Value protobuf did not have any value set")
return result |
java | public void setCoveragesByTime(java.util.Collection<CoverageByTime> coveragesByTime) {
if (coveragesByTime == null) {
this.coveragesByTime = null;
return;
}
this.coveragesByTime = new java.util.ArrayList<CoverageByTime>(coveragesByTime);
} |
java | @Override
public void paint(final RenderContext renderContext) {
WebXmlRenderContext webRenderContext = (WebXmlRenderContext) renderContext;
PrintWriter writer = webRenderContext.getWriter();
beforePaint(writer);
getBackingComponent().paint(renderContext);
afterPaint(writer);
} |
java | @Override
public void run() {
if (!isRegistered()) {
try {
register();
} catch (IOException ex) {
throw new RuntimeException("Failed to register prefix, aborting.", ex);
}
}
// continuously serve packets
while (true) {
try {
synchronized (face) {
face.processEvents();
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to process events.", ex);
} catch (EncodingException ex) {
logger.log(Level.SEVERE, "Failed to parse bytes.", ex);
}
}
} |
java | private static BatchExecutor getSetBatchExecutor(BeanMappingParam param, BeanMappingObject config) {
BatchExecutor executor = config.getSetBatchExecutor();
if (executor != null) { // 如果已经生成,则直接返回
return executor;
}
if (canBatch(config.getBehavior()) == false) {
config.setBatch(false);
return null;
}
// 处理target操作数据搜集
List<String> targetFields = new ArrayList<String>();
List<Class> targetArgs = new ArrayList<Class>();
Class locatorClass = param.getTargetRef().getClass(); // 检查一下locatorClass
for (BeanMappingField beanField : config.getBeanFields()) {
String targetField = beanField.getTargetField().getName();
Class targetArg = beanField.getTargetField().getClazz();
if (StringUtils.isEmpty(targetField) || targetArg == null) {
return null; // 直接不予处理
}
Class selfLocatorClass = beanField.getTargetField().getLocatorClass();
if (selfLocatorClass != null && selfLocatorClass != locatorClass) {
config.setBatch(false);// 直接改写为false,发现locatorClass存在于不同的class
return null;
}
if (canBatch(beanField.getBehavior()) == false) {
config.setBatch(false);
return null;
}
SetExecutor set = beanField.getSetExecutor();// 只针对property进行batch优化
if (set != null && (set instanceof FastPropertySetExecutor || set instanceof PropertySetExecutor) == false) {
config.setBatch(false);
return null;
}
// 搜集信息
targetFields.add(targetField);
targetArgs.add(targetArg);
}
// 生成下target批量处理器
executor = Uberspector.getInstance().getBatchExecutor(locatorClass,
targetFields.toArray(new String[targetFields.size()]),
targetArgs.toArray(new Class[targetArgs.size()]));
if (config.getBehavior().isDebug() && logger.isDebugEnabled()) {
logger.debug("TargetClass[" + param.getTargetRef().getClass() + "]SetBatchExecutor is init");
}
config.setSetBatchExecutor(executor);
return executor;
} |
java | public Table addHeading(Object o,String attributes)
{
addHeading(o);
cell.attribute(attributes);
return this;
} |
java | public static IVdmStackFrame getEvaluationContext(IWorkbenchWindow window)
{
List<IWorkbenchWindow> alreadyVisited = new ArrayList<IWorkbenchWindow>();
if (window == null)
{
window = fgManager.fActiveWindow;
}
return getEvaluationContext(window, alreadyVisited);
} |
java | public static FormItem createFormItem(AbstractReadOnlyAttributeInfo info, AttributeProvider attributeProvider) {
FormItem formItem = null;
if (info.getFormInputType() != null) {
FormItemFactory factory = FORM_ITEMS.get(info.getFormInputType());
if (null != factory) {
formItem = factory.create();
} else {
Log.logWarn("Cannot find form item for " + info.getFormInputType() + ", using default instead.");
}
}
if (formItem == null) {
//Only check if attribute is editable. Non editable attributes can be ignored.
if (info instanceof PrimitiveAttributeInfo) {
String name = ((PrimitiveAttributeInfo) info).getType().name();
formItem = FORM_ITEMS.get(name).create();
} else if (info instanceof SyntheticAttributeInfo) {
String name = PrimitiveType.STRING.name();
formItem = FORM_ITEMS.get(name).create();
} else if (info instanceof AssociationAttributeInfo) {
String name = ((AssociationAttributeInfo) info).getType().name();
formItem = FORM_ITEMS.get(name).create();
} else {
throw new IllegalStateException("Don't know how to create form for field " + info.getName() + ", " +
"maybe you need to define the formInputType.");
}
}
if (formItem != null) {
formItem.setName(info.getName());
formItem.setTitle(info.getLabel());
formItem.setValidateOnChange(true);
formItem.setWidth("*");
// Special treatment for associations
if (info instanceof AssociationAttributeInfo) {
AssociationAttributeInfo associationInfo = (AssociationAttributeInfo) info;
String displayName = associationInfo.getFeature().getDisplayAttributeName();
if (displayName == null) {
displayName = associationInfo.getFeature().getAttributes().get(0).getName();
}
formItem.setDisplayField(displayName);
Object o = formItem.getAttributeAsObject(AssociationItem.ASSOCIATION_ITEM_ATTRIBUTE_KEY);
if (o instanceof OneToManyItem<?>) {
OneToManyItem<?> item = (OneToManyItem<?>) o;
item.init(associationInfo, attributeProvider);
} else if (o instanceof ManyToOneItem<?>) {
ManyToOneItem<?> item = (ManyToOneItem<?>) o;
item.init(associationInfo, attributeProvider);
}
}
return formItem;
}
return null;
} |
python | def get_gemeente_by_id(self, id):
'''
Retrieve a `gemeente` by id (the NIScode).
:rtype: :class:`Gemeente`
'''
def creator():
url = self.base_url + '/municipality/%s' % id
h = self.base_headers
p = {
'geometry': 'full',
'srs': '31370'
}
res = capakey_rest_gateway_request(url, h, p).json()
return Gemeente(
res['municipalityCode'],
res['municipalityName'],
self._parse_centroid(res['geometry']['center']),
self._parse_bounding_box(res['geometry']['boundingBox']),
res['geometry']['shape']
)
if self.caches['long'].is_configured:
key = 'get_gemeente_by_id_rest#%s' % id
gemeente = self.caches['long'].get_or_create(key, creator)
else:
gemeente = creator()
gemeente.set_gateway(self)
return gemeente |
python | def print_error(msg):
""" Print an error message """
if IS_POSIX:
print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END))
else:
print(u"[ERRO] %s" % (msg)) |
python | def get(self, request):
"""
Redirects to CAS logout page
:param request:
:return:
"""
next_page = request.GET.get('next')
# try to find the ticket matching current session for logout signal
try:
st = SessionTicket.objects.get(session_key=request.session.session_key)
ticket = st.ticket
except SessionTicket.DoesNotExist:
ticket = None
# send logout signal
cas_user_logout.send(
sender="manual",
user=request.user,
session=request.session,
ticket=ticket,
)
auth_logout(request)
# clean current session ProxyGrantingTicket and SessionTicket
ProxyGrantingTicket.objects.filter(session_key=request.session.session_key).delete()
SessionTicket.objects.filter(session_key=request.session.session_key).delete()
next_page = next_page or get_redirect_url(request)
if settings.CAS_LOGOUT_COMPLETELY:
protocol = get_protocol(request)
host = request.get_host()
redirect_url = urllib_parse.urlunparse(
(protocol, host, next_page, '', '', ''),
)
client = get_cas_client(request=request)
return HttpResponseRedirect(client.get_logout_url(redirect_url))
else:
# This is in most cases pointless if not CAS_RENEW is set. The user will
# simply be logged in again on next request requiring authorization.
return HttpResponseRedirect(next_page) |
python | def require_data(self):
"""
raise a DatacatsError if the datadir or volumes are missing or damaged
"""
files = task.source_missing(self.target)
if files:
raise DatacatsError('Missing files in source directory:\n' +
'\n'.join(files))
if not self.data_exists():
raise DatacatsError('Environment datadir missing. '
'Try "datacats init".')
if not self.data_complete():
raise DatacatsError('Environment datadir damaged or volumes '
'missing. '
'To reset and discard all data use '
'"datacats reset"') |
java | public boolean removeOrderbookCallback(final BitfinexOrderBookSymbol symbol,
final BiConsumer<BitfinexOrderBookSymbol, BitfinexOrderBookEntry> callback) throws BitfinexClientException {
return channelCallbacks.removeCallback(symbol, callback);
} |
java | @Pure
@Override
public int compare(Tuple3f<?> o1, Tuple3f<?> o2) {
if (o1==o2) return 0;
if (o1==null) return Integer.MIN_VALUE;
if (o2==null) return Integer.MAX_VALUE;
int cmp = Double.compare(o1.getX(), o2.getX());
if (cmp!=0) return cmp;
cmp = Double.compare(o1.getY(), o2.getY());
if (cmp!=0) return cmp;
return Double.compare(o1.getZ(), o2.getZ());
} |
python | def create_qgis_template_output(output_path, layout):
"""Produce QGIS Template output.
:param output_path: The output path.
:type output_path: str
:param composition: QGIS Composition object to get template.
values
:type composition: qgis.core.QgsLayout
:return: Generated output path.
:rtype: str
"""
# make sure directory is created
dirname = os.path.dirname(output_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
context = QgsReadWriteContext()
context.setPathResolver(QgsProject.instance().pathResolver())
layout.saveAsTemplate(output_path, context)
return output_path |
python | def new(arg_name, annotated_with=None):
"""Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey
"""
if annotated_with is not None:
annotation = annotations.Annotation(annotated_with)
else:
annotation = annotations.NO_ANNOTATION
return BindingKey(arg_name, annotation) |
python | def doctree_resolved(app, doctree, fromdocname):
"""
When the document, and all the links are fully resolved, we inject one
raw html element for running the command for processing the wavedrom
diagrams at the onload event.
"""
# Skip for non-html or if javascript is not inlined
if not app.env.config.wavedrom_html_jsinline:
return
text = """
<script type="text/javascript">
function init() {
WaveDrom.ProcessAll();
}
window.onload = init;
</script>"""
doctree.append(nodes.raw(text=text, format='html')) |
java | public CreateSessionResponse createSession(String description, String preset, String notification,
String securityPolicy, String recording, LivePublishInfo publish) {
CreateSessionRequest request = new CreateSessionRequest();
request.withPreset(preset).withDescription(description).withNotification(notification);
request.withSecurityPolicy(securityPolicy).withPublish(publish).withRecording(recording);
return createSession(request);
} |
java | public static void setFollowRedirects(boolean set) {
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
// seems to be the best check here...
sec.checkSetFactory();
}
followRedirects = set;
} |
python | def normalize_hex(hex_value):
"""
Normalize a hexadecimal color value to 6 digits, lowercase.
"""
match = HEX_COLOR_RE.match(hex_value)
if match is None:
raise ValueError(
u"'{}' is not a valid hexadecimal color value.".format(hex_value)
)
hex_digits = match.group(1)
if len(hex_digits) == 3:
hex_digits = u''.join(2 * s for s in hex_digits)
return u'#{}'.format(hex_digits.lower()) |
java | private void loadGrid() {
if (fetch() == 0) {
initGrid(0);
return;
}
Iterator<String> data = template.iterator();
String[] pcs = StrUtil.split(data.next(), StrUtil.U, 3);
int testcnt = StrUtil.toInt(pcs[0]);
int datecnt = StrUtil.toInt(pcs[1]);
int datacnt = StrUtil.toInt(pcs[2]);
if (datacnt == 0 || datecnt == 0) {
// showMessage("No data available within selected range.");
return;
}
initGrid(datecnt);
// Populate test names and units
for (int r = 0; r < testcnt; r++) {
addRow();
pcs = StrUtil.split(data.next(), StrUtil.U, 8);
String range = pcs[5] + "-" + pcs[6];
range = "-".equals(range) ? "" : range + " ";
setValue(0, r, WordUtils.capitalizeFully(pcs[2]), pcs[0]);
setValue(datecnt + 1, r, range + pcs[4], pcs[4]);
}
// Populate date headers
Map<String, Integer> headers = new HashMap<>();
for (int c = 1; c <= datecnt; c++) {
pcs = StrUtil.split(data.next(), StrUtil.U, 2);
FMDate date = new FMDate(pcs[1]);
Column column = getColumn(c);
DateTimebox dtb = (DateTimebox) column.getFirstChild();
dtb.setDate(date);
headers.put(pcs[0], c);
}
// Populate data cells
for (int i = 0; i < datacnt; i++) {
pcs = StrUtil.split(data.next(), StrUtil.U, 3);
int col = headers.get(pcs[0]);
int row = StrUtil.toInt(pcs[1]) - 1;
setValue(col, row, pcs[2], pcs[4]);
}
} |
python | def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(404/405). '''
targets, urlargs = self._match_path(environ)
if not targets:
raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO']))
method = environ['REQUEST_METHOD'].upper()
if method in targets:
return targets[method], urlargs
if method == 'HEAD' and 'GET' in targets:
return targets['GET'], urlargs
if 'ANY' in targets:
return targets['ANY'], urlargs
allowed = [verb for verb in targets if verb != 'ANY']
if 'GET' in allowed and 'HEAD' not in allowed:
allowed.append('HEAD')
raise HTTPError(405, "Method not allowed.",
header=[('Allow',",".join(allowed))]) |
python | def create_view(self, request):
"""
Initiates the organization and user account creation process
"""
try:
if request.user.is_authenticated():
return redirect("organization_add")
except TypeError:
if request.user.is_authenticated:
return redirect("organization_add")
form = org_registration_form(self.org_model)(request.POST or None)
if form.is_valid():
try:
user = self.user_model.objects.get(email=form.cleaned_data["email"])
except self.user_model.DoesNotExist:
user = self.user_model.objects.create(
username=self.get_username(),
email=form.cleaned_data["email"],
password=self.user_model.objects.make_random_password(),
)
user.is_active = False
user.save()
else:
return redirect("organization_add")
organization = create_organization(
user,
form.cleaned_data["name"],
form.cleaned_data["slug"],
is_active=False,
)
return render(
request,
self.activation_success_template,
{"user": user, "organization": organization},
)
return render(request, self.registration_form_template, {"form": form}) |
python | def create_store_credit_transaction(cls, store_credit_transaction, **kwargs):
"""Create StoreCreditTransaction
Create a new StoreCreditTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_store_credit_transaction(store_credit_transaction, async=True)
>>> result = thread.get()
:param async bool
:param StoreCreditTransaction store_credit_transaction: Attributes of storeCreditTransaction to create (required)
:return: StoreCreditTransaction
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_store_credit_transaction_with_http_info(store_credit_transaction, **kwargs)
else:
(data) = cls._create_store_credit_transaction_with_http_info(store_credit_transaction, **kwargs)
return data |
java | public void deleteLocalizationPoint(JsBus bus, LWMConfig dest) throws SIBExceptionBase, SIException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, "deleteLocalizationPoint", ((BaseDestination)dest).getName());
}
DestinationDefinition destDef = (DestinationDefinition) _me.getSIBDestination(bus.getName(), ((SIBDestination) dest).getName());
if (destDef == null) {
missingDestinations.add(destDef.getName());
}
if (!isInZOSServentRegion() && _mpAdmin != null) {
alterDestinations.add(destDef.getName());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "unlocalize: Dest unlocalized on existing destination deferring alter until end, Destination Name=" + destDef.getName());
}
// Now add code to call administrator to delete destination localization
deleteDestLocalizations(bus);
alterDestinations.remove(destDef.getName());
unlocalize(destDef);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "deleteLocalizationPoint");
} |
python | def send_fence(self):
'''send fence points from fenceloader'''
# must disable geo-fencing when loading
self.fenceloader.target_system = self.target_system
self.fenceloader.target_component = self.target_component
self.fenceloader.reindex()
action = self.get_mav_param('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE)
self.param_set('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE, 3)
self.param_set('FENCE_TOTAL', self.fenceloader.count(), 3)
for i in range(self.fenceloader.count()):
p = self.fenceloader.point(i)
self.master.mav.send(p)
p2 = self.fetch_fence_point(i)
if p2 is None:
self.param_set('FENCE_ACTION', action, 3)
return False
if (p.idx != p2.idx or
abs(p.lat - p2.lat) >= 0.00003 or
abs(p.lng - p2.lng) >= 0.00003):
print("Failed to send fence point %u" % i)
self.param_set('FENCE_ACTION', action, 3)
return False
self.param_set('FENCE_ACTION', action, 3)
return True |
python | def infer_namespaces(ac):
"""infer possible namespaces of given accession based on syntax
Always returns a list, possibly empty
>>> infer_namespaces("ENST00000530893.6")
['ensembl']
>>> infer_namespaces("ENST00000530893")
['ensembl']
>>> infer_namespaces("ENSQ00000530893")
[]
>>> infer_namespaces("NM_01234")
['refseq']
>>> infer_namespaces("NM_01234.5")
['refseq']
>>> infer_namespaces("NQ_01234.5")
[]
>>> infer_namespaces("A2BC19")
['uniprot']
>>> sorted(infer_namespaces("P12345"))
['insdc', 'uniprot']
>>> infer_namespaces("A0A022YWF9")
['uniprot']
"""
return [v for k, v in ac_namespace_regexps.items() if k.match(ac)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.