_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q13200
EDBConverter.convertEKBCommit
train
public ConvertedCommit convertEKBCommit(EKBCommit commit) { ConvertedCommit result = new ConvertedCommit(); ConnectorInformation information = commit.getConnectorInformation(); result.setInserts(convertModelsToEDBObjects(commit.getInserts(), information)); result.setUpdates(convertModelsToEDBObjects(commit.getUpdates(), information)); result.setDeletes(convertModelsToEDBObjects(commit.getDeletes(), information)); return result; }
java
{ "resource": "" }
q13201
EDBConverter.fillEDBObjectWithEngineeringObjectInformation
train
private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model) throws IllegalAccessException { if (!new AdvancedModelWrapper(model).isEngineeringObject()) { return; } for (Field field : model.getClass().getDeclaredFields()) { OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class); if (annotation == null) { continue; } String value = (String) FieldUtils.readField(field, model, true); if (value == null) { continue; } value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value); String key = getEOReferenceStringFromAnnotation(annotation); object.put(key, new EDBObjectEntry(key, value, String.class)); } }
java
{ "resource": "" }
q13202
EDBConverter.filterEngineeringObjectInformation
train
private void filterEngineeringObjectInformation(EDBObject object, Class<?> model) { if (!AdvancedModelWrapper.isEngineeringObjectClass(model)) { return; } Iterator<String> keys = object.keySet().iterator(); while (keys.hasNext()) { if (keys.next().startsWith(REFERENCE_PREFIX)) { keys.remove(); } } }
java
{ "resource": "" }
q13203
EDBConverter.getEntryNameForMapKey
train
public static String getEntryNameForMapKey(String property, Integer index) { return getEntryNameForMap(property, true, index); }
java
{ "resource": "" }
q13204
EDBConverter.getEntryNameForMapValue
train
public static String getEntryNameForMapValue(String property, Integer index) { return getEntryNameForMap(property, false, index); }
java
{ "resource": "" }
q13205
EDBConverter.getEntryNameForMap
train
private static String getEntryNameForMap(String property, Boolean key, Integer index) { return String.format("%s.%d.%s", property, index, key ? "key" : "value"); }
java
{ "resource": "" }
q13206
EDBConverter.getEntryNameForList
train
public static String getEntryNameForList(String property, Integer index) { return String.format("%s.%d", property, index); }
java
{ "resource": "" }
q13207
EDBConverter.getEOReferenceStringFromAnnotation
train
public static String getEOReferenceStringFromAnnotation(OpenEngSBForeignKey key) { return String.format("%s%s:%s", REFERENCE_PREFIX, key.modelType(), key.modelVersion().toString()); }
java
{ "resource": "" }
q13208
XLinkUtils.assigneModelsToViews
train
private static Map<String, ModelDescription> assigneModelsToViews(Map<ModelDescription, XLinkConnectorView[]> modelsToViews) { HashMap<String, ModelDescription> viewsToModels = new HashMap<String, ModelDescription>(); for (ModelDescription modelInfo : modelsToViews.keySet()) { List<XLinkConnectorView> currentViewList = Arrays.asList(modelsToViews.get(modelInfo)); for (XLinkConnectorView view : currentViewList) { if (!viewsToModels.containsKey(view.getViewId())) { viewsToModels.put(view.getViewId(), modelInfo); } } } return viewsToModels; }
java
{ "resource": "" }
q13209
XLinkUtils.getExpirationDate
train
private static String getExpirationDate(int futureDays) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, futureDays); Format formatter = new SimpleDateFormat(XLinkConstants.DATEFORMAT); return formatter.format(calendar.getTime()); }
java
{ "resource": "" }
q13210
XLinkUtils.setValueOfModel
train
public static void setValueOfModel(Object model, OpenEngSBModelEntry entry, Object value) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Class clazz = model.getClass(); Field field = clazz.getDeclaredField(entry.getKey()); field.setAccessible(true); field.set(model, value); }
java
{ "resource": "" }
q13211
XLinkUtils.createInstanceOfModelClass
train
public static Object createInstanceOfModelClass(Class clazzObject, List<OpenEngSBModelEntry> entries) { return ModelUtils.createModel(clazzObject, entries); }
java
{ "resource": "" }
q13212
XLinkUtils.dateStringToCalendar
train
public static Calendar dateStringToCalendar(String dateString) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat(XLinkConstants.DATEFORMAT); try { calendar.setTime(formatter.parse(dateString)); } catch (Exception ex) { return null; } return calendar; }
java
{ "resource": "" }
q13213
XLinkUtils.urlEncodeParameter
train
private static String urlEncodeParameter(String parameter) { try { return URLEncoder.encode(parameter, "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(XLinkUtils.class.getName()).log(Level.SEVERE, null, ex); } return parameter; }
java
{ "resource": "" }
q13214
XLinkUtils.getViewsOfRegistration
train
public static XLinkConnectorView[] getViewsOfRegistration(XLinkConnectorRegistration registration) { List<XLinkConnectorView> viewsOfRegistration = new ArrayList<XLinkConnectorView>(); Map<ModelDescription, XLinkConnectorView[]> modelsToViews = registration.getModelsToViews(); for (XLinkConnectorView[] views : modelsToViews.values()) { for (int i = 0; i < views.length; i++) { XLinkConnectorView view = views[i]; if (!viewsOfRegistration.contains(view)) { viewsOfRegistration.add(view); } } } return viewsOfRegistration.toArray(new XLinkConnectorView[0]); }
java
{ "resource": "" }
q13215
XLinkUtils.getLocalToolFromRegistrations
train
public static XLinkConnector[] getLocalToolFromRegistrations(List<XLinkConnectorRegistration> registrations) { List<XLinkConnector> tools = new ArrayList<XLinkConnector>(); for (XLinkConnectorRegistration registration : registrations) { XLinkConnector newLocalTools = new XLinkConnector( registration.getConnectorId(), registration.getToolName(), getViewsOfRegistration(registration)); tools.add(newLocalTools); } return tools.toArray(new XLinkConnector[0]); }
java
{ "resource": "" }
q13216
JpaTarget.mergeInTransaction
train
private void mergeInTransaction(EntityManager em, Collection objects) { EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); for (Object o : objects) { em.merge(o); } tx.commit(); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } }
java
{ "resource": "" }
q13217
SchemaCreateCommand.execute
train
public void execute() { try { new JdbcTemplate(dataSource).execute(readResourceContent(SCHEMA_FILE)); // TODO: sql independence } catch (IOException e) { throw new RuntimeException("Could not create schema for EDBI Index", e); } }
java
{ "resource": "" }
q13218
TimebasedOrderFilter.addId
train
public static void addId(Entry entry, boolean updateRdn) { String uuid = newUUID().toString(); try { entry.add(SchemaConstants.OBJECT_CLASS_ATTRIBUTE, UNIQUE_OBJECT_OC); entry.add(ID_ATTRIBUTE, uuid); } catch (LdapException e) { throw new LdapRuntimeException(e); } if (updateRdn) { Dn newDn = LdapUtils.concatDn(ID_ATTRIBUTE, uuid, entry.getDn().getParent()); entry.setDn(newDn); } }
java
{ "resource": "" }
q13219
TimebasedOrderFilter.addIds
train
public static void addIds(List<Entry> entries, boolean updateRdn) { for (Entry entry : entries) { addId(entry, updateRdn); } }
java
{ "resource": "" }
q13220
ClusteredExecutorService.initialize
train
protected synchronized void initialize() { String invocationServiceName = this.invocationServiceName; invocationService = (InvocationService) CacheFactory.getService(invocationServiceName); if (invocationService == null) { throw new IllegalArgumentException("Invocation service [" + invocationServiceName + "] is not defined."); } invocationService.addMemberListener(this); serviceMembers = invocationService.getInfo().getServiceMembers(); memberIterator = serviceMembers.iterator(); }
java
{ "resource": "" }
q13221
ClusteredExecutorService.execute
train
public void execute(Runnable command) { if (!(command instanceof ClusteredFutureTask)) { command = new ClusteredFutureTask<Object>(command, null); } command.run(); }
java
{ "resource": "" }
q13222
ClusteredExecutorService.getExecutionMember
train
protected synchronized Member getExecutionMember() { Iterator<Member> it = memberIterator; if (it == null || !it.hasNext()) { memberIterator = it = serviceMembers.iterator(); } return it.next(); }
java
{ "resource": "" }
q13223
AbstractAnnotationCatalogAccessorProvider.getMethodAccessor
train
protected BrokerServiceAccessor getMethodAccessor(String serviceBrokerName, CatalogService description) { return new AnnotationBrokerServiceAccessor(description, serviceBrokerName, getBeanClass(serviceBrokerName), context.getBean(serviceBrokerName)); }
java
{ "resource": "" }
q13224
AbstractAnnotationCatalogAccessorProvider.getBeanClass
train
protected Class<?> getBeanClass(String beanName) { Class<?> clazz = context.getType(beanName); while (Proxy.isProxyClass(clazz) || Enhancer.isEnhanced(clazz)) { clazz = clazz.getSuperclass(); } return clazz; }
java
{ "resource": "" }
q13225
Constraint.skipSolver
train
public void skipSolver(ConstraintSolver ... solvers) { if (solversToSkip == null) solversToSkip = new HashSet<ConstraintSolver>(); for (ConstraintSolver solver : solvers) solversToSkip.add(solver); }
java
{ "resource": "" }
q13226
XmlTarget.initAttributesAndElements
train
private void initAttributesAndElements(String... propertyNames) { for (String propertyName : propertyNames) { Property property = new Property(propertyName); if (property.isAttribute()) { m_attributes.add(property); } else { m_elements.add(property); } } }
java
{ "resource": "" }
q13227
TimePoint.setUsed
train
public void setUsed(boolean newVal){ if(isUsed() && newVal == false) { Arrays.fill(out, null); } used = newVal; }
java
{ "resource": "" }
q13228
PadOperation.getPadCharacter
train
private Character getPadCharacter(String characterString) { if (characterString.length() > 0) { getLogger().debug("The given character string is longer than one element. The first character is used."); } return characterString.charAt(0); }
java
{ "resource": "" }
q13229
PadOperation.getDirectionString
train
private String getDirectionString(String direction) { if (direction == null || !(direction.equals("Start") || direction.equals("End"))) { getLogger().debug("Unrecognized direction string. The standard value 'Start' will be used."); return "Start"; } return direction; }
java
{ "resource": "" }
q13230
PadOperation.performPadOperation
train
private String performPadOperation(String source, Integer length, Character padChar, String direction) { if (direction.equals("Start")) { return Strings.padStart(source, length, padChar); } else { return Strings.padEnd(source, length, padChar); } }
java
{ "resource": "" }
q13231
ProjectFileAccessObject.findAllProjects
train
public List<Project> findAllProjects() { List<Project> list = new ArrayList<>(); List<String> projectNames; try { projectNames = readLines(projectsFile); } catch (IOException e) { throw new FileBasedRuntimeException(e); } for (String projectName : projectNames) { if (StringUtils.isNotBlank(projectName)) { list.add(new Project(projectName)); } } return list; }
java
{ "resource": "" }
q13232
Introspector.getPropertyTypeMap
train
public static Map<String, Class<?>> getPropertyTypeMap(Class<?> clazz, String... exclude) { PropertyDescriptor[] descriptors; try { descriptors = getPropertyDescriptors(clazz); } catch (IntrospectionException e) { LOG.error("Failed to introspect " + clazz, e); return Collections.emptyMap(); } HashMap<String, Class<?>> map = new HashMap<>(descriptors.length); for (PropertyDescriptor pd : descriptors) { map.put(pd.getName(), pd.getPropertyType()); } for (String property : exclude) { map.remove(property); } return map; }
java
{ "resource": "" }
q13233
Introspector.read
train
public static Map<String, Object> read(Object object) { PropertyDescriptor[] descriptors; Class<?> clazz = object.getClass(); try { descriptors = getPropertyDescriptors(clazz); } catch (IntrospectionException e) { LOG.error("Failed to introspect " + clazz, e); return Collections.emptyMap(); } HashMap<String, Object> map = new HashMap<>(descriptors.length); for (PropertyDescriptor pd : descriptors) { try { Object value = pd.getReadMethod().invoke(object); map.put(pd.getName(), value); } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { LOG.error("Failed to visit property " + pd.getName(), e); } } map.remove("class"); return map; }
java
{ "resource": "" }
q13234
AdvancedModelWrapper.wrap
train
public static AdvancedModelWrapper wrap(Object model) { if (!(isModel(model.getClass()))) { throw new IllegalArgumentException("The given object is no model"); } return new AdvancedModelWrapper((OpenEngSBModel) model); }
java
{ "resource": "" }
q13235
AdvancedModelWrapper.getModelsReferringToThisModel
train
public List<EDBObject> getModelsReferringToThisModel(EngineeringDatabaseService edbService) { return edbService.query(QueryRequest.query( EDBConverter.REFERENCE_PREFIX + "%", getCompleteModelOID())); }
java
{ "resource": "" }
q13236
AdvancedModelWrapper.isEngineeringObjectClass
train
public static Boolean isEngineeringObjectClass(Class<?> clazz) { for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(OpenEngSBForeignKey.class)) { return true; } } return false; }
java
{ "resource": "" }
q13237
JsonUtils.convertObject
train
public static <T> T convertObject(String json, Class<T> clazz) throws IOException { try { if (clazz.isAnnotationPresent(Model.class)) { return MODEL_MAPPER.readValue(json, clazz); } return MAPPER.readValue(json, clazz); } catch (IOException e) { String error = String.format("Unable to parse given json '%s' into class '%s'.", json, clazz.getName()); LOGGER.error(error, e); throw new IOException(error, e); } }
java
{ "resource": "" }
q13238
CommitConverter.convert
train
public IndexCommit convert(EKBCommit ekbCommit) { IndexCommit commit = new IndexCommit(); commit.setCommitId(ekbCommit.getRevisionNumber()); commit.setParentCommitId(ekbCommit.getParentRevisionNumber()); commit.setConnectorId(ekbCommit.getConnectorId()); commit.setDomainId(ekbCommit.getDomainId()); commit.setInstanceId(ekbCommit.getInstanceId()); commit.setTimestamp(new Date()); commit.setUser(getUser()); commit.setContextId(getContextId()); List<OpenEngSBModel> inserts = ekbCommit.getInserts(); List<OpenEngSBModel> updates = ekbCommit.getUpdates(); List<OpenEngSBModel> deletes = ekbCommit.getDeletes(); Set<Class<?>> modelClasses = extractTypes(inserts, updates, deletes); commit.setModelClasses(modelClasses); commit.setInserts(mapByClass(inserts)); commit.setUpdates(mapByClass(updates)); commit.setDeletes(mapByClass(deletes)); return commit; }
java
{ "resource": "" }
q13239
CommitConverter.mapByClass
train
protected Map<Class<?>, List<OpenEngSBModel>> mapByClass(Collection<OpenEngSBModel> models) { return group(models, new Function<OpenEngSBModel, Class<?>>() { @Override public Class<?> apply(OpenEngSBModel input) { return input.getClass(); } }); }
java
{ "resource": "" }
q13240
CatalogAccessor.createCatalog
train
public Catalog createCatalog() { final List<CatalogService> services = new ArrayList<>(); for (BrokerServiceAccessor serviceAccessor : serviceAccessors) { services.add(serviceAccessor.getServiceDescription()); } return new Catalog(services); }
java
{ "resource": "" }
q13241
CatalogAccessor.getServiceAccessor
train
public BrokerServiceAccessor getServiceAccessor(String serviceId) { for (BrokerServiceAccessor serviceAccessor : serviceAccessors) { if (serviceId.equals(serviceAccessor.getServiceDescription().getId())) { return serviceAccessor; } } throw new NotFoundException("Could not find service broker with service_id " + serviceId); }
java
{ "resource": "" }
q13242
OrientModelGraphUtils.setIdFieldValue
train
public static void setIdFieldValue(ODocument document, String value) { setFieldValue(document, OGraphDatabase.LABEL, value); }
java
{ "resource": "" }
q13243
OrientModelGraphUtils.setActiveFieldValue
train
public static void setActiveFieldValue(ODocument document, Boolean active) { setFieldValue(document, ACTIVE_FIELD, active.toString()); }
java
{ "resource": "" }
q13244
OrientModelGraphUtils.getFieldValue
train
public static String getFieldValue(ODocument document, String fieldname) { return (String) document.field(fieldname); }
java
{ "resource": "" }
q13245
OrientModelGraphUtils.setFieldValue
train
public static void setFieldValue(ODocument document, String fieldname, String value) { document.field(fieldname, value); }
java
{ "resource": "" }
q13246
OrientModelGraphUtils.fillEdgeWithPropertyConnections
train
public static void fillEdgeWithPropertyConnections(ODocument edge, TransformationDescription description) { Map<String, String> connections = convertPropertyConnectionsToSimpleForm(description.getPropertyConnections()); for (Map.Entry<String, String> entry : connections.entrySet()) { edge.field(entry.getKey(), entry.getValue()); } }
java
{ "resource": "" }
q13247
PermutationsWithRepetition.getVariations
train
public int[][] getVariations() { int permutations = (int) Math.pow(n, r); int[][] table = new int[permutations][r]; for (int x = 0; x < r; x++) { int t2 = (int) Math.pow(n, x); for (int p1 = 0; p1 < permutations;) { for (int al = 0; al < n; al++) { for (int p2 = 0; p2 < t2; p2++) { table[p1][x] = al; p1++; } } } } return table; }
java
{ "resource": "" }
q13248
CheckPreCommitHook.checkInserts
train
private List<JPAObject> checkInserts(List<JPAObject> inserts) { List<JPAObject> failedObjects = new ArrayList<JPAObject>(); for (JPAObject insert : inserts) { String oid = insert.getOID(); if (checkIfActiveOidExisting(oid)) { failedObjects.add(insert); } else { insert.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, "1", Integer.class.getName(), insert)); } } return failedObjects; }
java
{ "resource": "" }
q13249
CheckPreCommitHook.checkDeletions
train
private List<String> checkDeletions(List<String> deletes) { List<String> failedObjects = new ArrayList<String>(); for (String delete : deletes) { if (!checkIfActiveOidExisting(delete)) { failedObjects.add(delete); } } return failedObjects; }
java
{ "resource": "" }
q13250
CheckPreCommitHook.checkUpdates
train
private List<JPAObject> checkUpdates(List<JPAObject> updates) throws EDBException { List<JPAObject> failedObjects = new ArrayList<JPAObject>(); for (JPAObject update : updates) { try { Integer modelVersion = investigateVersionAndCheckForConflict(update); modelVersion++; update.removeEntry(EDBConstants.MODEL_VERSION); update.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, modelVersion + "", Integer.class.getName(), update)); } catch (EDBException e) { failedObjects.add(update); } } return failedObjects; }
java
{ "resource": "" }
q13251
CheckPreCommitHook.investigateVersionAndCheckForConflict
train
private Integer investigateVersionAndCheckForConflict(JPAObject newObject) throws EDBException { JPAEntry entry = newObject.getEntry(EDBConstants.MODEL_VERSION); String oid = newObject.getOID(); Integer modelVersion = 0; if (entry != null) { modelVersion = Integer.parseInt(entry.getValue()); Integer currentVersion = dao.getVersionOfOid(oid); if (!modelVersion.equals(currentVersion)) { try { checkForConflict(newObject); } catch (EDBException e) { LOGGER.info("conflict detected, user get informed"); throw new EDBException("conflict was detected. There is a newer version of the model with the oid " + oid + " saved."); } modelVersion = currentVersion; } } else { modelVersion = dao.getVersionOfOid(oid); } return modelVersion; }
java
{ "resource": "" }
q13252
CheckPreCommitHook.checkForConflict
train
private void checkForConflict(JPAObject newObject) throws EDBException { String oid = newObject.getOID(); JPAObject object = dao.getJPAObject(oid); for (JPAEntry entry : newObject.getEntries()) { if (entry.getKey().equals(EDBConstants.MODEL_VERSION)) { continue; } JPAEntry rival = object.getEntry(entry.getKey()); String value = rival != null ? rival.getValue() : null; if (value == null || !value.equals(entry.getValue())) { LOGGER.debug("Conflict detected at key {} when comparing {} with {}", new Object[]{ entry.getKey(), entry.getValue(), value == null ? "null" : value }); throw new EDBException("Conflict detected. Failure when comparing the values of the key " + entry.getKey()); } } }
java
{ "resource": "" }
q13253
WsdlToDll.execute
train
@Override public void execute() throws MojoExecutionException { checkParameters(); windowsModus = isWindows(); if (windowsModus) { setWindowsVariables(); } else { setLinuxVariables(); } createDllFromWsdl(); }
java
{ "resource": "" }
q13254
WsdlToDll.createDllFromWsdl
train
private void createDllFromWsdl() throws MojoExecutionException { getLog().info("Execute WSDl to cs command"); wsdlCommand(); getLog().info("Execute cs to dll command"); cscCommand(); if (generateNugetPackage) { if (isLinux()) { throw new MojoExecutionException( "At this point, mono and nuget does not work so well together." + "Please execute the plugin with nuget under Windows"); } nugetLib = nugetFolder + "lib"; getLog().info("Create Nuget folder structure"); createNugetStructure(); getLog().info("Copy the dlls to the nuget structure"); copyFilesToNuget(); getLog().info("Generate " + namespace + " .nuspec"); generateNugetPackedFile(); getLog().info("Pack .nuspec to a nuget package"); nugetPackCommand(); } }
java
{ "resource": "" }
q13255
WsdlToDll.wsdlCommand
train
private void wsdlCommand() throws MojoExecutionException { String cmd = findWsdlCommand(); int i = 0; for (String location : wsdlLocations) { String outputFilename = new File(outputDirectory, namespace + (i++) + ".cs").getAbsolutePath(); String[] command = new String[]{ cmd, serverParameter, "/n:" + namespace, location, "/out:" + outputFilename }; ProcessBuilder builder = new ProcessBuilder(); builder.redirectErrorStream(true); builder.command(command); try { executeACommand(builder.start()); } catch (IOException | InterruptedException e) { throw new MojoExecutionException( "Error, while executing command: " + Arrays.toString(command) + "\n", e); } cspath.add(outputFilename); } try { FileComparer.removeSimilaritiesAndSaveFiles(cspath, getLog(), windowsModus); } catch (IOException e) { throw new MojoExecutionException( "It was not possible, to remove similarities form the files", e); } }
java
{ "resource": "" }
q13256
WsdlToDll.cscCommand
train
private void cscCommand() throws MojoExecutionException { generateAssemblyInfo(); String cscPath = findCscCommand(); List<String> commandList = new LinkedList<String>(cspath); commandList.add(0, cscPath); commandList.add(1, "/target:library"); commandList.add(2, "/out:" + namespace + ".dll"); if (isLinux()) { commandList.add(3, "/reference:System.Web.Services"); } String[] command = commandList.toArray(new String[commandList.size()]); ProcessBuilder builder = new ProcessBuilder(); builder.redirectErrorStream(true); builder.directory(outputDirectory); builder.command(command); try { executeACommand(builder.start()); } catch (InterruptedException | IOException e) { throw new MojoExecutionException("Error, while executing command: " + Arrays.toString(command) + "\n", e); } }
java
{ "resource": "" }
q13257
WsdlToDll.nugetPackCommand
train
private void nugetPackCommand() throws MojoExecutionException { List<String> commandList = new LinkedList<String>(); commandList.add(0, NUGET_COMMAND); commandList.add(1, "pack"); String[] command = commandList.toArray(new String[commandList.size()]); ProcessBuilder builder = new ProcessBuilder(); builder.redirectErrorStream(true); builder.directory(new File(nugetFolder)); builder.command(command); try { executeACommand(builder.start()); } catch (InterruptedException | IOException e) { throw new MojoExecutionException("Error, while executing command: " + Arrays.toString(command) + "\n", e); } }
java
{ "resource": "" }
q13258
IndexCommitBuilder.insert
train
public IndexCommitBuilder insert(Object object) { updateModelClassSet(object); getInsertList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
{ "resource": "" }
q13259
IndexCommitBuilder.update
train
public IndexCommitBuilder update(Object object) { updateModelClassSet(object); getUpdateList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
{ "resource": "" }
q13260
IndexCommitBuilder.delete
train
public IndexCommitBuilder delete(Object object) { updateModelClassSet(object); getDeleteList(object.getClass()).add((OpenEngSBModel) object); return this; }
java
{ "resource": "" }
q13261
TransformationPerformer.checkNeededValues
train
private void checkNeededValues(TransformationDescription description) { String message = "The TransformationDescription doesn't contain a %s. Description loading aborted"; if (description.getSourceModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "source class")); } if (description.getTargetModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "target class")); } String message2 = "The version string of the %s is not a correct version string. Description loading aborted"; try { Version.parseVersion(description.getSourceModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "source class"), e); } try { Version.parseVersion(description.getTargetModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "target class"), e); } }
java
{ "resource": "" }
q13262
TransformationPerformer.transformObject
train
public Object transformObject(TransformationDescription description, Object source) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return transformObject(description, source, null); }
java
{ "resource": "" }
q13263
TransformationPerformer.transformObject
train
public Object transformObject(TransformationDescription description, Object source, Object target) throws InstantiationException, IllegalAccessException, ClassNotFoundException { checkNeededValues(description); Class<?> sourceClass = modelRegistry.loadModel(description.getSourceModel()); Class<?> targetClass = modelRegistry.loadModel(description.getTargetModel()); if (!sourceClass.isAssignableFrom(source.getClass())) { throw new IllegalArgumentException("The given source object does not match the given description"); } this.source = source; if (target == null) { this.target = targetClass.newInstance(); } else { this.target = target; } for (TransformationStep step : description.getTransformingSteps()) { performTransformationStep(step); } return this.target; }
java
{ "resource": "" }
q13264
TransformationPerformer.performTransformationStep
train
private void performTransformationStep(TransformationStep step) throws IllegalAccessException { try { TransformationOperation operation = operationLoader.loadTransformationOperationByName(step.getOperationName()); Object value = operation.performOperation(getSourceFieldValues(step), step.getOperationParams()); setObjectToTargetField(step.getTargetField(), value); } catch (TransformationStepException e) { LOGGER.debug(e.getMessage(), e); } catch (Exception e) { LOGGER.error("Unable to perform transformation step {}.", step, e); } }
java
{ "resource": "" }
q13265
TransformationPerformer.getSourceFieldValues
train
private List<Object> getSourceFieldValues(TransformationStep step) throws Exception { List<Object> sources = new ArrayList<Object>(); for (String sourceField : step.getSourceFields()) { Object object = getObjectValue(sourceField, true); if (object == null) { String message = String.format("The source field %s is null. Step will be be ignored", sourceField); throw new TransformationStepException(message); } sources.add(object); } return sources; }
java
{ "resource": "" }
q13266
TransformationPerformer.setObjectToTargetField
train
private void setObjectToTargetField(String fieldname, Object value) throws Exception { Object toWrite = null; if (fieldname.contains(".")) { String path = StringUtils.substringBeforeLast(fieldname, "."); toWrite = getObjectValue(path, false); } if (toWrite == null && isTemporaryField(fieldname)) { String mapKey = StringUtils.substringAfter(fieldname, "#"); mapKey = StringUtils.substringBefore(mapKey, "."); temporaryFields.put(mapKey, value); return; } String realFieldName = fieldname.contains(".") ? StringUtils.substringAfterLast(fieldname, ".") : fieldname; writeObjectToField(realFieldName, value, toWrite, target); }
java
{ "resource": "" }
q13267
TransformationPerformer.getObjectValue
train
private Object getObjectValue(String fieldname, boolean fromSource) throws Exception { Object sourceObject = fromSource ? source : target; Object result = null; for (String part : StringUtils.split(fieldname, ".")) { if (isTemporaryField(part)) { result = loadObjectFromTemporary(part, fieldname); } else { result = loadObjectFromField(part, result, sourceObject); } } return result; }
java
{ "resource": "" }
q13268
TransformationPerformer.loadObjectFromField
train
private Object loadObjectFromField(String fieldname, Object object, Object alternative) throws Exception { Object source = object != null ? object : alternative; try { return FieldUtils.readField(source, fieldname, true); } catch (Exception e) { throw new IllegalArgumentException(String.format("Unable to load field '%s' from object '%s'", fieldname, source.getClass().getName())); } }
java
{ "resource": "" }
q13269
TransformationPerformer.writeObjectToField
train
private void writeObjectToField(String fieldname, Object value, Object object, Object alternative) throws Exception { Object target = object != null ? object : alternative; try { FieldUtils.writeField(target, fieldname, value, true); } catch (Exception e) { throw new IllegalArgumentException(String.format("Unable to write value '%s' to field '%s' of object %s", value.toString(), fieldname, target.getClass().getName())); } }
java
{ "resource": "" }
q13270
DefaultOsgiUtilsService.waitForServiceFromTracker
train
private static Object waitForServiceFromTracker(ServiceTracker tracker, long timeout) throws OsgiServiceNotAvailableException { synchronized (tracker) { tracker.open(); try { return tracker.waitForService(timeout); } catch (InterruptedException e) { throw new OsgiServiceNotAvailableException(e); } finally { tracker.close(); } } }
java
{ "resource": "" }
q13271
DefaultConfirmDialogFactory.getDialogDimensions
train
protected double[] getDialogDimensions(String message, VaadinConfirmDialog.ContentMode style) { // Based on Reindeer style: double chrW = 0.51d; double chrH = 1.5d; double length = message != null? chrW * message.length() : 0; double rows = Math.ceil(length / MAX_WIDTH); // Estimate extra lines if (style == VaadinConfirmDialog.ContentMode.TEXT_WITH_NEWLINES) { rows += message != null? count("\n", message): 0; } //System.out.println(message.length() + " = " + length + "em"); //System.out.println("Rows: " + (length / MAX_WIDTH) + " = " + rows); // Obey maximum size double width = Math.min(MAX_WIDTH, length); double height = Math.ceil(Math.min(MAX_HEIGHT, rows * chrH)); // Obey the minimum size width = Math.max(width, MIN_WIDTH); height = Math.max(height, MIN_HEIGHT); // Based on Reindeer style: double btnHeight = 4d; double vmargin = 5d; double hmargin = 1d; double[] res = new double[] { width + hmargin, height + btnHeight + vmargin }; //System.out.println(res[0] + "," + res[1]); return res; }
java
{ "resource": "" }
q13272
DefaultConfirmDialogFactory.count
train
private static int count(final String needle, final String haystack) { int count = 0; int pos = -1; while ((pos = haystack.indexOf(needle, pos + 1)) >= 0) { count++; } return count; }
java
{ "resource": "" }
q13273
DefaultConfirmDialogFactory.format
train
private String format(double n) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setMaximumFractionDigits(1); nf.setGroupingUsed(false); return nf.format(n); }
java
{ "resource": "" }
q13274
EDBModelObject.getModelDescription
train
public ModelDescription getModelDescription() { String modelType = object.getString(EDBConstants.MODEL_TYPE); String version = object.getString(EDBConstants.MODEL_TYPE_VERSION); return new ModelDescription(modelType, version); }
java
{ "resource": "" }
q13275
EDBModelObject.getCorrespondingModel
train
public OpenEngSBModel getCorrespondingModel() throws EKBException { ModelDescription description = getModelDescription(); try { Class<?> modelClass = modelRegistry.loadModel(description); return (OpenEngSBModel) edbConverter.convertEDBObjectToModel(modelClass, object); } catch (ClassNotFoundException e) { throw new EKBException(String.format("Unable to load model of type %s", description), e); } }
java
{ "resource": "" }
q13276
CsvSource.iterator
train
public Iterator iterator() { CsvPreference preferences = new CsvPreference.Builder(m_quoteChar, m_delimiterChar, m_endOfLineSymbols).build(); return new CsvIterator(new CsvListReader(m_reader, preferences), m_header); }
java
{ "resource": "" }
q13277
MvelExpression.getCompiledExpression
train
protected Serializable getCompiledExpression() { if (compiledExpression == null) { compiledExpression = MVEL.compileExpression(getExpression(), PARSER_CONTEXT); } return compiledExpression; }
java
{ "resource": "" }
q13278
MvelExpression.getCompiledSetExpression
train
protected Serializable getCompiledSetExpression() { if (compiledSetExpression == null) { compiledSetExpression = MVEL.compileSetExpression(getExpression(), PARSER_CONTEXT); } return compiledSetExpression; }
java
{ "resource": "" }
q13279
ServiceEditorPanel.attachFormValidator
train
public void attachFormValidator(final Form<?> form, final FormValidator validator) { form.add(new AbstractFormValidator() { private static final long serialVersionUID = -4181095793820830517L; @Override public void validate(Form<?> form) { Map<String, FormComponent<?>> loadFormComponents = loadFormComponents(form); Map<String, String> toValidate = new HashMap<String, String>(); for (Map.Entry<String, FormComponent<?>> entry : loadFormComponents.entrySet()) { toValidate.put(entry.getKey(), entry.getValue().getValue()); } try { validator.validate(toValidate); } catch (ConnectorValidationFailedException e) { Map<String, String> attributeErrorMessages = e.getErrorMessages(); for (Map.Entry<String, String> entry : attributeErrorMessages.entrySet()) { FormComponent<?> fc = loadFormComponents.get(entry.getKey()); fc.error(new ValidationError().setMessage(entry.getValue())); } } } @Override public FormComponent<?>[] getDependentFormComponents() { Collection<FormComponent<?>> formComponents = loadFormComponents(form).values(); return formComponents.toArray(new FormComponent<?>[formComponents.size()]); } private Map<String, FormComponent<?>> loadFormComponents(final Form<?> form) { Map<String, FormComponent<?>> formComponents = new HashMap<String, FormComponent<?>>(); if (validator != null) { for (String attribute : validator.fieldsToValidate()) { Component component = form.get("attributesPanel:fields:" + attribute + ":row:field"); if (component instanceof FormComponent<?>) { formComponents.put(attribute, (FormComponent<?>) component); } } } return formComponents; } }); }
java
{ "resource": "" }
q13280
AbstractEDBService.performCommitLogic
train
protected Long performCommitLogic(EDBCommit commit) throws EDBException { if (!(commit instanceof JPACommit)) { throw new EDBException("The given commit type is not supported."); } if (commit.isCommitted()) { throw new EDBException("EDBCommit is already commitet."); } if (revisionCheckEnabled && commit.getParentRevisionNumber() != null && !commit.getParentRevisionNumber().equals(getCurrentRevisionNumber())) { throw new EDBException("EDBCommit do not have the correct head revision number."); } runBeginCommitHooks(commit); EDBException exception = runPreCommitHooks(commit); if (exception != null) { return runErrorHooks(commit, exception); } Long timestamp = performCommit((JPACommit) commit); runEDBPostHooks(commit); return timestamp; }
java
{ "resource": "" }
q13281
AbstractEDBService.persistCommitChanges
train
private void persistCommitChanges(JPACommit commit, Long timestamp) { commit.setTimestamp(timestamp); addModifiedObjectsToEntityManager(commit.getJPAObjects(), timestamp); commit.setCommitted(true); logger.debug("persisting JPACommit"); entityManager.persist(commit); logger.debug("mark the deleted elements as deleted"); updateDeletedObjectsThroughEntityManager(commit.getDeletions(), timestamp); }
java
{ "resource": "" }
q13282
AbstractEDBService.addModifiedObjectsToEntityManager
train
private void addModifiedObjectsToEntityManager(List<JPAObject> modified, Long timestamp) { for (JPAObject update : modified) { update.setTimestamp(timestamp); entityManager.persist(update); } }
java
{ "resource": "" }
q13283
AbstractEDBService.updateDeletedObjectsThroughEntityManager
train
private void updateDeletedObjectsThroughEntityManager(List<String> oids, Long timestamp) { for (String id : oids) { EDBObject o = new EDBObject(id); o.updateTimestamp(timestamp); o.setDeleted(true); JPAObject j = EDBUtils.convertEDBObjectToJPAObject(o); entityManager.persist(j); } }
java
{ "resource": "" }
q13284
AbstractEDBService.runBeginCommitHooks
train
private void runBeginCommitHooks(EDBCommit commit) throws EDBException { for (EDBBeginCommitHook hook : beginCommitHooks) { try { hook.onStartCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { throw e; } catch (Exception e) { logger.error("Error while performing EDBBeginCommitHook", e); } } }
java
{ "resource": "" }
q13285
AbstractEDBService.runPreCommitHooks
train
private EDBException runPreCommitHooks(EDBCommit commit) { EDBException exception = null; for (EDBPreCommitHook hook : preCommitHooks) { try { hook.onPreCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { exception = e; break; } catch (Exception e) { logger.error("Error while performing EDBPreCommitHook", e); } } return exception; }
java
{ "resource": "" }
q13286
AbstractEDBService.runErrorHooks
train
private Long runErrorHooks(EDBCommit commit, EDBException exception) throws EDBException { for (EDBErrorHook hook : errorHooks) { try { EDBCommit newCommit = hook.onError(commit, exception); if (newCommit != null) { return commit(newCommit); } } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { exception = e; break; } catch (Exception e) { logger.error("Error while performing EDBErrorHook", e); } } throw exception; }
java
{ "resource": "" }
q13287
AbstractEDBService.runEDBPostHooks
train
private void runEDBPostHooks(EDBCommit commit) { for (EDBPostCommitHook hook : postCommitHooks) { try { hook.onPostCommit(commit); } catch (ServiceUnavailableException e) { // Ignore } catch (Exception e) { logger.error("Error while performing EDBPostCommitHook", e); } } }
java
{ "resource": "" }
q13288
LaconicExplanationGenerator.isLaconic
train
public boolean isLaconic(Explanation<E> justification) throws ExplanationException { // OBSERVATION: If a justification is laconic, then given its O+, there should be // one justification that is equal to itself. // Could optimise more here - we know that a laconic justification won't contain // equivalent classes axioms, inverse properties axioms etc. If an checker doesn't // appear in O+ then it's not laconic! Set<OWLAxiom> justificationSigmaClosure = computeOPlus(justification.getAxioms()); ExplanationGenerator<E> gen2 = explanationGeneratorFactory.createExplanationGenerator(justificationSigmaClosure); Set<Explanation<E>> exps = gen2.getExplanations(justification.getEntailment(), 2); return Collections.singleton(justification).equals(exps); }
java
{ "resource": "" }
q13289
JPAObject.getEntry
train
public JPAEntry getEntry(String entryKey) { for (JPAEntry entry : entries) { if (entry.getKey().equals(entryKey)) { return entry; } } return null; }
java
{ "resource": "" }
q13290
JPAObject.removeEntry
train
public void removeEntry(String entryKey) { Iterator<JPAEntry> iter = entries.iterator(); while (iter.hasNext()) { if (iter.next().getKey().equals(entryKey)) { iter.remove(); return; } } }
java
{ "resource": "" }
q13291
LengthOperation.getLengthOfObject
train
private Object getLengthOfObject(Object object, String functionName) throws TransformationOperationException { try { Method method = object.getClass().getMethod(functionName); return method.invoke(object); } catch (NoSuchMethodException e) { StringBuilder builder = new StringBuilder(); builder.append("The type of the given field for the length step doesn't support "); builder.append(functionName).append(" method. So 0 will be used as standard value."); throw new TransformationOperationException(builder.toString(), e); } catch (IllegalArgumentException e) { throw new TransformationOperationException("Can't get length of the source field", e); } catch (IllegalAccessException e) { throw new TransformationOperationException("Can't get length of the source field", e); } catch (InvocationTargetException e) { throw new TransformationOperationException("Can't get length of the source field", e); } }
java
{ "resource": "" }
q13292
InMemoryRepository.read_
train
private <T> T read_(Class<T> clazz, Object id) { Map<String, Object> objects = objects(clazz); return (T) objects.get(id.toString()); }
java
{ "resource": "" }
q13293
LdapDao.deleteSubtreeExcludingRoot
train
public void deleteSubtreeExcludingRoot(Dn root) throws NoSuchNodeException, MissingParentException { existsCheck(root); try { EntryCursor entryCursor = connection.search(root, "(objectclass=*)", SearchScope.ONELEVEL); while (entryCursor.next()) { deleteSubtreeIncludingRoot(entryCursor.get().getDn()); } } catch (Exception e) { throw new LdapDaoException(e); } }
java
{ "resource": "" }
q13294
LdapDao.exists
train
public boolean exists(Dn dn) { try { return connection.exists(dn); } catch (LdapException e) { throw new LdapDaoException(e); } }
java
{ "resource": "" }
q13295
DefaultQueryParser.createQueryRequest
train
private QueryRequest createQueryRequest(String[] elements) { QueryRequest request = QueryRequest.create(); for (String element : elements) { String[] parts = StringUtils.split(element, ":", 2); parts[0] = parts[0].replace("\\", "\\\\"); parts[1] = parts[1].replace("\\", "\\\\"); request.addParameter(parts[0], parts[1].substring(1, parts[1].length() - 1)); } return request; }
java
{ "resource": "" }
q13296
Sequence.allocateBlock
train
public SequenceGenerator.SequenceBlock allocateBlock(int blockSize) { final long l = this.last; SequenceGenerator.SequenceBlock block = new SequenceGenerator.SequenceBlock(l + 1, l + blockSize); this.last = l + blockSize; return block; }
java
{ "resource": "" }
q13297
Sequence.readExternal
train
public void readExternal(PofReader reader) throws IOException { name = reader.readString(0); last = reader.readLong(1); }
java
{ "resource": "" }
q13298
Sequence.writeExternal
train
public void writeExternal(PofWriter writer) throws IOException { writer.writeString(0, name); writer.writeLong(1, last); }
java
{ "resource": "" }
q13299
CompleteRootDerivedReasoner.getRootUnsatisfiableClasses
train
public Set<OWLClass> getRootUnsatisfiableClasses() throws ExplanationException { StructuralRootDerivedReasoner srd = new StructuralRootDerivedReasoner(manager, baseReasoner, reasonerFactory); Set<OWLClass> estimatedRoots = srd.getRootUnsatisfiableClasses(); cls2JustificationMap = new HashMap<OWLClass, Set<Explanation<OWLAxiom>>>(); Set<OWLAxiom> allAxioms = new HashSet<OWLAxiom>(); for (OWLOntology ont : baseReasoner.getRootOntology().getImportsClosure()) { allAxioms.addAll(ont.getLogicalAxioms()); } for (OWLClass cls : estimatedRoots) { cls2JustificationMap.put(cls, new HashSet<Explanation<OWLAxiom>>()); System.out.println("POTENTIAL ROOT: " + cls); } System.out.println("Finding real roots from " + estimatedRoots.size() + " estimated roots"); int done = 0; roots.addAll(estimatedRoots); for (final OWLClass estimatedRoot : estimatedRoots) { ExplanationGeneratorFactory<OWLAxiom> genFac = ExplanationManager.createExplanationGeneratorFactory(reasonerFactory); ExplanationGenerator<OWLAxiom> gen = genFac.createExplanationGenerator(allAxioms); OWLDataFactory df = manager.getOWLDataFactory(); Set<Explanation<OWLAxiom>> expls = gen.getExplanations(df.getOWLSubClassOfAxiom(estimatedRoot, df.getOWLNothing())); cls2JustificationMap.get(estimatedRoot).addAll(expls); done++; System.out.println("Done " + done); } for(OWLClass clsA : estimatedRoots) { for(OWLClass clsB : estimatedRoots) { if (!clsA.equals(clsB)) { Set<Explanation<OWLAxiom>> clsAExpls = cls2JustificationMap.get(clsA); Set<Explanation<OWLAxiom>> clsBExpls = cls2JustificationMap.get(clsB); boolean clsARootForClsB = false; boolean clsBRootForClsA = false; // Be careful of cyclic dependencies! for(Explanation<OWLAxiom> clsAExpl : clsAExpls) { for(Explanation<OWLAxiom> clsBExpl : clsBExpls) { if(isRootFor(clsAExpl, clsBExpl)) { // A is a root of B clsARootForClsB = true; // System.out.println(clsB + " --- depends ---> " + clsA); } else if(isRootFor(clsBExpl, clsAExpl)) { // B is a root of A clsBRootForClsA = true; // System.out.println(clsA + " --- depends ---> " + clsB); } } } if (!clsARootForClsB || !clsBRootForClsA) { if(clsARootForClsB) { roots.remove(clsB); } else if(clsBRootForClsA) { roots.remove(clsA); } } } } } return roots; }
java
{ "resource": "" }