_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q13100
Application.initApplication
train
public static void initApplication(String... args) { if (args.length < 1) { System.err.println("Please specify an Application as argument"); System.exit(-1); } setInstance(createApplicationByClassName(args[0])); }
java
{ "resource": "" }
q13101
Permutation.next
train
public int[] next() { if (!hasNext) return null; int[] result = new int[r]; for (int i=0; i<r; i++) result[i] = index[i]; moveIndex(); return result; }
java
{ "resource": "" }
q13102
Permutation.reverseAfter
train
private void reverseAfter(int i) { int start = i+1; int end = n-1; while (start < end) { swap(index,start,end); start++; end--; } }
java
{ "resource": "" }
q13103
Permutation.rightmostDip
train
private int rightmostDip() { for (int i=n-2; i>=0; i--) if (index[i] < index[i+1]) return i; return -1; }
java
{ "resource": "" }
q13104
FuzzyAllenIntervalConstraint.getInversePossibilities
train
public HashMap<Type, Double> getInversePossibilities() { HashMap<Type, Double> ret = new HashMap<Type, Double>(); for (Type t : Type.values()) ret.put(t, 0.0); for (Type t : types) { //??? IS THIS CORRECT ??? --> Seems correct //get inverse of each relation that is 1.0 Type inverseRelation = FuzzyAllenIntervalConstraint.getInverseRelation(t); HashMap<FuzzyAllenIntervalConstraint.Type, Double> possibilities = this.getPossibilities(); //set poss of each inverse relation to 1.0 ret.put(inverseRelation, possibilities.get(t)); //calculate the Freksa N of each inverse relation HashMap<FuzzyAllenIntervalConstraint.Type, Double> fr = new HashMap<FuzzyAllenIntervalConstraint.Type, Double>(); for(int i = 0; i < FuzzyAllenIntervalConstraint.freksa_neighbor[inverseRelation.ordinal()].length; i++) fr.put(FuzzyAllenIntervalConstraint.lookupTypeByInt(i), FuzzyAllenIntervalConstraint.getPossibilityDegree(FuzzyAllenIntervalConstraint.freksa_neighbor[inverseRelation.ordinal()][i])); //take the maximum between calculated Freksa N and previously added possibilities //(because this is an OR) for(FuzzyAllenIntervalConstraint.Type t1: fr.keySet()) ret.put(t1, Math.max(ret.get(t1), fr.get(t1))); } /* System.out.println("====================================="); System.out.println("DIRECT " + this + ":\n" + this.possibilities); System.out.println("INVERSE:\n" + ret); System.out.println("====================================="); */ return ret; }
java
{ "resource": "" }
q13105
TransformationDescription.addStep
train
public void addStep(String operationName, List<String> sourceFields, String targetField, Map<String, String> parameters) { TransformationStep step = new TransformationStep(); step.setOperationName(operationName); step.setSourceFields(sourceFields.toArray(new String[sourceFields.size()])); step.setTargetField(targetField); step.setOperationParams(parameters); steps.add(step); }
java
{ "resource": "" }
q13106
TransformationDescription.forwardField
train
public void forwardField(String sourceField, String targetField) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceField); step.setOperationName("forward"); steps.add(step); }
java
{ "resource": "" }
q13107
TransformationDescription.concatField
train
public void concatField(String targetField, String concatString, String... sourceFields) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceFields); step.setOperationParameter(TransformationConstants.CONCAT_PARAM, concatString); step.setOperationName("concat"); steps.add(step); }
java
{ "resource": "" }
q13108
TransformationDescription.splitField
train
public void splitField(String sourceField, String targetField, String splitString, String index) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceField); step.setOperationParameter(TransformationConstants.SPLIT_PARAM, splitString); step.setOperationParameter(TransformationConstants.INDEX_PARAM, index); step.setOperationName("split"); steps.add(step); }
java
{ "resource": "" }
q13109
TransformationDescription.splitRegexField
train
public void splitRegexField(String sourceField, String targetField, String regexString, String index) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceField); step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString); step.setOperationParameter(TransformationConstants.INDEX_PARAM, index); step.setOperationName("splitRegex"); steps.add(step); }
java
{ "resource": "" }
q13110
TransformationDescription.substringField
train
public void substringField(String sourceField, String targetField, String from, String to) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceField); step.setOperationParameter(TransformationConstants.SUBSTRING_FROM_PARAM, from); step.setOperationParameter(TransformationConstants.SUBSTRING_TO_PARAM, to); step.setOperationName("substring"); steps.add(step); }
java
{ "resource": "" }
q13111
TransformationDescription.valueField
train
public void valueField(String targetField, String value) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.VALUE_PARAM, value); step.setOperationName("value"); steps.add(step); }
java
{ "resource": "" }
q13112
TransformationDescription.replaceField
train
public void replaceField(String sourceField, String targetField, String oldString, String newString) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceField); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.REPLACE_OLD_PARAM, oldString); step.setOperationParameter(TransformationConstants.REPLACE_NEW_PARAM, newString); step.setOperationName("replace"); steps.add(step); }
java
{ "resource": "" }
q13113
TransformationDescription.padField
train
public void padField(String sourceField, String targetField, String length, String character, String direction) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceField); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.PAD_LENGTH_PARAM, length); step.setOperationParameter(TransformationConstants.PAD_CHARACTER_PARAM, character); step.setOperationParameter(TransformationConstants.PAD_DIRECTION_PARAM, direction); step.setOperationName("pad"); steps.add(step); }
java
{ "resource": "" }
q13114
TransformationDescription.removeLeadingField
train
public void removeLeadingField(String sourceField, String targetField, String regexString, String length) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceField); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.REMOVELEADING_LENGTH_PARAM, length); step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString); step.setOperationName("removeleading"); steps.add(step); }
java
{ "resource": "" }
q13115
TransformationDescription.instantiateField
train
public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) { TransformationStep step = new TransformationStep(); step.setSourceFields(sourceFields); step.setTargetField(targetField); step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType); if (targetTypeInit != null) { step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit); } step.setOperationName("instantiate"); steps.add(step); }
java
{ "resource": "" }
q13116
QueryRequestCriteriaBuilder.convertParametersToPredicate
train
@SuppressWarnings({ "unchecked" }) private Predicate convertParametersToPredicate(Root<?> from, CriteriaQuery<?> query) { List<Predicate> predicates = new ArrayList<>(); for (Map.Entry<String, Set<Object>> value : request.getParameters().entrySet()) { Subquery<JPAEntry> subquery = buildJPAEntrySubquery(value.getKey(), value.getValue(), from, query); predicates.add(builder.exists(subquery)); } if (request.isAndJoined()) { return builder.and(Iterables.toArray(predicates, Predicate.class)); } else { return builder.or(Iterables.toArray(predicates, Predicate.class)); } }
java
{ "resource": "" }
q13117
BinaryPropertyProcessor.set
train
protected void set(PofValue target, Object value) { navigator.navigate(target).setValue(value); }
java
{ "resource": "" }
q13118
NodeDiscovery.getNodes
train
public Map<String, T> getNodes() { return Maps.transformValues(Collections.unmodifiableMap(_nodes), input -> (input != null) ? input.orElse(null) : null); }
java
{ "resource": "" }
q13119
NodeDiscovery.loadExistingData
train
private synchronized void loadExistingData() { for (ChildData childData : _pathCache.getCurrentData()) { addNode(childData.getPath(), parseChildData(childData)); } }
java
{ "resource": "" }
q13120
QueryInterfaceService.convertEDBCommitToEKBCommit
train
private EKBCommit convertEDBCommitToEKBCommit(EDBCommit commit) throws EKBException { EKBCommit result = new EKBCommit(); Map<ModelDescription, Class<?>> cache = new HashMap<>(); result.setRevisionNumber(commit.getRevisionNumber()); result.setComment(commit.getComment()); result.setParentRevisionNumber(commit.getParentRevisionNumber()); result.setDomainId(commit.getDomainId()); result.setConnectorId(commit.getConnectorId()); result.setInstanceId(commit.getInstanceId()); for (EDBObject insert : commit.getInserts()) { result.addInsert(createModelOfEDBObject(insert, cache)); } for (EDBObject update : commit.getUpdates()) { result.addUpdate(createModelOfEDBObject(update, cache)); } for (String delete : commit.getDeletions()) { EDBObject object = edbService.getObject(delete, commit.getTimestamp()); result.addDelete(createModelOfEDBObject(object, cache)); } return result; }
java
{ "resource": "" }
q13121
QueryInterfaceService.createModelOfEDBObject
train
private Object createModelOfEDBObject(EDBObject object, Map<ModelDescription, Class<?>> cache) { try { ModelDescription description = getDescriptionFromObject(object); Class<?> modelClass; if (cache.containsKey(description)) { modelClass = cache.get(description); } else { modelClass = modelRegistry.loadModel(description); cache.put(description, modelClass); } return edbConverter.convertEDBObjectToModel(modelClass, object); } catch (IllegalArgumentException | ClassNotFoundException e) { LOGGER.warn("Unable to create model of the object {}", object.getOID(), e); return null; } }
java
{ "resource": "" }
q13122
QueryInterfaceService.getDescriptionFromObject
train
private ModelDescription getDescriptionFromObject(EDBObject obj) { String modelName = obj.getString(EDBConstants.MODEL_TYPE); String modelVersion = obj.getString(EDBConstants.MODEL_TYPE_VERSION); if (modelName == null || modelVersion == null) { throw new IllegalArgumentException("The object " + obj.getOID() + " contains no model information"); } return new ModelDescription(modelName, modelVersion); }
java
{ "resource": "" }
q13123
CoherenceCacheTarget.init
train
private void init(String cacheName, NamedCache cache, IdGenerator idGenerator, IdExtractor idExtractor) { m_cacheName = cacheName; m_cache = cache; m_idGenerator = idGenerator; m_idExtractor = idExtractor; }
java
{ "resource": "" }
q13124
TextFileAuthentication.main
train
public static void main(String[] args) { if (args.length < 2) { System.err.println("Two arguments needed as username and password"); System.exit(-1); } User user = new User(); user.name = args[0]; user.password.setPassword(args[1].toCharArray()); for (int i = 2; i<args.length; i++) { user.roles.add(new UserRole(args[i].trim())); } System.out.println(user.format()); }
java
{ "resource": "" }
q13125
TransformationUtils.getDescriptionsFromXMLInputStream
train
public static List<TransformationDescription> getDescriptionsFromXMLInputStream(InputStream fileContent) { List<TransformationDescription> desc = new ArrayList<TransformationDescription>(); try { desc = loadDescrtipionsFromXMLInputSource(new InputSource(fileContent), null); } catch (Exception e) { LOGGER.error("Unable to read the descriptions from input stream. ", e); } return desc; }
java
{ "resource": "" }
q13126
TransformationUtils.getDescriptionsFromXMLFile
train
public static List<TransformationDescription> getDescriptionsFromXMLFile(File file) { List<TransformationDescription> desc = new ArrayList<TransformationDescription>(); try { return loadDescrtipionsFromXMLInputSource(new InputSource(file.getAbsolutePath()), file.getName()); } catch (Exception e) { LOGGER.error("Unable to read the descriptions from file " + file.getAbsolutePath(), e); } return desc; }
java
{ "resource": "" }
q13127
TransformationUtils.loadDescrtipionsFromXMLInputSource
train
private static List<TransformationDescription> loadDescrtipionsFromXMLInputSource(InputSource source, String fileName) throws Exception { XMLReader xr = XMLReaderFactory.createXMLReader(); TransformationDescriptionXMLReader reader = new TransformationDescriptionXMLReader(fileName); xr.setContentHandler(reader); xr.parse(source); return reader.getResult(); }
java
{ "resource": "" }
q13128
AbstractBaseTarget.getWriteableProperties
train
protected static List<PropertyDescriptor> getWriteableProperties(Class cls) { BeanWrapper beanWrapper = new BeanWrapperImpl(cls); List<PropertyDescriptor> writeableProperties = new ArrayList<PropertyDescriptor>(); PropertyDescriptor[] props = beanWrapper.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (isWriteable(prop)) { writeableProperties.add(prop); } } return writeableProperties; }
java
{ "resource": "" }
q13129
AbstractJdbcCacheStore.load
train
@Transactional(readOnly = true) public Object load(Object key) { List<T> results = getJdbcTemplate().query( getSelectSql(), getRowMapper(), getPrimaryKeyComponents(key)); return results.size() == 0 ? null : results.get(0); }
java
{ "resource": "" }
q13130
AbstractJdbcCacheStore.store
train
public void store(Object key, Object value) { getJdbcTemplate().update(getMergeSql(), new BeanPropertySqlParameterSource(value)); }
java
{ "resource": "" }
q13131
PlotSTPTemporalModule.tableToString
train
String tableToString(Table table) { StringBuilder strb = new StringBuilder(); for(int row = 0; row < table.getRowCount(); row++) { for(int col = 0; col < table.getColumnCount(); col++) { strb.append(table.get(row, col)); strb.append(" "); } strb.append("\n"); } return strb.toString(); }
java
{ "resource": "" }
q13132
ModelWrapper.wrap
train
public static ModelWrapper wrap(Object model) { if (!(isModel(model.getClass()))) { throw new IllegalArgumentException("The given object is no model"); } return new ModelWrapper((OpenEngSBModel) model); }
java
{ "resource": "" }
q13133
ModelWrapper.getModelDescription
train
public ModelDescription getModelDescription() { String modelName = retrieveModelName(); String modelVersion = retrieveModelVersion(); if (modelName == null || modelVersion == null) { throw new IllegalArgumentException("Unsufficient information to create model description."); } return new ModelDescription(modelName, modelVersion); }
java
{ "resource": "" }
q13134
ModelWrapper.appendContextId
train
protected String appendContextId(Object modelId) { return String.format("%s/%s", ContextHolder.get().getCurrentContextId(), modelId); }
java
{ "resource": "" }
q13135
Interval.compareTo
train
@Override public int compareTo(Object arg0) { Interval that = (Interval)arg0; return this.bounds.compareTo(that.getBounds()); }
java
{ "resource": "" }
q13136
RoleFileAccessObject.findAllRoles
train
public List<Role> findAllRoles() { List<Role> list = new ArrayList<>(); List<String> roleStrings; try { roleStrings = readLines(rolesFile); } catch (IOException e) { throw new FileBasedRuntimeException(e); } for (String roleString : roleStrings) { if (StringUtils.isNotBlank(roleString)) { String[] substrings = StringUtils.splitByWholeSeparator(roleString, Configuration.get().getAssociationSeparator()); if (substrings.length < 1 || StringUtils.isBlank(substrings[0])) { continue; } Role role = new Role(substrings[0]); if (substrings.length > 1) { role.setRoles(Arrays.asList(StringUtils.splitByWholeSeparator(substrings[1], Configuration.get() .getValueSeparator()))); } list.add(role); } } return list; }
java
{ "resource": "" }
q13137
AttributeEditorUtil.createFieldList
train
public static RepeatingView createFieldList(String id, Class<?> bean, Map<String, String> values) { List<AttributeDefinition> attributes = MethodUtil.buildAttributesList(bean); return createFieldList(id, attributes, values); }
java
{ "resource": "" }
q13138
AttributeEditorUtil.createFieldList
train
public static RepeatingView createFieldList(String id, List<AttributeDefinition> attributes, Map<String, String> values) { RepeatingView fields = new RepeatingView(id); for (AttributeDefinition a : attributes) { WebMarkupContainer row = new WebMarkupContainer(a.getId()); MapModel<String, String> model = new MapModel<String, String>(values, a.getId()); row.add(createEditorField("row", model, a)); fields.add(row); } return fields; }
java
{ "resource": "" }
q13139
PropertyConnectionCalculator.getPropertyConnections
train
public Map<String, Set<String>> getPropertyConnections(TransformationDescription description) { Map<String, Set<String>> propertyMap = getSourceProperties(description.getSourceModel()); fillPropertyMap(propertyMap, description); resolveTemporaryProperties(propertyMap); deleteTemporaryProperties(propertyMap); return propertyMap; }
java
{ "resource": "" }
q13140
PropertyConnectionCalculator.getSourceProperties
train
private Map<String, Set<String>> getSourceProperties(ModelDescription description) { Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>(); try { Class<?> sourceModel = registry.loadModel(description); while (sourceModel != null && !sourceModel.equals(Object.class)) { for (Field field : sourceModel.getDeclaredFields()) { result.put(field.getName(), new HashSet<String>()); } sourceModel = sourceModel.getSuperclass(); } } catch (ClassNotFoundException e) { LOGGER.error("Unable to load model {}", description); return result; } return result; }
java
{ "resource": "" }
q13141
PropertyConnectionCalculator.fillPropertyMap
train
private void fillPropertyMap(Map<String, Set<String>> map, TransformationDescription description) { for (TransformationStep step : description.getTransformingSteps()) { if (step.getSourceFields() == null) { LOGGER.debug("Step {} is ignored since no source properties are defined"); continue; } String targetField = step.getTargetField(); if (!map.containsKey(targetField) && isTemporaryProperty(targetField)) { LOGGER.debug("Add new property entry for field {}", targetField); map.put(targetField, new HashSet<String>()); } for (String sourceField : step.getSourceFields()) { if (sourceField == null) { continue; } String[] result = StringUtils.split(sourceField, "."); String mapValue = result[0]; Set<String> targets = map.get(mapValue); if (targets != null) { targets.add(targetField); } else { LOGGER.error("Accessed property with the name {} which isn't existing", mapValue); } } } }
java
{ "resource": "" }
q13142
PropertyConnectionCalculator.resolveTemporaryProperties
train
private void resolveTemporaryProperties(Map<String, Set<String>> map) { boolean temporaryPresent = false; do { temporaryPresent = false; for (Map.Entry<String, Set<String>> entry : map.entrySet()) { Set<String> newProperties = new HashSet<String>(); Iterator<String> properties = entry.getValue().iterator(); while (properties.hasNext()) { String property = properties.next(); if (isTemporaryProperty(property)) { LOGGER.debug("Resolve temporary field {} for property {}", entry.getKey(), property); temporaryPresent = true; newProperties.addAll(map.get(property)); properties.remove(); } } entry.getValue().addAll(newProperties); } } while (temporaryPresent); }
java
{ "resource": "" }
q13143
PropertyConnectionCalculator.deleteTemporaryProperties
train
private void deleteTemporaryProperties(Map<String, Set<String>> map) { Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); if (isTemporaryProperty(key)) { LOGGER.debug("Delete temporary field {} from the connection result", key); iterator.remove(); } } }
java
{ "resource": "" }
q13144
Frontend.loginAtStart
train
public static boolean loginAtStart() { boolean loginAtStart = Application.getInstance().isLoginRequired() || Configuration.get("MjLoginAtStart", "false").equals("true"); if (loginAtStart && !Backend.getInstance().isAuthenticationActive()) { throw new IllegalStateException("Login required but authorization is not configured!"); } return loginAtStart; }
java
{ "resource": "" }
q13145
Frontend.createInput
train
public Optional<Input<String>> createInput(int maxLength, InputType inputType, InputComponentListener changeListener) { return Optional.empty(); }
java
{ "resource": "" }
q13146
SqlRepository.clear
train
public void clear() { List<AbstractTable<?>> tableList = new ArrayList<AbstractTable<?>>(tables.values()); for (AbstractTable<?> table : tableList) { table.clear(); } }
java
{ "resource": "" }
q13147
EDBObject.getObject
train
@SuppressWarnings("unchecked") public <T> T getObject(String key, Class<T> clazz) { EDBObjectEntry entry = get(key); return entry == null ? null : (T) entry.getValue(); }
java
{ "resource": "" }
q13148
EDBObject.isDeleted
train
public final Boolean isDeleted() { Boolean deleted = getObject(DELETED_CONST, Boolean.class); return deleted != null ? deleted : false; }
java
{ "resource": "" }
q13149
EDBObject.putEDBObjectEntry
train
public void putEDBObjectEntry(String key, Object value) { putEDBObjectEntry(key, value, value.getClass()); }
java
{ "resource": "" }
q13150
EDBObject.appendEntry
train
private void appendEntry(Map.Entry<String, EDBObjectEntry> entry, StringBuilder builder) { if (builder.length() > 2) { builder.append(","); } builder.append(" \"").append(entry.getKey()).append("\""); builder.append(" : ").append(entry.getValue()); }
java
{ "resource": "" }
q13151
EDBUtils.convertJPAEntryToEDBObjectEntry
train
public static EDBObjectEntry convertJPAEntryToEDBObjectEntry(JPAEntry entry) { for (EDBConverterStep step : steps) { if (step.doesStepFit(entry.getType())) { LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType()); return step.convertToEDBObjectEntry(entry); } } LOGGER.error("No EDBConverterStep fit for JPAEntry {}", entry); return null; }
java
{ "resource": "" }
q13152
EDBUtils.convertEDBObjectEntryToJPAEntry
train
public static JPAEntry convertEDBObjectEntryToJPAEntry(EDBObjectEntry entry, JPAObject owner) { for (EDBConverterStep step : steps) { if (step.doesStepFit(entry.getType())) { LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType()); return step.convertToJPAEntry(entry, owner); } } LOGGER.error("No EDBConverterStep fit for EDBObjectEntry {}", entry); return null; }
java
{ "resource": "" }
q13153
EDBUtils.convertJPAObjectToEDBObject
train
public static EDBObject convertJPAObjectToEDBObject(JPAObject object) { EDBObject result = new EDBObject(object.getOID()); for (JPAEntry kvp : object.getEntries()) { EDBObjectEntry entry = convertJPAEntryToEDBObjectEntry(kvp); result.put(entry.getKey(), entry); } result.setDeleted(object.isDeleted()); if (object.getTimestamp() != null) { result.updateTimestamp(object.getTimestamp()); } return result; }
java
{ "resource": "" }
q13154
EDBUtils.convertEDBObjectToJPAObject
train
public static JPAObject convertEDBObjectToJPAObject(EDBObject object) { JPAObject result = new JPAObject(); result.setTimestamp(object.getTimestamp()); result.setOID(object.getOID()); result.setDeleted(object.isDeleted()); List<JPAEntry> entries = new ArrayList<JPAEntry>(); for (EDBObjectEntry entry : object.values()) { entries.add(convertEDBObjectEntryToJPAEntry(entry, result)); } result.setEntries(entries); return result; }
java
{ "resource": "" }
q13155
EDBUtils.convertEDBObjectsToJPAObjects
train
public static List<JPAObject> convertEDBObjectsToJPAObjects(List<EDBObject> objects) { List<JPAObject> result = new ArrayList<JPAObject>(); for (EDBObject object : objects) { result.add(convertEDBObjectToJPAObject(object)); } return result; }
java
{ "resource": "" }
q13156
EDBUtils.convertJPAObjectsToEDBObjects
train
public static List<EDBObject> convertJPAObjectsToEDBObjects(List<JPAObject> objects) { List<EDBObject> result = new ArrayList<EDBObject>(); for (JPAObject object : objects) { result.add(convertJPAObjectToEDBObject(object)); } return result; }
java
{ "resource": "" }
q13157
Defaults.createExpression
train
public static Expression createExpression(String expression) { try { return INSTANCE.ctorExpression.newInstance(expression); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q13158
Defaults.createExtractor
train
public static Extractor createExtractor(String expression) { try { return INSTANCE.ctorExtractor.newInstance(expression); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q13159
Defaults.createUpdater
train
public static Updater createUpdater(String expression) { try { return INSTANCE.ctorUpdater.newInstance(expression); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q13160
Defaults.createCondition
train
public static Condition createCondition(String expression) { try { return INSTANCE.ctorCondition.newInstance(expression); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q13161
Defaults.getConstructor
train
protected Constructor getConstructor(Class type) { try { return type.getConstructor(String.class); } catch (NoSuchMethodException e) { throw new RuntimeException( "Unable to find a constructor that accepts" + " a single String argument in the " + type.getName() + " class.", e); } }
java
{ "resource": "" }
q13162
EngineeringObjectModelWrapper.enhance
train
public static EngineeringObjectModelWrapper enhance(AdvancedModelWrapper model) { if (!model.isEngineeringObject()) { throw new IllegalArgumentException("The model of the AdvancedModelWrapper is no EngineeringObject"); } return new EngineeringObjectModelWrapper(model.getUnderlyingModel()); }
java
{ "resource": "" }
q13163
EngineeringObjectModelWrapper.getForeignKeyFields
train
public List<Field> getForeignKeyFields() { List<Field> fields = new ArrayList<Field>(); for (Field field : model.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(OpenEngSBForeignKey.class)) { fields.add(field); } } return fields; }
java
{ "resource": "" }
q13164
EngineeringObjectModelWrapper.loadReferencedModel
train
public AdvancedModelWrapper loadReferencedModel(Field field, ModelRegistry modelRegistry, EngineeringDatabaseService edbService, EDBConverter edbConverter) { try { ModelDescription description = getModelDescriptionFromField(field); String modelKey = (String) FieldUtils.readField(field, model, true); if (modelKey == null) { return null; } modelKey = appendContextId(modelKey); Class<?> sourceClass = modelRegistry.loadModel(description); Object model = edbConverter.convertEDBObjectToModel(sourceClass, edbService.getObject(modelKey)); return new AdvancedModelWrapper((OpenEngSBModel) model); } catch (SecurityException e) { throw new EKBException(generateErrorMessage(field), e); } catch (IllegalArgumentException e) { throw new EKBException(generateErrorMessage(field), e); } catch (IllegalAccessException e) { throw new EKBException(generateErrorMessage(field), e); } catch (ClassNotFoundException e) { throw new EKBException(generateErrorMessage(field), e); } }
java
{ "resource": "" }
q13165
EngineeringObjectModelWrapper.getModelDescriptionFromField
train
private ModelDescription getModelDescriptionFromField(Field field) { OpenEngSBForeignKey key = field.getAnnotation(OpenEngSBForeignKey.class); ModelDescription description = new ModelDescription(key.modelType(), key.modelVersion()); return description; }
java
{ "resource": "" }
q13166
SequenceGenerator.generateId
train
public synchronized Long generateId() { if (sequenceBlock == null || !sequenceBlock.hasNext()) { sequenceBlock = allocateSequenceBlock(); } return sequenceBlock.next(); }
java
{ "resource": "" }
q13167
RemoveLeadingOperation.performRemoveLeading
train
private String performRemoveLeading(String source, Integer length, Matcher matcher) { if (length != null && length != 0) { matcher.region(0, length); } if (matcher.find()) { String matched = matcher.group(); return source.substring(matched.length()); } return source; }
java
{ "resource": "" }
q13168
Mat2.set
train
public void set( float radians ) { float c = (float)StrictMath.cos( radians ); float s = (float)StrictMath.sin( radians ); m00 = c; m01 = -s; m10 = s; m11 = c; }
java
{ "resource": "" }
q13169
AbstractTypeMap.put
train
protected DataType put(Class<?> clazz, int type, String name) { DataType dataType = new DataType(type, name); map.put(clazz, dataType); return dataType; }
java
{ "resource": "" }
q13170
CipherUtils.decrypt
train
public static byte[] decrypt(byte[] text, Key key) throws DecryptionException { return decrypt(text, key, key.getAlgorithm()); }
java
{ "resource": "" }
q13171
CipherUtils.decrypt
train
public static byte[] decrypt(byte[] text, Key key, String algorithm) throws DecryptionException { Cipher cipher; try { LOGGER.trace("start decrypting text using {} cipher", algorithm); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); LOGGER.trace("initialized decryption with key of type {}", key.getClass()); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("unable to initialize cipher for algorithm " + algorithm, e); } try { return cipher.doFinal(text); } catch (GeneralSecurityException e) { throw new DecryptionException("unable to decrypt data using algorithm " + algorithm, e); } }
java
{ "resource": "" }
q13172
CipherUtils.encrypt
train
public static byte[] encrypt(byte[] text, Key key) throws EncryptionException { return encrypt(text, key, key.getAlgorithm()); }
java
{ "resource": "" }
q13173
CipherUtils.encrypt
train
public static byte[] encrypt(byte[] text, Key key, String algorithm) throws EncryptionException { Cipher cipher; try { LOGGER.trace("start encrypting text using {} cipher", algorithm); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); LOGGER.trace("initialized encryption with key of type {}", key.getClass()); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("unable to initialize cipher for algorithm " + algorithm, e); } try { return cipher.doFinal(text); } catch (GeneralSecurityException e) { throw new EncryptionException("unable to encrypt data using algorithm " + algorithm, e); } }
java
{ "resource": "" }
q13174
CipherUtils.sign
train
public static byte[] sign(byte[] text, PrivateKey key, String algorithm) throws SignatureException { Signature signature; try { signature = Signature.getInstance(algorithm); signature.initSign(key); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e); } signature.update(text); return signature.sign(); }
java
{ "resource": "" }
q13175
CipherUtils.verify
train
public static boolean verify(byte[] text, byte[] signatureValue, PublicKey key, String algorithm) throws SignatureException { Signature signature; try { signature = Signature.getInstance(algorithm); signature.initVerify(key); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e); } signature.update(text); return signature.verify(signatureValue); }
java
{ "resource": "" }
q13176
OgnlExpression.getCompiledExpression
train
protected synchronized Object getCompiledExpression() { if (compiledExpression == null) { try { compiledExpression = Ognl.parseExpression(getExpression()); } catch (OgnlException e) { throw new IllegalArgumentException("[" + getExpression() + "] is not a valid OGNL expression", e); } } return compiledExpression; }
java
{ "resource": "" }
q13177
ViewUtil.view
train
public static <T> T view(Object completeObject, T viewObject) { if (completeObject == null) return null; Map<String, PropertyInterface> propertiesOfCompleteObject = FlatProperties.getProperties(completeObject.getClass()); Map<String, PropertyInterface> properties = FlatProperties.getProperties(viewObject.getClass()); for (Map.Entry<String, PropertyInterface> entry : properties.entrySet()) { PropertyInterface property = propertiesOfCompleteObject.get(entry.getKey()); Object value = property != null ? property.getValue(completeObject) : readByGetMethod(completeObject, entry.getKey()); entry.getValue().setValue(viewObject, value); } return viewObject; }
java
{ "resource": "" }
q13178
ViewUtil.viewed
train
public static <T> T viewed(View<T> viewObject) { if (viewObject == null) return null; @SuppressWarnings("unchecked") Class<T> viewedClass = (Class<T>) getViewedClass(viewObject.getClass()); Object id = IdUtils.getId(viewObject); if (id == null) { return null; } return Backend.read(viewedClass, id); }
java
{ "resource": "" }
q13179
ModelDiff.createModelDiff
train
public static ModelDiff createModelDiff(OpenEngSBModel before, OpenEngSBModel after) { ModelDiff diff = new ModelDiff(before, after); calculateDifferences(diff); return diff; }
java
{ "resource": "" }
q13180
ModelDiff.createModelDiff
train
public static ModelDiff createModelDiff(OpenEngSBModel updated, String completeModelId, EngineeringDatabaseService edbService, EDBConverter edbConverter) { EDBObject queryResult = edbService.getObject(completeModelId); OpenEngSBModel old = edbConverter.convertEDBObjectToModel(updated.getClass(), queryResult); ModelDiff diff = new ModelDiff(old, updated); calculateDifferences(diff); return diff; }
java
{ "resource": "" }
q13181
ModelDiff.calculateDifferences
train
private static void calculateDifferences(ModelDiff diff) { Class<?> modelClass = diff.getBefore().getClass(); for (Field field : modelClass.getDeclaredFields()) { if (field.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) { continue; } try { Object before = FieldUtils.readField(field, diff.getBefore(), true); Object after = FieldUtils.readField(field, diff.getAfter(), true); if (!Objects.equal(before, after)) { diff.addDifference(field, before, after); } } catch (IllegalAccessException e) { LOGGER.warn("Skipped field '{}' because of illegal access to it", field.getName(), e); } } }
java
{ "resource": "" }
q13182
ModelDiff.addDifference
train
public void addDifference(Field field, Object before, Object after) { ModelDiffEntry entry = new ModelDiffEntry(); entry.setBefore(before); entry.setAfter(after); entry.setField(field); differences.put(field, entry); }
java
{ "resource": "" }
q13183
ModelDiff.isForeignKeyChanged
train
public boolean isForeignKeyChanged() { return CollectionUtils.exists(differences.values(), new Predicate() { @Override public boolean evaluate(Object object) { return ((ModelDiffEntry) object).isForeignKey(); } }); }
java
{ "resource": "" }
q13184
PolygonalDomain.containsPoint
train
public boolean containsPoint(Coordinate point) { Point p = new GeometryFactory().createPoint(point); return this.getGeometry().contains(p); }
java
{ "resource": "" }
q13185
SecurityContext.executeWithSystemPermissions
train
public static <ReturnType> ReturnType executeWithSystemPermissions(Callable<ReturnType> task) throws ExecutionException { ContextAwareCallable<ReturnType> contextAwareCallable = new ContextAwareCallable<ReturnType>(task); Subject newsubject = new Subject.Builder().buildSubject(); newsubject.login(new RootAuthenticationToken()); try { return newsubject.execute(contextAwareCallable); } finally { newsubject.logout(); } }
java
{ "resource": "" }
q13186
SecurityContext.executeWithSystemPermissions
train
public static void executeWithSystemPermissions(Runnable task) { ContextAwareRunnable contextAwaretask = new ContextAwareRunnable(task); Subject newsubject = new Subject.Builder().buildSubject(); newsubject.login(new RootAuthenticationToken()); try { newsubject.execute(contextAwaretask); } finally { newsubject.logout(); } }
java
{ "resource": "" }
q13187
SecurityContext.getSecurityContextAwareExecutor
train
public static ExecutorService getSecurityContextAwareExecutor(ExecutorService original) { SubjectAwareExecutorService subjectAwareExecutor = new SubjectAwareExecutorService(original); return ThreadLocalUtil.contextAwareExecutor(subjectAwareExecutor); }
java
{ "resource": "" }
q13188
BeanUtilsExtended.createBeanFromAttributeMap
train
public static <BeanType> BeanType createBeanFromAttributeMap(Class<BeanType> beanType, Map<String, ? extends Object> attributeValues) { BeanType instance; try { instance = beanType.newInstance(); BeanUtils.populate(instance, attributeValues); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); throw new IllegalStateException("Should never get here"); } return instance; }
java
{ "resource": "" }
q13189
RulebaseBuilder.reloadRulebase
train
public synchronized void reloadRulebase() throws RuleBaseException { long start = System.currentTimeMillis(); reloadDeclarations(); packageStrings.clear(); for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Function)) { String packageName = id.getPackageName(); StringBuffer packageString = getPackageString(packageName); String code = manager.get(id); packageString.append(code); } for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Rule)) { String packageName = id.getPackageName(); StringBuffer packageString = getPackageString(packageName); String code = manager.get(id); String formattedRule = String.format(RULE_TEMPLATE, id.getName(), code); packageString.append(formattedRule); } for (RuleBaseElementId id : manager.listAll(RuleBaseElementType.Process)) { getPackageString(id.getPackageName()); } Collection<KnowledgePackage> compiledPackages = new HashSet<KnowledgePackage>(); if (packageStrings.isEmpty()) { Set<String> emptySet = Collections.emptySet(); compiledPackages.addAll(compileDrlString("package dummy;\n" + declarations, emptySet)); } else { for (Map.Entry<String, StringBuffer> entry : packageStrings.entrySet()) { String packageName = entry.getKey(); StringBuffer drlCode = entry.getValue(); Collection<String> flows = queryFlows(packageName); Collection<KnowledgePackage> compiledDrlPackage = compileDrlString(drlCode.toString(), flows); compiledPackages.addAll(compiledDrlPackage); } } lockRuleBase(); clearRulebase(); base.addKnowledgePackages(compiledPackages); unlockRuleBase(); LOGGER.info("Reloading the rulebase took {}ms", System.currentTimeMillis() - start); }
java
{ "resource": "" }
q13190
EDBConverter.convertEDBObjectToModel
train
@SuppressWarnings("unchecked") public <T> T convertEDBObjectToModel(Class<T> model, EDBObject object) { return (T) convertEDBObjectToUncheckedModel(model, object); }
java
{ "resource": "" }
q13191
EDBConverter.convertEDBObjectsToModelObjects
train
public <T> List<T> convertEDBObjectsToModelObjects(Class<T> model, List<EDBObject> objects) { List<T> models = new ArrayList<>(); for (EDBObject object : objects) { T instance = convertEDBObjectToModel(model, object); if (instance != null) { models.add(instance); } } return models; }
java
{ "resource": "" }
q13192
EDBConverter.checkEDBObjectModelType
train
private boolean checkEDBObjectModelType(EDBObject object, Class<?> model) { String modelClass = object.getString(EDBConstants.MODEL_TYPE); if (modelClass == null) { LOGGER.warn(String.format("The EDBObject with the oid %s has no model type information." + "The resulting model may be a different model type than expected.", object.getOID())); } if (modelClass != null && !modelClass.equals(model.getName())) { return false; } return true; }
java
{ "resource": "" }
q13193
EDBConverter.convertEDBObjectToUncheckedModel
train
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) { if (!checkEDBObjectModelType(object, model)) { return null; } filterEngineeringObjectInformation(object, model); List<OpenEngSBModelEntry> entries = new ArrayList<>(); for (PropertyDescriptor propertyDescriptor : getPropertyDescriptorsForClass(model)) { if (propertyDescriptor.getWriteMethod() == null || propertyDescriptor.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) { continue; } Object value = getValueForProperty(propertyDescriptor, object); Class<?> propertyClass = propertyDescriptor.getPropertyType(); if (propertyClass.isPrimitive()) { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, ClassUtils .primitiveToWrapper(propertyClass))); } else { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass)); } } for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) { EDBObjectEntry entry = objectEntry.getValue(); Class<?> entryType; try { entryType = model.getClassLoader().loadClass(entry.getType()); entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType)); } catch (ClassNotFoundException e) { LOGGER.error("Unable to load class {} of the model tail", entry.getType()); } } return ModelUtils.createModel(model, entries); }
java
{ "resource": "" }
q13194
EDBConverter.getPropertyDescriptorsForClass
train
private List<PropertyDescriptor> getPropertyDescriptorsForClass(Class<?> clasz) { try { BeanInfo beanInfo = Introspector.getBeanInfo(clasz); return Arrays.asList(beanInfo.getPropertyDescriptors()); } catch (IntrospectionException e) { LOGGER.error("instantiation exception while trying to create instance of class {}", clasz.getName()); } return Lists.newArrayList(); }
java
{ "resource": "" }
q13195
EDBConverter.getValueForProperty
train
private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) { Method setterMethod = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getName(); Object value = object.getObject(propertyName); Class<?> parameterType = setterMethod.getParameterTypes()[0]; // TODO: OPENENGSB-2719 do that in a better way than just an if-else series if (Map.class.isAssignableFrom(parameterType)) { List<Class<?>> classes = getGenericMapParameterClasses(setterMethod); value = getMapValue(classes.get(0), classes.get(1), propertyName, object); } else if (List.class.isAssignableFrom(parameterType)) { Class<?> clazz = getGenericListParameterClass(setterMethod); value = getListValue(clazz, propertyName, object); } else if (parameterType.isArray()) { Class<?> clazz = parameterType.getComponentType(); value = getArrayValue(clazz, propertyName, object); } else if (value == null) { return null; } else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) { Object timestamp = object.getObject(EDBConstants.MODEL_TIMESTAMP); Long time = System.currentTimeMillis(); if (timestamp != null) { try { time = Long.parseLong(timestamp.toString()); } catch (NumberFormatException e) { LOGGER.warn("The model with the oid {} has an invalid timestamp.", object.getOID()); } } EDBObject obj = edbService.getObject((String) value, time); value = convertEDBObjectToUncheckedModel(parameterType, obj); object.remove(propertyName); } else if (parameterType.equals(FileWrapper.class)) { FileWrapper wrapper = new FileWrapper(); String filename = object.getString(propertyName + FILEWRAPPER_FILENAME_SUFFIX); String content = (String) value; wrapper.setFilename(filename); wrapper.setContent(Base64.decodeBase64(content)); value = wrapper; object.remove(propertyName + FILEWRAPPER_FILENAME_SUFFIX); } else if (parameterType.equals(File.class)) { return null; } else if (object.containsKey(propertyName)) { if (parameterType.isEnum()) { value = getEnumValue(parameterType, value); } } object.remove(propertyName); return value; }
java
{ "resource": "" }
q13196
EDBConverter.getListValue
train
@SuppressWarnings("unchecked") private <T> List<T> getListValue(Class<T> type, String propertyName, EDBObject object) { List<T> temp = new ArrayList<>(); for (int i = 0;; i++) { String property = getEntryNameForList(propertyName, i); Object obj = object.getObject(property); if (obj == null) { break; } if (OpenEngSBModel.class.isAssignableFrom(type)) { obj = convertEDBObjectToUncheckedModel(type, edbService.getObject(object.getString(property))); } temp.add((T) obj); object.remove(property); } return temp; }
java
{ "resource": "" }
q13197
EDBConverter.getArrayValue
train
@SuppressWarnings("unchecked") private <T> T[] getArrayValue(Class<T> type, String propertyName, EDBObject object) { List<T> elements = getListValue(type, propertyName, object); T[] ar = (T[]) Array.newInstance(type, elements.size()); return elements.toArray(ar); }
java
{ "resource": "" }
q13198
EDBConverter.getMapValue
train
private Object getMapValue(Class<?> keyType, Class<?> valueType, String propertyName, EDBObject object) { Map<Object, Object> temp = new HashMap<>(); for (int i = 0;; i++) { String keyProperty = getEntryNameForMapKey(propertyName, i); String valueProperty = getEntryNameForMapValue(propertyName, i); if (!object.containsKey(keyProperty)) { break; } Object key = object.getObject(keyProperty); Object value = object.getObject(valueProperty); if (OpenEngSBModel.class.isAssignableFrom(keyType)) { key = convertEDBObjectToUncheckedModel(keyType, edbService.getObject(key.toString())); } if (OpenEngSBModel.class.isAssignableFrom(valueType)) { value = convertEDBObjectToUncheckedModel(valueType, edbService.getObject(value.toString())); } temp.put(key, value); object.remove(keyProperty); object.remove(valueProperty); } return temp; }
java
{ "resource": "" }
q13199
EDBConverter.getEnumValue
train
private Object getEnumValue(Class<?> type, Object value) { Object[] enumValues = type.getEnumConstants(); for (Object enumValue : enumValues) { if (enumValue.toString().equals(value.toString())) { value = enumValue; break; } } return value; }
java
{ "resource": "" }