id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
2213380_0 | public double calculateRisk(double baselineSurvival) {
return calculateRisk(baselineSurvival, linearPredictor());
} |
2221963_20 | public void h3() {
delegate.h3();
} |
2254694_7 | public Converter<?> getConverter(Class<?> type, Annotation[] annotations) {
for (ConverterFactory factory : factories) {
Converter<?> converter = factory.createConverter(type, annotations);
if (converter != null) {
return converter;
}
}
throw new NoConverterException(type);
} |
2259237_53 | protected void populateServiceAlerts(Set<String> serviceAlertDescriptions, List<ServiceAlertBean> serviceAlertBeans) {
populateServiceAlerts(serviceAlertDescriptions, serviceAlertBeans, true);
} |
2271327_0 | public static LoadableDetachableModel loadedModel(final Object bean,
final String loadMethod)
{
// assert that method exists
ReflectUtils.getZeroArgMethod(bean.getClass(), loadMethod);
return new LoadableDetachableModel() {
@Override protected Object load()
{
return ReflectUtils.invokeZeroArgMethod(bean, loadMethod);
}
};
} |
2272670_4 | @Factory
public static Matcher<Object> isApproved() throws IOException {
final StackTraceElement trace = StackUtils
.getCallingTestMethodStackTraceElement();
final String methodName = trace.getMethodName();
final String className = getClassName(trace);
final Class<?> clazz = getClassObject(trace);
return looksLike(String.format("%s.%s.png", className, methodName),
clazz);
} |
2287347_24 | public List<AggregatedSegment> aggregateSegments(List<? extends ConnectableSegment> segments) {
List<AggregatedSegment> aggregatedSegments = new ArrayList<AggregatedSegment>();
for (Iterator<? extends ConnectableSegment> it = segments.iterator(); it.hasNext();) {
ConnectableSegment segment = it.next();
AggregatedSegment newAggregatedSegment = new AggregatedSegment(segment);
if (!canConnect(aggregatedSegments, newAggregatedSegment))
aggregatedSegments.add(newAggregatedSegment);
}
return aggregateMore(aggregatedSegments);
} |
2293442_5 | public static String toOID(UUID uuid) {
return toOID(uuid, OID_ROOT);
} |
2296450_8 | static void populateDataIndexFromAnnotations(final AnnotationData data,
final Class expectedAnnotationClass,
final Method targetMethod)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (!UPDATES.contains(expectedAnnotationClass)) { return; }
final ReturnDataUpdateContent returnAnnotation = targetMethod.getAnnotation(ReturnDataUpdateContent.class);
if (returnAnnotation != null) {
data.setDataIndex(-1);
return;
}
final Annotation[][] paramAnnotationArrays = targetMethod.getParameterAnnotations();
int foundIndex = Integer.MIN_VALUE;
if (paramAnnotationArrays != null && paramAnnotationArrays.length > 0) {
for (int ix = 0; ix < paramAnnotationArrays.length; ix++) {
final Annotation[] paramAnnotations = paramAnnotationArrays[ix];
if (paramAnnotations != null && paramAnnotations.length > 0) {
for (int jx = 0; jx < paramAnnotations.length; jx++) {
final Annotation paramAnnotation = paramAnnotations[jx];
if (ParameterDataUpdateContent.class.equals(paramAnnotation.annotationType())) {
if (foundIndex >= 0) {
throw new InvalidParameterException(String.format(
"Multiple annotations of type [%s] found on method [%s]",
ParameterDataUpdateContent.class.getName(),
targetMethod.getName()
));
}
foundIndex = ix;
}
}
}
}
}
if (foundIndex < 0) {
throw new InvalidParameterException(String.format(
"No KeyProvider annotation found method [%s]",
targetMethod.getName()
));
}
data.setDataIndex(foundIndex);
} |
2304277_106 | public static String getMetadataInstance(final String metadataId) {
if (isIdentifyingInstance(metadataId)) {
return metadataId.substring(metadataId.indexOf(INSTANCE_DELIMITER) + 1);
}
return null;
} |
2306348_0 | public String sayHello( String who )
{
return "Hello " + who;
} |
2306900_3 | @Override
public List<String> getAddressesForApplication(String jid) {
return delegateStore.getAddressesForApplication(jid);
} |
2311431_0 | public final int orientation(Vertex a, Vertex b, Vertex c) {
double result = Geometry.leftOfPlane(a.x, a.y, a.z, b.x, b.y, b.z, c.x,
c.y, c.z, x, y, z);
if (result > 0.0) {
return 1;
} else if (result < 0.0) {
return -1;
}
return 0;
} |
2316136_86 | public AggregationType getAggregateType() {
return aggregateType;
} |
2316191_151 | public SerializedResultSet doPreview( String connectionName, String query, String previewLimit )
throws DatasourceServiceException {
if ( !hasDataAccessPermission() ) {
logger.error( Messages.getErrorString( "DatasourceServiceImpl.ERROR_0001_PERMISSION_DENIED" ) ); //$NON-NLS-1$
throw new DatasourceServiceException( Messages
.getErrorString( "DatasourceServiceImpl.ERROR_0001_PERMISSION_DENIED" ) ); //$NON-NLS-1$
}
SerializedResultSet returnResultSet;
try {
connectionName = UtilHtmlSanitizer.getInstance().safeEscapeHtml( connectionName );
executeQuery( connectionName, query, previewLimit );
returnResultSet = DatasourceServiceHelper.getSerializeableResultSet( connectionName, query,
Integer.parseInt( previewLimit ), PentahoSessionHolder.getSession() );
} catch ( QueryValidationException e ) {
throw new DatasourceServiceException( Messages.getErrorString(
"DatasourceServiceImpl.ERROR_0009_QUERY_VALIDATION_FAILED", e.getLocalizedMessage() ), e ); //$NON-NLS-1$
} catch ( SqlQueriesNotSupportedException e ) {
throw new DatasourceServiceException( e.getLocalizedMessage(), e ); //$NON-NLS-1$
}
return returnResultSet;
} |
2316200_293 | public void closeChangePasswordDialog() {
zkHelper.findComponent(CHANGE_PASSWORD_DIALOG).detach();
} |
2316202_113 | public Integer getNewPmCountFor(String username) {
Element cacheElementForUser = userDataCache.get(username);
if (cacheElementForUser == null) {
return null;
}
return (Integer) cacheElementForUser.getValue();
} |
2335594_25 | public CheckStylePluginException wrap(@Nullable final String message, @NotNull final Throwable error) {
final Throwable root = rootOrCheckStyleException(error);
final String exMessage = ofNullable(message).orElseGet(root::getMessage);
if (isParseException(root)) {
return new CheckStylePluginParseException(exMessage, root);
}
return new CheckStylePluginException(exMessage, root);
} |
2341027_0 | @Override
public int readTo(DecoderAdapter dest, String encoded, MessageParamField field ) {
int decodedValue = IntegerEncoded.parseInt(encoded, radix);
dest.putInt(field.dbFieldName, decodedValue);
return 1;
} |
2349183_21 | public static TaskId toTaskID(String tid) {
Iterator<String> it = _split(tid).iterator();
return toTaskID(TASK, tid, it);
} |
2349728_0 | public static Repository eventRepoToRepo(GitHubEvent.RepoIdentifier repo) {
String[] ref = repo.repoWithUserName().split("/");
return InfoUtils.createRepoFromData(ref[0], ref[1]);
} |
2357859_654 | @Override
public void filter(DocumentIndexingPackage dip) throws IndexingException {
log.debug("Performing set access status filter on {}", dip.getPid());
dip.getDocument().setStatus(determineAccessStatus(dip));
} |
2364987_147 | @Override
public void orFallBackTo(Runnable defaultClosure) {
defaultClosure.run();
} |
2383782_393 | public String parse(Element root) {
return parseWithName(root, null);
} |
2389245_26 | public static void renameCascadingParentLinks(final String oldName, final String newName) throws IOException {
if (StringUtils.isBlank(newName) || StringUtils.isBlank(oldName)) {
return;
}
for (Job job : Hudson.getInstance().getAllItems(Job.class)) {
if (oldName.equals(job.getCascadingProjectName())) {
job.renameCascadingProjectNameTo(newName);
}
}
} |
2394379_79 | @Override
public boolean matches(Document document, Document query) {
for (String key : query.keySet()) {
Object queryValue = query.get(key);
validateQueryValue(queryValue, key);
if (!checkMatch(queryValue, key, document)) {
return false;
}
}
return true;
} |
2397476_0 | public DateTime getValue()
{
return value;
} |
2403733_3 | public PromoteKeyResult execute(long masterKeyId, byte[] cardAid, long[] subKeyIds) {
OperationLog log = new OperationLog();
log.add(LogType.MSG_PR, 0);
// Perform actual type change
UncachedKeyRing promotedRing;
{
try {
log.add(LogType.MSG_PR_FETCHING, 1,
KeyFormattingUtils.convertKeyIdToHex(masterKeyId));
CanonicalizedPublicKeyRing pubRing =
mProviderHelper.getCanonicalizedPublicKeyRing(masterKeyId);
if (subKeyIds == null) {
log.add(LogType.MSG_PR_ALL, 1);
} else {
// sort for binary search
for (CanonicalizedPublicKey key : pubRing.publicKeyIterator()) {
long subKeyId = key.getKeyId();
if (naiveIndexOf(subKeyIds, subKeyId) != null) {
log.add(LogType.MSG_PR_SUBKEY_MATCH, 1,
KeyFormattingUtils.convertKeyIdToHex(subKeyId));
} else {
log.add(LogType.MSG_PR_SUBKEY_NOMATCH, 1,
KeyFormattingUtils.convertKeyIdToHex(subKeyId));
}
}
}
// create divert-to-card secret key from public key
promotedRing = pubRing.createDivertSecretRing(cardAid, subKeyIds);
} catch (NotFoundException e) {
log.add(LogType.MSG_PR_ERROR_KEY_NOT_FOUND, 2);
return new PromoteKeyResult(PromoteKeyResult.RESULT_ERROR, log, null);
}
}
// If the edit operation didn't succeed, exit here
if (promotedRing == null) {
// error is already logged by modification
return new PromoteKeyResult(PromoteKeyResult.RESULT_ERROR, log, null);
}
// Check if the action was cancelled
if (checkCancelled()) {
log.add(LogType.MSG_OPERATION_CANCELLED, 0);
return new PromoteKeyResult(PgpEditKeyResult.RESULT_CANCELLED, log, null);
}
// Cannot cancel from here on out!
setPreventCancel();
// Save the new keyring.
SaveKeyringResult saveResult = mProviderHelper
.saveSecretKeyRing(promotedRing, new ProgressScaler(mProgressable, 60, 95, 100));
log.add(saveResult, 1);
// If the save operation didn't succeed, exit here
if (!saveResult.success()) {
return new PromoteKeyResult(PromoteKeyResult.RESULT_ERROR, log, null);
}
updateProgress(R.string.progress_done, 100, 100);
log.add(LogType.MSG_PR_SUCCESS, 0);
return new PromoteKeyResult(PromoteKeyResult.RESULT_OK, log, promotedRing.getMasterKeyId());
} |
2408915_45 | public int getResourceId(Context context) {
int resourceId = context.getResources().getIdentifier(
resourceName, resourceType, hasResourcePackage() ? resourcePackage : context.getPackageName());
checkResource(resourceId);
return resourceId;
} |
2416378_14 | public boolean inherits(ASTType astType, ASTType inheritable) {
if (astType == null) {
return false;
}
if(inheritable == null || inheritable.equals(OBJECT_TYPE)){
return true;
}
if (astType.equals(inheritable)) {
return true;
}
for (ASTType typeInterfaces : astType.getInterfaces()) {
if (inherits(typeInterfaces, inheritable)) {
return true;
}
}
return inherits(astType.getSuperClass(), inheritable);
} |
2422006_24 | public void shutdown() {
keepRunning = false;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
logger.error("Error shutting down thread with hook", e);
}
} |
2425139_0 | @Name("insert")
@Description("Insert Geoff subgraph into the database from a list of rule strings")
@PluginTarget(GraphDatabaseService.class)
public Representation insert(
@Source GraphDatabaseService graphDB,
@Description("Geoff subgraph to insert")
@Parameter(name = "subgraph", optional = false) String[] subgraph,
@Description("Named entity references to pass into insert routine")
@Parameter(name = "params", optional = true) Map params
)
throws SubgraphError, SyntaxError
{
return new GeoffResultRepresentation(
Geoff.insertIntoNeo4j(new Subgraph(subgraph), graphDB, GeoffParams.toEntities(params, graphDB))
);
} |
2432524_5 | public static String prettyPrint( String xml )
{
return prettyPrint( xml, INDENT_NUMBER );
} |
2434719_21 | public boolean contains(int charCode) {
boolean found = false;
for (int i = 0; !found && i < size(); i++) {
CharacterRange range = get(i);
if (range.characterSet != null) {
// Version 1 CGT
found = range.characterSet.contains(String.valueOf((char)charCode));
} else {
// Version 5 EGT
found = charCode >= range.start && charCode <= range.end;
}
}
return found;
} |
2438993_1 | public String getContextPath() {
return this.contextPath;
} |
2449032_110 | Value not () {
throw newOperandException ("not");
} |
2466190_0 | public static File getEncryptedFilename(File file) {
String filename = file.getName();
return filename.endsWith(ENCRYPTED_FILENAME_SUFFIX) ? file : new File(file.getParent(), filename + ENCRYPTED_FILENAME_SUFFIX);
} |
2470704_0 | protected float normalize(float score, int longestString){
return 1f - (score / longestString);
} |
2474070_1 | public static Gson createGson(Context context)
{
if (gson == null)
{
GsonBuilder builder = new GsonBuilder();
if (context == null || Feature.get(context, R.bool.feature_load_old_experiences).isEnabled())
{
builder.registerTypeAdapterFactory(new ExperienceTypeAdapterFactor());
}
gson = builder.create();
}
return gson;
} |
2477847_190 | public MarkupLanguage getMarkupLanguage(final String languageName) throws IllegalArgumentException {
checkArgument(!Strings.isNullOrEmpty(languageName), "Must provide a languageName"); //$NON-NLS-1$
Pattern classNamePattern = Pattern.compile("\\s*([^\\s#]+)?#?.*"); //$NON-NLS-1$
// first try Java services (jar-based)
final List<String> names = new ArrayList<>();
final List<MarkupLanguage> languages = new ArrayList<>();
final MarkupLanguage[] result = new MarkupLanguage[1];
loadMarkupLanguages(new MarkupLanguageVisitor() {
public boolean accept(MarkupLanguage language) {
if (languageName.equals(language.getName())) {
result[0] = language;
return false;
}
languages.add(language);
names.add(language.getName());
return true;
}
});
if (result[0] != null) {
return result[0];
}
// next attempt to load the markup language as if the language name is a fully qualified name
Matcher matcher = classNamePattern.matcher(languageName);
if (matcher.matches()) {
String className = matcher.group(1);
if (className != null) {
// first try to load from a discovered markup language since this will circumvent
// classloader issues
for (MarkupLanguage language : languages) {
if (className.equals(language.getClass().getName())) {
return language;
}
}
try {
Class<?> clazz = Class.forName(className, true, classLoader);
if (MarkupLanguage.class.isAssignableFrom(clazz)) {
MarkupLanguage instance = (MarkupLanguage) clazz.newInstance();
return instance;
}
} catch (Exception e) {
// ignore
}
}
}
Collections.sort(names);
// specified language not found.
// create a useful error message
StringBuilder buf = new StringBuilder();
for (String name : names) {
if (buf.length() != 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append('\'');
buf.append(name);
buf.append('\'');
}
throw new IllegalArgumentException(MessageFormat.format(Messages.getString("ServiceLocator.4"), //$NON-NLS-1$
languageName, buf.length() == 0
? Messages.getString("ServiceLocator.5") //$NON-NLS-1$
: Messages.getString("ServiceLocator.6") + buf)); //$NON-NLS-1$
} |
2478263_260 | @RequestMapping(value = "/findExternalUrlForStudy/{studyTitle}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String findExternalLinkForStudyWithTitle(HttpServletRequest request, @PathVariable("studyTitle") String taxonName) throws IOException {
return ExternalIdUtil.getUrlFromExternalId(CypherUtil.executeRemote(findExternalIdForStudyNew(request, taxonName)));
} |
2479886_26 | @Override
public String toString() {
StringBuffer sb = new StringBuffer();
StringBuffer text = new StringBuffer();
byte c;
int len = bb.limit();
int lengthRoundedUpToNextMultipleOf16 = (int) Math.ceil(len / 16.0) * 16;
sb.append("apid: " + getAPID() + "\n");
sb.append("packetId: " + getPacketID() + "\n");
for (int i = 0; i < lengthRoundedUpToNextMultipleOf16; ++i) {
// If we are at the beginning of a 16 byte multiple
if (i % 16 == 0) {
sb.append(String.format("%04x:", i));
text.setLength(0);
}
// For every 2 bytes, insert an extra space
if ((i & 1) == 0) {
sb.append(" ");
}
// If we did not reach the end of the buffer
if (i < len) {
c = bb.get(i);
// Add 2 byte hexadecimal translation of the byte
sb.append(String.format("%02x", 0xFF & c));
// Add printable characters or a dot to the ASCII buffer of the line being parsed
text.append(((c >= ' ') && (c <= 127)) ? String.format("%c", c) : ".");
} else { // If we reached the end of the buffer
// Pad with spaces
sb.append(" ");
text.append(" ");
}
// If we reached the end of a 16 byte multiple
if ((i + 1) % 16 == 0) {
// Append the ASCII buffer of the parsed line
sb.append(" ");
sb.append(text);
sb.append("\n");
}
}
// End with an extra newline
sb.append("\n");
return sb.toString();
} |
2485432_0 | public byte[] getNetmaskAddress() {
return netmaskAddress;
} |
2488113_3 | @Override
public LinkableInfo getLinkableInfo(String link) {
LinkableInfo linkableInfo = linkableMapping.get(link);
Validate.notNull(linkableInfo, "Invalid link: " + link);
return linkableInfo;
} |
2488848_139 | public boolean exists(@Nullable ID subject, @Nullable UID predicate, @Nullable NODE object, @Nullable UID context) {
return findStatements(subject, predicate, object, context, false).hasNext();
} |
2491679_4 | @Override
public boolean isValid(String pis, final ConstraintValidatorContext context) {
boolean result = false;
if ( pis == null || "".equals(pis) ) {
result = true;
} else {
result = PISPASEP.isValido(pis);
}
return result;
} |
2497245_83 | @Nonnull
public static SizeValue percent(final int percentage) {
return new SizeValue(percentage, SizeValueType.Percent);
} |
2499324_6 | protected LinkType getLinkType(long linkTypeVal) {
switch ((int)linkTypeVal) {
case 0:
return LinkType.NULL;
case 1:
return LinkType.EN10MB;
case 101:
return LinkType.RAW;
case 108:
return LinkType.LOOP;
case 113:
return LinkType.LINUX_SLL;
}
return null;
} |
2500369_7 | @Override
public void parseArguments(final ParsedArguments parsedArguments, final String... arguments) throws ArgumentValidationException
{
boolean finishedOptions = false;
for (final String argument : arguments)
{
if(finishedOptions)
{
parsedArguments.addValue(argument);
}
else
{
finishedOptions = add(parsedArguments, argument);
}
}
} |
2501197_4 | public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyPath, Class<?>... groups) {
Set<ConstraintViolation<T>> violations = new HashSet<ConstraintViolation<T>>();
try {
int currentIndex = -1;
String currentPropertyPath;
do {
currentIndex = propertyPath.indexOf(".", ++currentIndex);
if (currentIndex >= 0) {
currentPropertyPath = propertyPath.substring(0, currentIndex);
} else {
currentPropertyPath = propertyPath;
}
Set<ConstraintViolation<T>> currentViolations = validator.validateProperty(object, currentPropertyPath, groups);
ConstraintViolation<T> notNullViolation = findNotNullViolation(currentViolations);
if (notNullViolation == null) {
violations = currentViolations;
} else {
violations.add(notNullViolation);
break;
}
} while (currentIndex >= 0);
} catch (IllegalArgumentException e) {
// ignore null property path
}
return violations;
} |
2505794_638 | @Override public boolean evaluate(final T instance) {
return any(predicates, new UnaryPredicate<UnaryPredicate<? super T>>() {
@Override public boolean evaluate(UnaryPredicate<? super T> predicate) {
return predicate.evaluate(instance);
}
});
} |
2510313_7 | @Override
public OngoingReadingWithoutWhere match(PatternElement... pattern) {
return this.match(false, pattern);
} |
2516145_2 | public String[] asArray(String value){
return value.split(",");
} |
2521501_29 | public void confirm(String message, BooleanCallback callback) {
confirm(null, message, callback);
} |
2524488_375 | @Override
public synchronized void fetchColumn(Text colFam, Text colQual) {
checkArgument(colFam != null, "colFam is null");
checkArgument(colQual != null, "colQual is null");
Column c = new Column(TextUtil.getBytes(colFam), TextUtil.getBytes(colQual), null);
fetchedColumns.add(c);
} |
2536041_2 | public static void addJarDirToDistributedCache(Configuration conf, File jarDirectory)
throws IOException {
if (!jarDirectory.exists() || !jarDirectory.isDirectory()) {
throw new IOException("Jar directory: " + jarDirectory.getCanonicalPath() + " does not "
+ "exist or is not a directory.");
}
for (File file : jarDirectory.listFiles()) {
if (!file.isDirectory() && file.getName().endsWith(".jar")) {
addJarToDistributedCache(conf, file);
}
}
} |
2544900_7 | public double[] evaluateSchedule(Integer[] jobArray)
{
_schedule = null;
return evaluateSchedule(jobArray, false);
} |
2548552_0 | public void sort(int[] values) {
// Check for empty or null array
if (values ==null || values.length==0){
return;
}
this.numbers = values;
number = values.length;
quicksort(0, number - 1);
} |
2550825_37 | public Map<String, String> getRouterConfigInformation(RouterConfig routerConfig) {
Map<String, String> result = new HashMap<String, String>();
result.put("Router", routerConfig.getClass().getSimpleName());
String routerDispatcher = routerConfig.routerDispatcher();
result.put("Router Dispatcher", routerDispatcher);
result.putAll(extract(routerConfig));
return result;
} |
2562371_4 | protected void newRule(Class<?> ruleClass, NewRepository repository) {
org.sonar.check.Rule ruleAnnotation = AnnotationUtils.getAnnotation(ruleClass, org.sonar.check.Rule.class);
if (ruleAnnotation == null) {
throw new IllegalArgumentException("No Rule annotation was found on " + ruleClass);
}
String ruleKey = ruleAnnotation.key();
if (Strings.isNullOrEmpty(ruleKey)) {
throw new IllegalArgumentException("No key is defined in Rule annotation of " + ruleClass);
}
NewRule rule = repository.rule(ruleKey);
if (rule == null) {
throw new IllegalStateException("No rule was created for " + ruleClass + " in " + repository.key());
}
// Check whether it is a Rule Template.
rule.setTemplate(AnnotationUtils.getAnnotation(ruleClass, RuleTemplate.class) != null);
ruleMetadata(ruleClass, rule);
} |
2562751_4 | static byte[] convertBoolArrayToByteArray(boolean[] boolArr) {
byte[] byteArr = new byte[(boolArr.length + 7) / 8];
for (int i = 0; i < byteArr.length; i++) {
byteArr[i] = readByte(boolArr, 8 * i);
}
return byteArr;
} |
2572668_0 | @Override
public Set<User> searchUsers(UserSearchCriteria criteria) {
final Set<User> users = this.listUsers();
final Set<User> filteredUsers = this.filterListInMemeory(users, criteria);
logger.debug("filteredUsers({}): {}", criteria, filteredUsers);
return filteredUsers;
} |
2573331_1 | private List<String> getUniprotMappings(Model aUpModel) {
QueryExecution ex = QueryExecutionFactory
.create("SELECT ?x WHERE{?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://purl.uniprot.org/core/Protein>}",
aUpModel);
ResultSet rs = ex.execSelect();
List<String> returnMe = new ArrayList<String>();
while (rs.hasNext()) {
QuerySolution sol = rs.next();
Resource r = sol.getResource("x");
String lPattern = "http:\\/\\/purl.uniprot.org\\/uniprot\\/(\\w+)";
Pattern p = Pattern.compile(lPattern);
Matcher m = p.matcher(r.getURI());
if (m.matches()) {
returnMe.add(m.group(1).trim());
}
}
return returnMe;
} |
2576064_42 | public static Map<String, List<CtxModelObject>> sortByObfuscability(List<CtxModelObject> ctxDataList) {
if (null == ctxDataList || ctxDataList.size() <= 0) {
// LOG.error("Can't sort null values");
return null;
}
String notObfuscableType = "NOT_OBFUCSABLE";
DataTypeUtils dataTypeUtils = new DataTypeUtils();
ObfuscatorInfoFactory obfuscatorInfoFactory = new ObfuscatorInfoFactory();
Map<String, List<CtxModelObject>> sorted = new HashMap<String, List<CtxModelObject>>();
for(CtxModelObject data : ctxDataList) {
List<CtxModelObject> dataTypeGroup = null;
String dataType = data.getId().getType();
// -- Directly an obfuscable type ?
ObfuscatorInfo obfuscatorInfo = obfuscatorInfoFactory.getObfuscatorInfo(dataType);
if (null != obfuscatorInfo && obfuscatorInfo.isObfuscable()) {
dataTypeGroup = new ArrayList<CtxModelObject>();
dataTypeGroup.add(data);
sorted.put(dataType, dataTypeGroup);
continue;
}
// -- Parent obfuscable?
// Retrieve parent type
String dataTypeParent = dataTypeUtils.getParent(dataType);
// Already a parent type
if (null == dataTypeParent) {
dataTypeParent = dataType;
}
// Is obfuscable ?
obfuscatorInfo = obfuscatorInfoFactory.getObfuscatorInfo(dataTypeParent);
if (null == obfuscatorInfo || !obfuscatorInfo.isObfuscable()) {
dataTypeParent = notObfuscableType;
}
// Retrieve this group or create it
dataTypeGroup = sorted.get(dataTypeParent);
if (null == dataTypeGroup) {
dataTypeGroup = new ArrayList<CtxModelObject>();
}
// Add data
dataTypeGroup.add(data);
sorted.put(dataTypeParent, dataTypeGroup);
}
return sorted;
} |
2576181_14 | public void addMethodListener(String regex, RegexMethodInterceptorListener<T> listener) {
if(listener == null) {
throw new IllegalArgumentException("listener cannot be null.");
}
Set<RegexMethodInterceptorListener<T>> set = listeners.get(regex);
if(set == null) {
set = new HashSet<RegexMethodInterceptorListener<T>>();
listeners.put(regex, set);
}
set.add(listener);
} |
2580771_3 | @Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
// url format = /cache/key so get the key from path
String path = req.getPathInfo();
String servletPath = req.getServletPath();
String key = retrieveKeyFromPath( path );
if ( StringUtils.isEmpty( key ) )
{
resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "key missing in path" );
return;
}
String acceptContentType = req.getHeader( "Accept" );
if ( StringUtils.isEmpty( acceptContentType ) )
{
resp.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"you must specify Accept with Content-Type you want in the response" );
return;
}
ContentTypeHandler contentTypeHandler = findGetCacheContentTypeHandler( req, resp );
if ( contentTypeHandler == null )
{
String contentType = req.getContentType();
log.error( "No content type handler for content type {}", acceptContentType );
resp.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Content-Type: " + acceptContentType + " not supported" );
return;
}
byte[] bytes = cacheService.retrieveByteArray( key );
log.debug( "return content size {} for key {}", ( bytes == null ? "null" : bytes.length ), key );
if ( bytes == null || bytes.length == 0 )
{
resp.sendError( HttpServletResponse.SC_NO_CONTENT, "No content for key: " + key );
return;
}
try
{
byte[] respBytes =
contentTypeHandler.handleGet( new DirectMemoryRequest().setKey( key ), bytes, resp, req );
resp.getOutputStream().write( respBytes );
}
catch ( DirectMemoryException e )
{
resp.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage() );
}
} |
2588654_1 | protected boolean updatePeakForChannel(Network network, Channel channel) {
try {
int storedCount = getCount(network, channel);
int numberCurrentlyOnChannel = channel.getNicks().size();
if (storedCount < numberCurrentlyOnChannel) {
peaks.put(channelIdentifier(network, channel), "" + numberCurrentlyOnChannel);
return true;
}
} catch (NumberFormatException nfe) {
logger.error("Malformed data for Peak plugin stored in peaks. Deactivating plugin.", nfe.getCause());
this.enabled = false;
}
return false;
} |
2611961_0 | public static String estimateAge(String birthdate) throws ParseException {
Date date = RegistrationUtils.parseDate(birthdate);
return PatientUtils.estimateAge(date);
} |
2613332_20 | @SuppressWarnings("unchecked")
@Override
public DashBoardPage render(RenderTime timer)
{
basicRender(timer);
// We don't know if the dashlets will appear so do the basic rendering
try
{
getDashlet("my-sites").render(timer);
getDashlet("my-documents").render(timer);
getDashlet("activities").render(timer);
}
catch (PageException pe)
{
throw new PageException(this.getClass().getName() + " failed to render in time", pe);
}
return this;
} |
2614085_60 | @Override
public boolean appliesTo(IPortletDefinition portlet) {
final boolean portletMatch =
portletName.equalsIgnoreCase(portlet.getPortletDescriptorKey().getPortletName());
final boolean webappMatch =
webappName.equalsIgnoreCase(portlet.getPortletDescriptorKey().getWebAppName());
final boolean preferenceMatch =
portlet.getPortletPreferences().stream()
.anyMatch(
preference ->
preference.getName().equalsIgnoreCase(preferenceName));
return portletMatch && webappMatch && preferenceMatch;
} |
2618757_4 | public Map<String, Schema> getNamedMappings() {
ensureInit();
return nameToSchemaMappings;
} |
2622727_0 | public static HttpRequest get(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
} |
2622978_77 | public final void onAfterTestMethod(@Observes(precedence = 45) AfterPersistenceTest event) {
executeCacheEviction(event, TestExecutionPhase.AFTER);
} |
2624179_0 | @Action
void registerConnector( @Nonnull final Connector connector )
{
if ( Replicant.shouldCheckInvariants() )
{
invariant( () -> _connectors.stream()
.noneMatch( e -> e.getConnector().getSchema().getId() == connector.getSchema().getId() ),
() -> "Replicant-0015: Invoked registerConnector for system schema named '" +
connector.getSchema().getName() + "' but a Connector for specified schema exists." );
}
getConnectorsObservableValue().preReportChanged();
final ConnectorEntry entry = new ConnectorEntry( connector, true );
_connectors.add( entry );
DisposeNotifier
.asDisposeNotifier( connector )
.addOnDisposeListener( this, () -> deregisterConnector( connector ) );
getConnectorsObservableValue().reportChanged();
} |
2626654_7 | public static String stripAndFillSessionData(final String url, final UrlDataImpl urldata) {
final int pos = url.indexOf(';');
if (pos != -1) {
final char[] data = url.toCharArray();
int sessionStart;
if ((sessionStart = indexOf(data, jsessionLower, pos)) != -1 || (sessionStart = indexOf(data, jsessionUpper, pos)) != -1) {
int sessionEnd = indexOf(data, SEMICOLON, sessionStart + 1);
if (sessionEnd == -1) {
sessionEnd = indexOf(data, QUESTION, sessionStart + 1);
}
if (sessionEnd == -1) { // still
sessionEnd = data.length;
}
final int len = sessionEnd - sessionStart;
if (len > 0) {
if (urldata != null) {
urldata.setjSessionId(new String(data, sessionStart + 1, len - 1));
}
System.arraycopy(data, sessionStart + len, data, sessionStart, data.length - sessionEnd);
return new String(data, 0, data.length - len);
}
}
}
return url;
} |
2647335_4 | public String forGroup(String groupName, ResourceHtmlTag tag) {
return namePattern
.replace("@groupName@", groupName)
.replace("@extension@", tag.getExtension());
} |
2651891_0 | public String get() {
if (stringList.isEmpty()) {
return null;
} else {
String result = stringList.remove(0);
return result;
}
} |
2656737_4 | public String createConsentCDA(Patient patient,
PatientConsentPolicy policy, DocumentEntry documentEntry) {
// Basic checks
if (patient == null)
throw new IllegalArgumentException("Patient cannot be null.");
if (policy == null)
throw new IllegalArgumentException("policy cannot be null.");
if (documentEntry == null)
throw new IllegalArgumentException("documentEntry cannot be null.");
StringWriter writer = new StringWriter();
/* create a context and add data */
VelocityContext context = new VelocityContext();
/* load Metadata */
context = createMetaContext(context, patient, policy, documentEntry);
context.put(TAG_CDA_ID_ROOT, documentEntry.getUniqueId());
context.put(TAG_CDA_CODE_CODE, documentEntry.getTypeCode().getCode());
context.put(TAG_CDA_CODE_DISPLAYNAME, documentEntry.getTypeCode()
.getDisplayName().getValue());
context.put(TAG_CDA_CODE_CODESYSTEM, CDA_CODE_CODESYSTEM_OID);
context.put(TAG_CDA_CODE_CODESYSTEMNAME, documentEntry.getTypeCode()
.getSchemeName());
context.put(TAG_CDA_EFFECTIVETIME, documentEntry.getCreationTime());
context.put(TAG_CDA_CONFIDENTIALTY_CODE, documentEntry
.getConfidentialityCodes().get(0).getCode());
context.put(TAG_CDA_CONFIDENTIALTY_DISPLAYNAME, documentEntry
.getConfidentialityCodes().get(0).getDisplayName().getValue());
context.put(TAG_CDA_CONFIDENTIALTY_CODESYSTEM,
CDA_CONFIDENTIALTY_CODESYSTEM_OID);
context.put(TAG_CDA_CONFIDENTIALTY_CODESYSTEMNAME, documentEntry
.getConfidentialityCodes().get(0).getSchemeName());
context.put(TAG_CDA_LANGUAGECODE, documentEntry.getLanguageCode());
context.put(TAG_CDA_Author_TITLE, documentEntry.getAuthor()
.getAuthorPerson().getName().getPrefix());
context.put(TAG_CDA_Author_FAMILY, documentEntry.getAuthor()
.getAuthorPerson().getName().getFamilyName());
context.put(TAG_CDA_Author_GIVEN, documentEntry.getAuthor()
.getAuthorPerson().getName().getGivenName());
context.put(TAG_CDA_VALIDFROM, documentEntry.getServiceStartTime());
context.put(TAG_CDA_VALIDUNTIL, documentEntry.getServiceStopTime());
try {
/* now render the template into a StringWriter */
t.merge(context, writer);
} catch (Exception e) {
throw new CDACreationException(e.getLocalizedMessage(), e);
}
/* show the World */
LOG.debug(writer.toString());
return writer.toString();
} |
2657795_0 | @Override
public MuleEvent process(MuleEvent event) throws MuleException, NullPointerException {
checkNotNull(event, "event");
return getFlow(event.getMuleContext()).process(event);
} |
2666578_179 | @Override
public int hashCode()
{
int hash = 17;
hash = hash * 31 + key.hashCode();
hash = hash * 31 + ( ( value != null ) ? value.hashCode() : 0 );
return hash;
} |
2666662_13 | static CreationFactory createCreationFactory(final String baseURI, final Map<String, Object> pathParameterValues,
final Method method)
throws URISyntaxException {
final Path classPathAnnotation = method.getDeclaringClass().getAnnotation(Path.class);
final OslcCreationFactory creationFactoryAnnotation = method.getAnnotation(
OslcCreationFactory.class);
final Path methodPathAnnotation = method.getAnnotation(Path.class);
CreationFactory creationFactory = createCreationFactory(baseURI, pathParameterValues,
classPathAnnotation, creationFactoryAnnotation, methodPathAnnotation);
return creationFactory;
} |
2675355_2 | public Node deserializeObject(JsonReader reader) {
Log.info("Deserializing JSON to Node.");
JsonObject jsonObject = reader.readObject();
return deserializeObject(jsonObject);
} |
2675654_37 | public static DependencyAtom getMinimumVersion(DependencyAtom left, DependencyAtom right) {
String leftVersion = left.getPropertyValue();
String rightVersion = right.getPropertyValue();
if ((leftVersion == null) || (rightVersion == null) || leftVersion.equals(rightVersion)) {
return null;
}
String[] leftVersions = leftVersion.split("\\.");
String[] rightVersions = rightVersion.split("\\.");
for (int i = 0; i < leftVersions.length; i++) {
String leftCandidate = leftVersions[i];
String rightCandidate = null;
if (rightVersions.length > i) {
rightCandidate = rightVersions[i];
}
if (rightCandidate == null) {
return right;
}
if (leftCandidate.startsWith("v") || leftCandidate.startsWith("V")) {
leftCandidate = leftCandidate.substring(1);
}
if (rightCandidate.startsWith("v") || rightCandidate.startsWith("V")) {
rightCandidate = rightCandidate.substring(1);
}
boolean leftRc = false, rightRc = false;
if (leftCandidate.endsWith("-rc")) {
leftCandidate = leftCandidate.substring(0, leftCandidate.length() - 3);
leftRc = true;
}
if (rightCandidate.endsWith("-rc")) {
rightCandidate = rightCandidate.substring(0, rightCandidate.length() - 3);
rightRc = true;
}
boolean leftSnapshot = false, rightSnapshot = false;
if (leftCandidate.endsWith("-SNAPSHOT")) {
leftCandidate = leftCandidate.substring(0, leftCandidate.length() - 9);
leftSnapshot = true;
}
if (rightCandidate.endsWith("-SNAPSHOT")) {
rightCandidate = rightCandidate.substring(0, rightCandidate.length() - 9);
rightSnapshot = true;
}
try {
Long leftPortion = Long.valueOf(leftCandidate);
Long rightPortion = Long.valueOf(rightCandidate);
if (leftPortion > rightPortion) {
return right;
} else if (rightPortion > leftPortion) {
return left;
}
if ((leftRc && !rightRc) || (leftSnapshot && !rightSnapshot)) {
return left;
}
if ((rightRc && !leftRc) || (rightSnapshot && !leftSnapshot)) {
return right;
}
} catch (NumberFormatException nfe) {
return null;
}
}
return (rightVersions.length > leftVersion.length() ? left : null);
} |
2680621_5 | public Widget getWidgetByFieldName(String fieldName) {
for (Map.Entry<Widget, String> e : fieldNames.entrySet()) {
if (e.getValue().equals(fieldName))
return e.getKey();
}
return null;
} |
2681994_39 | @Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedirectUri() != null) {
for (String uri : client.getRegisteredRedirectUri()) {
if (blacklistedSiteService.isBlacklisted(uri)) {
throw new IllegalArgumentException("Client URI is blacklisted: " + uri);
}
}
}
// assign a random clientid if it's empty
// NOTE: don't assign a random client secret without asking, since public clients have no secret
if (Strings.isNullOrEmpty(client.getClientId())) {
client = generateClientId(client);
}
// make sure that clients with the "refresh_token" grant type have the "offline_access" scope, and vice versa
ensureRefreshTokenConsistency(client);
// make sure we don't have both a JWKS and a JWKS URI
ensureKeyConsistency(client);
// check consistency when using HEART mode
checkHeartMode(client);
// timestamp this to right now
client.setCreatedAt(new Date());
// check the sector URI
checkSectorIdentifierUri(client);
ensureNoReservedScopes(client);
ClientDetailsEntity c = clientRepository.saveClient(client);
statsService.resetCache();
return c;
} |
2685841_1710 | @Override
public void writeJSON(Patient patient, JSONObject json)
{
writeJSON(patient, json, null);
} |
2689039_50 | @Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeValue(getValue());
} |
2694049_1 | SshServer getServer() {
return server;
} |
2698192_2 | public static String explain(final Throwable throwable) {
checkNotNull(throwable);
StringBuilder buff = new StringBuilder();
explain(buff, throwable);
Throwable cause = throwable;
while ((cause = cause.getCause()) != null) {
buff.append(", caused by: ");
explain(buff, cause);
}
return buff.toString();
} |
2708082_94 | public void pushDecision(Decision decision) {
int p = last.get();
decision.setPosition(p);
if(decisions.size() == p){
decisions.add(decision);
}else if(decisions.size() == p + 1) {
decisions.set(p, decision);
}else throw new SolverException("Cannot add decision to decision path");
} |
2708789_0 | @Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
// why not using println? because it makes testing harder, *nix and
// windows think different about new line as in \n vs \r\n
System.out.print("Hello World!");
return RepeatStatus.FINISHED;
} |
2710254_2 | public void loadSettings(String resourcePath, String defaultResourcePath, Object bean) {
try {
Map properties = loadSettings(resourcePath, defaultResourcePath);
BeanUtils.populate(bean, properties);
} catch (IllegalAccessException | InvocationTargetException | IOException e) {
throw new IllegalStateException(e);
}
} |
2719141_12 | public boolean contentEquals( String src, String dest )
throws FileManipulatorException
{
FileObject srcFile = null;
FileObject destFile = null;
try
{
LOGGER.debug( "Comparing the content of {} and {}", src, dest );
srcFile = this.resolveFile( src );
destFile = this.resolveFile( dest );
if ( !srcFile.exists() || !destFile.exists() )
{
LOGGER.debug( "{} or {} don't exist", src, dest );
return false;
}
if ( !srcFile.getType().equals( FileType.FILE ) )
{
LOGGER.error( "The source {} is not a file", src );
throw new IllegalArgumentException( "The source URI " + src + " is not a file" );
}
if ( !destFile.getType().equals( FileType.FILE ) )
{
LOGGER.error( "The destination {} is not a file", dest );
throw new IllegalArgumentException( "The destination URI " + dest + " is not a file" );
}
return IOUtils.contentEquals( srcFile.getContent().getInputStream(),
destFile.getContent().getInputStream() );
}
catch ( Exception e )
{
LOGGER.error( "Can't compare content of {} and {}", new Object[]{ src, dest }, e );
throw new FileManipulatorException( "Can't compare content of " + src + " and " + dest, e );
}
finally
{
if ( srcFile != null )
{
try
{
srcFile.close();
}
catch ( Exception e )
{
// ignore
}
}
if ( destFile != null )
{
try
{
destFile.close();
}
catch ( Exception e )
{
// ignore
}
}
}
} |
2737689_92 | public final PJsonObject toJSON() {
try {
JSONObject json = new JSONObject();
for (String key: this.obj.keySet()) {
Object opt = opt(key);
if (opt instanceof PYamlObject) {
opt = ((PYamlObject) opt).toJSON().getInternalObj();
} else if (opt instanceof PYamlArray) {
opt = ((PYamlArray) opt).toJSON().getInternalArray();
}
json.put(key, opt);
}
return new PJsonObject(json, this.getContextName());
} catch (Throwable e) {
throw ExceptionUtils.getRuntimeException(e);
}
} |
2740148_425 | @Override
public boolean areOutcomesCompatible(String[] outcomes) {
Set<String> start = new HashSet<>();
Set<String> cont = new HashSet<>();
Set<String> last = new HashSet<>();
Set<String> unit = new HashSet<>();
for (int i = 0; i < outcomes.length; i++) {
String outcome = outcomes[i];
if (outcome.endsWith(BilouCodec.START)) {
start.add(outcome.substring(0, outcome.length()
- BilouCodec.START.length()));
} else if (outcome.endsWith(BilouCodec.CONTINUE)) {
cont.add(outcome.substring(0, outcome.length()
- BilouCodec.CONTINUE.length()));
} else if (outcome.endsWith(BilouCodec.LAST)) {
last.add(outcome.substring(0, outcome.length()
- BilouCodec.LAST.length()));
} else if (outcome.endsWith(BilouCodec.UNIT)) {
unit.add(outcome.substring(0, outcome.length()
- BilouCodec.UNIT.length()));
} else if (!outcome.equals(BilouCodec.OTHER)) {
return false;
}
}
if (start.size() == 0 && unit.size() == 0) {
return false;
} else {
// Start, must have matching Last
for (String startPrefix : start) {
if (!last.contains(startPrefix)) {
return false;
}
}
// Cont, must have matching Start and Last
for (String contPrefix : cont) {
if (!start.contains(contPrefix) && !last.contains(contPrefix)) {
return false;
}
}
// Last, must have matching Start
for (String lastPrefix : last) {
if (!start.contains(lastPrefix)) {
return false;
}
}
}
return true;
} |
2740607_0 | public String getDeploymentPath() {
return deployDetails.getArtifactPath();
} |
2742247_3 | public String getCacheName(){
return this.cache.getName();
} |
2747986_8 | public MimeMessage createMessage(String from, String to, String cc,
String subject, SOAPMessage soapMessage) throws ConnectionException {
return createMessage(from, to, cc, subject, soapMessage, createSession());
} |
2752522_464 | public static Connection showDialog(String title) {
return showDialog(title, null);
} |
2755429_1 | public String innerText() {
return sbuf.toString();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.