method
stringlengths 13
441k
| clean_method
stringlengths 7
313k
| doc
stringlengths 17
17.3k
| comment
stringlengths 3
1.42k
| method_name
stringlengths 1
273
| extra
dict | imports
sequence | imports_info
stringlengths 19
34.8k
| cluster_imports_info
stringlengths 15
3.66k
| libraries
sequence | libraries_info
stringlengths 6
661
| id
int64 0
2.92M
|
---|---|---|---|---|---|---|---|---|---|---|---|
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory) throws IOException {
return getProtocolProxy(protocol, clientVersion, addr, ticket, conf,
factory, getRpcTimeout(conf), null);
} | static <T> ProtocolProxy<T> function(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory) throws IOException { return getProtocolProxy(protocol, clientVersion, addr, ticket, conf, factory, getRpcTimeout(conf), null); } | /**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param ticket user group information
* @param conf configuration to use
* @param factory socket factory
* @return the protocol proxy
* @throws IOException if the far end through a RemoteException
*/ | Get a protocol proxy that contains a proxy connection to a remote server and a set of methods that are supported by the server | getProtocolProxy | {
"repo_name": "lukmajercak/hadoop",
"path": "hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RPC.java",
"license": "apache-2.0",
"size": 38952
} | [
"java.io.IOException",
"java.net.InetSocketAddress",
"javax.net.SocketFactory",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.security.UserGroupInformation"
] | import java.io.IOException; import java.net.InetSocketAddress; import javax.net.SocketFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; | import java.io.*; import java.net.*; import javax.net.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.security.*; | [
"java.io",
"java.net",
"javax.net",
"org.apache.hadoop"
] | java.io; java.net; javax.net; org.apache.hadoop; | 2,026,682 |
void delete(CollaboratorGroup group) throws CSTransactionException;
| void delete(CollaboratorGroup group) throws CSTransactionException; | /**
* Delete a collaborator group.
*
* @param group the group to delete
* @throws CSTransactionException on CSM error
*/ | Delete a collaborator group | delete | {
"repo_name": "NCIP/caarray",
"path": "software/caarray-ejb.jar/src/main/java/gov/nih/nci/caarray/application/permissions/PermissionsManagementService.java",
"license": "bsd-3-clause",
"size": 4723
} | [
"gov.nih.nci.caarray.domain.permissions.CollaboratorGroup",
"gov.nih.nci.security.exceptions.CSTransactionException"
] | import gov.nih.nci.caarray.domain.permissions.CollaboratorGroup; import gov.nih.nci.security.exceptions.CSTransactionException; | import gov.nih.nci.caarray.domain.permissions.*; import gov.nih.nci.security.exceptions.*; | [
"gov.nih.nci"
] | gov.nih.nci; | 2,372,132 |
public CreateIndexRequest alias(Alias alias) {
this.aliases.add(alias);
return this;
} | CreateIndexRequest function(Alias alias) { this.aliases.add(alias); return this; } | /**
* Adds an alias that will be associated with the index when it gets created
*/ | Adds an alias that will be associated with the index when it gets created | alias | {
"repo_name": "Uiho/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java",
"license": "apache-2.0",
"size": 16893
} | [
"org.elasticsearch.action.admin.indices.alias.Alias"
] | import org.elasticsearch.action.admin.indices.alias.Alias; | import org.elasticsearch.action.admin.indices.alias.*; | [
"org.elasticsearch.action"
] | org.elasticsearch.action; | 918,017 |
public Map<String, Object> showEstadisticsCategory() {
Question preguntaMasDificil=questions.get(0);
Question preguntaMasFacil=questions.get(0);
Map<String, Object> preguntaFacilDificil= new HashMap<String,Object>();
for(Question q : questions)
{
if(q.getVecesAcertada()>preguntaMasFacil.getVecesAcertada())
preguntaMasFacil=q;
if(q.getVecesFallada()>preguntaMasDificil.getVecesFallada())
preguntaMasDificil=q;
}
preguntaFacilDificil.put("name", getName());
preguntaFacilDificil.put("preguntaFacil", preguntaMasFacil);
preguntaFacilDificil.put("preguntaDificil", preguntaMasDificil);
return preguntaFacilDificil;
}
| Map<String, Object> function() { Question preguntaMasDificil=questions.get(0); Question preguntaMasFacil=questions.get(0); Map<String, Object> preguntaFacilDificil= new HashMap<String,Object>(); for(Question q : questions) { if(q.getVecesAcertada()>preguntaMasFacil.getVecesAcertada()) preguntaMasFacil=q; if(q.getVecesFallada()>preguntaMasDificil.getVecesFallada()) preguntaMasDificil=q; } preguntaFacilDificil.put("name", getName()); preguntaFacilDificil.put(STR, preguntaMasFacil); preguntaFacilDificil.put(STR, preguntaMasDificil); return preguntaFacilDificil; } | /**
* Devuelve la pregunta mas facil y mas dificil de la categoria junto con su nombre
* @return
*/ | Devuelve la pregunta mas facil y mas dificil de la categoria junto con su nombre | showEstadisticsCategory | {
"repo_name": "Arquisoft/Trivial5a",
"path": "game/src/main/java/es/uniovi/asw/model/Category.java",
"license": "gpl-2.0",
"size": 3427
} | [
"java.util.HashMap",
"java.util.Map"
] | import java.util.HashMap; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 712,987 |
course = DataHelper.createBasicCourse();
user = DataHelper.createBasicGlobalLecturer();
Lecturer lecturer = DataHelper.createLecturerWith(course, user);
privilegedUser = DataHelper.createPrivUserWith(course, user);
sessionMap = new HashMap<>();
sessionMap.put(Constants.SESSION_MAP_KEY_USER, user);
exam = new Exam();
exam.setExamId(DataHelper.EXAM_ID);
exam.setExamId((long)1);
exam.setName("Test Exam");
exam.setShortcut("TE");
exam.setCourse(course);
exam.setGradeType(GradeType.Percent.getId());
exam.setDeadline(new Date());
exam.setWithAttendance(true);
exam.setDeadline(DateUtil.tenYearsLater());
course.getExams().add(exam);
event = new ExamEvent();
examEventController = new ExamEventController();
// Mocking dependencies
courseServiceMock = MockHelper.mockCourseService(course);
examEventController.setCourseService(courseServiceMock);
examServiceMock = Mockito.mock(ExamService.class);
when(examServiceMock.findExamById(DataHelper.EXAM_ID_STR))
.thenReturn(exam);
when(examServiceMock.update(exam)).thenReturn(exam);
examEventController.setExamService(examServiceMock);
logServiceMock = Mockito.mock(LogService.class);
examEventController.setLogService(logServiceMock);
studentServiceMock = MockHelper.mockStudentService();
examEventController.setStudentService(studentServiceMock);
examEventServiceMock = Mockito.mock(ExamEventService.class);
when(examEventServiceMock.persist(event)).thenReturn(event);
when(examEventServiceMock.update(event)).thenReturn(event);
examEventController.setExamEventService(examEventServiceMock);
privilegedUserService = Mockito.mock(PrivilegedUserService.class);
when(privilegedUserService.update(privilegedUser)).thenReturn(privilegedUser);
examEventController.setPrivilegedUserService(privilegedUserService);
userServiceMock = MockHelper.mockUserService();
when(userServiceMock.hasCourseRole(user, Role.LECTURER, course))
.thenReturn(true);
examEventController.setUserService(userServiceMock);
contextMock = ContextMocker.mockBasicFacesContext();
contextMock = MockHelper.addViewRootMock(contextMock);
contextMock = MockHelper.addExternalContextMock(contextMock, sessionMap);
uiComponentMock = Mockito.mock(UIComponent.class);
examEventController.init();
} | course = DataHelper.createBasicCourse(); user = DataHelper.createBasicGlobalLecturer(); Lecturer lecturer = DataHelper.createLecturerWith(course, user); privilegedUser = DataHelper.createPrivUserWith(course, user); sessionMap = new HashMap<>(); sessionMap.put(Constants.SESSION_MAP_KEY_USER, user); exam = new Exam(); exam.setExamId(DataHelper.EXAM_ID); exam.setExamId((long)1); exam.setName(STR); exam.setShortcut("TE"); exam.setCourse(course); exam.setGradeType(GradeType.Percent.getId()); exam.setDeadline(new Date()); exam.setWithAttendance(true); exam.setDeadline(DateUtil.tenYearsLater()); course.getExams().add(exam); event = new ExamEvent(); examEventController = new ExamEventController(); courseServiceMock = MockHelper.mockCourseService(course); examEventController.setCourseService(courseServiceMock); examServiceMock = Mockito.mock(ExamService.class); when(examServiceMock.findExamById(DataHelper.EXAM_ID_STR)) .thenReturn(exam); when(examServiceMock.update(exam)).thenReturn(exam); examEventController.setExamService(examServiceMock); logServiceMock = Mockito.mock(LogService.class); examEventController.setLogService(logServiceMock); studentServiceMock = MockHelper.mockStudentService(); examEventController.setStudentService(studentServiceMock); examEventServiceMock = Mockito.mock(ExamEventService.class); when(examEventServiceMock.persist(event)).thenReturn(event); when(examEventServiceMock.update(event)).thenReturn(event); examEventController.setExamEventService(examEventServiceMock); privilegedUserService = Mockito.mock(PrivilegedUserService.class); when(privilegedUserService.update(privilegedUser)).thenReturn(privilegedUser); examEventController.setPrivilegedUserService(privilegedUserService); userServiceMock = MockHelper.mockUserService(); when(userServiceMock.hasCourseRole(user, Role.LECTURER, course)) .thenReturn(true); examEventController.setUserService(userServiceMock); contextMock = ContextMocker.mockBasicFacesContext(); contextMock = MockHelper.addViewRootMock(contextMock); contextMock = MockHelper.addExternalContextMock(contextMock, sessionMap); uiComponentMock = Mockito.mock(UIComponent.class); examEventController.init(); } | /**
* Sets up all test classes in mocks.
* Injects the mocks in the TutorialEventController.
*/ | Sets up all test classes in mocks. Injects the mocks in the TutorialEventController | init | {
"repo_name": "stefanoberdoerfer/exmatrikulator",
"path": "src/test/java/de/unibremen/opensores/controller/ExamEventControllerTest.java",
"license": "agpl-3.0",
"size": 14227
} | [
"de.unibremen.opensores.controller.settings.ExamEventController",
"de.unibremen.opensores.model.Exam",
"de.unibremen.opensores.model.ExamEvent",
"de.unibremen.opensores.model.GradeType",
"de.unibremen.opensores.model.Lecturer",
"de.unibremen.opensores.model.Role",
"de.unibremen.opensores.service.ExamEventService",
"de.unibremen.opensores.service.ExamService",
"de.unibremen.opensores.service.LogService",
"de.unibremen.opensores.service.PrivilegedUserService",
"de.unibremen.opensores.testutil.ContextMocker",
"de.unibremen.opensores.testutil.DataHelper",
"de.unibremen.opensores.testutil.MockHelper",
"de.unibremen.opensores.util.Constants",
"de.unibremen.opensores.util.DateUtil",
"java.util.Date",
"java.util.HashMap",
"javax.faces.component.UIComponent",
"org.mockito.Mockito"
] | import de.unibremen.opensores.controller.settings.ExamEventController; import de.unibremen.opensores.model.Exam; import de.unibremen.opensores.model.ExamEvent; import de.unibremen.opensores.model.GradeType; import de.unibremen.opensores.model.Lecturer; import de.unibremen.opensores.model.Role; import de.unibremen.opensores.service.ExamEventService; import de.unibremen.opensores.service.ExamService; import de.unibremen.opensores.service.LogService; import de.unibremen.opensores.service.PrivilegedUserService; import de.unibremen.opensores.testutil.ContextMocker; import de.unibremen.opensores.testutil.DataHelper; import de.unibremen.opensores.testutil.MockHelper; import de.unibremen.opensores.util.Constants; import de.unibremen.opensores.util.DateUtil; import java.util.Date; import java.util.HashMap; import javax.faces.component.UIComponent; import org.mockito.Mockito; | import de.unibremen.opensores.controller.settings.*; import de.unibremen.opensores.model.*; import de.unibremen.opensores.service.*; import de.unibremen.opensores.testutil.*; import de.unibremen.opensores.util.*; import java.util.*; import javax.faces.component.*; import org.mockito.*; | [
"de.unibremen.opensores",
"java.util",
"javax.faces",
"org.mockito"
] | de.unibremen.opensores; java.util; javax.faces; org.mockito; | 121,406 |
public static void write(final CharSequence data, final Writer output) throws IOException {
if (data != null) {
write(data.toString(), output);
}
}
/**
* Writes chars from a <code>CharSequence</code> to bytes on an
* <code>OutputStream</code> using the default character encoding of the
* platform.
* <p>
* This method uses {@link String#getBytes()}.
*
* @param data the <code>CharSequence</code> to write, null ignored
* @param output the <code>OutputStream</code> to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.0
* @deprecated 2.5 use {@link #write(CharSequence, OutputStream, Charset)}
| static void function(final CharSequence data, final Writer output) throws IOException { if (data != null) { write(data.toString(), output); } } /** * Writes chars from a <code>CharSequence</code> to bytes on an * <code>OutputStream</code> using the default character encoding of the * platform. * <p> * This method uses {@link String#getBytes()}. * * @param data the <code>CharSequence</code> to write, null ignored * @param output the <code>OutputStream</code> to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 2.0 * @deprecated 2.5 use {@link #write(CharSequence, OutputStream, Charset)} | /**
* Writes chars from a <code>CharSequence</code> to a <code>Writer</code>.
*
* @param data the <code>CharSequence</code> to write, null ignored
* @param output the <code>Writer</code> to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.0
*/ | Writes chars from a <code>CharSequence</code> to a <code>Writer</code> | write | {
"repo_name": "ecd-plugin/ecd",
"path": "org.sf.feeling.decompiler/src/org/sf/feeling/decompiler/util/IOUtils.java",
"license": "epl-1.0",
"size": 55283
} | [
"java.io.IOException",
"java.io.OutputStream",
"java.io.Writer",
"java.nio.charset.Charset"
] | import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; | import java.io.*; import java.nio.charset.*; | [
"java.io",
"java.nio"
] | java.io; java.nio; | 2,838,096 |
static ThreadPoolBulkheadRegistry of(ThreadPoolBulkheadConfig bulkheadConfig,
List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers) {
return new InMemoryThreadPoolBulkheadRegistry(bulkheadConfig, registryEventConsumers);
} | static ThreadPoolBulkheadRegistry of(ThreadPoolBulkheadConfig bulkheadConfig, List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers) { return new InMemoryThreadPoolBulkheadRegistry(bulkheadConfig, registryEventConsumers); } | /**
* Creates a ThreadPoolBulkheadRegistry with a custom default ThreadPoolBulkhead configuration
* and a list of ThreadPoolBulkhead registry event consumers.
*
* @param bulkheadConfig a custom default ThreadPoolBulkhead configuration.
* @param registryEventConsumers a list of ThreadPoolBulkhead registry event consumers.
* @return a ThreadPoolBulkheadRegistry with a custom ThreadPoolBulkhead configuration and a
* list of ThreadPoolBulkhead registry event consumers.
*/ | Creates a ThreadPoolBulkheadRegistry with a custom default ThreadPoolBulkhead configuration and a list of ThreadPoolBulkhead registry event consumers | of | {
"repo_name": "drmaas/resilience4j",
"path": "resilience4j-bulkhead/src/main/java/io/github/resilience4j/bulkhead/ThreadPoolBulkheadRegistry.java",
"license": "apache-2.0",
"size": 13374
} | [
"io.github.resilience4j.bulkhead.internal.InMemoryThreadPoolBulkheadRegistry",
"io.github.resilience4j.core.registry.RegistryEventConsumer",
"java.util.List"
] | import io.github.resilience4j.bulkhead.internal.InMemoryThreadPoolBulkheadRegistry; import io.github.resilience4j.core.registry.RegistryEventConsumer; import java.util.List; | import io.github.resilience4j.bulkhead.internal.*; import io.github.resilience4j.core.registry.*; import java.util.*; | [
"io.github.resilience4j",
"java.util"
] | io.github.resilience4j; java.util; | 1,995,084 |
public interface MapWithModificationListener<K,V> extends ConcurrentMap<K,V> {
public void modificationListenerAdd(MapListener<K, V> listener); | interface MapWithModificationListener<K,V> extends ConcurrentMap<K,V> { public void function(MapListener<K, V> listener); | /**
* Add new modification listener notified when Map has been updated
* @param listener callback interface notified when map changes
*/ | Add new modification listener notified when Map has been updated | modificationListenerAdd | {
"repo_name": "paulnguyen/data",
"path": "nosql/mapdb/src/main/java/org/mapdb/Bind.java",
"license": "apache-2.0",
"size": 30984
} | [
"java.util.concurrent.ConcurrentMap"
] | import java.util.concurrent.ConcurrentMap; | import java.util.concurrent.*; | [
"java.util"
] | java.util; | 6,296 |
private static int appendFormattedColumn(StringBuilder sb, String text,
int alignment) {
String paddedText = String.format("%-" + alignment + "s", text);
int delimCount = 0;
if (paddedText.length() < alignment + PRETTY_MAX_INTERCOL_SPACING) {
delimCount = (alignment + PRETTY_MAX_INTERCOL_SPACING)
- paddedText.length();
} else {
delimCount = PRETTY_MAX_INTERCOL_SPACING;
}
String delim = StringUtils.repeat(" ", delimCount);
sb.append(paddedText);
sb.append(delim);
sb.append(MetaDataFormatUtils.FIELD_DELIM);
return paddedText.length() + delim.length();
} | static int function(StringBuilder sb, String text, int alignment) { String paddedText = String.format("%-" + alignment + "s", text); int delimCount = 0; if (paddedText.length() < alignment + PRETTY_MAX_INTERCOL_SPACING) { delimCount = (alignment + PRETTY_MAX_INTERCOL_SPACING) - paddedText.length(); } else { delimCount = PRETTY_MAX_INTERCOL_SPACING; } String delim = StringUtils.repeat(" ", delimCount); sb.append(paddedText); sb.append(delim); sb.append(MetaDataFormatUtils.FIELD_DELIM); return paddedText.length() + delim.length(); } | /**
* Appends the specified text with alignment to sb.
* Also appends an appopriately sized delimiter.
* @return The number of columns consumed by the aligned string and the
* delimiter.
*/ | Appends the specified text with alignment to sb. Also appends an appopriately sized delimiter | appendFormattedColumn | {
"repo_name": "BUPTAnderson/apache-hive-2.1.1-src",
"path": "ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/MetaDataPrettyFormatUtils.java",
"license": "apache-2.0",
"size": 9960
} | [
"org.apache.commons.lang.StringUtils"
] | import org.apache.commons.lang.StringUtils; | import org.apache.commons.lang.*; | [
"org.apache.commons"
] | org.apache.commons; | 1,173,264 |
private void renameCheckpoint(long txid, NameNodeFile fromNnf,
NameNodeFile toNnf, boolean renameMD5) throws IOException {
ArrayList<StorageDirectory> al = null;
for (StorageDirectory sd : storage.dirIterable(NameNodeDirType.IMAGE)) {
try {
renameImageFileInDir(sd, fromNnf, toNnf, txid, renameMD5);
} catch (IOException ioe) {
LOG.warn("Unable to rename checkpoint in " + sd, ioe);
if (al == null) {
al = Lists.newArrayList();
}
al.add(sd);
}
}
if(al != null) storage.reportErrorsOnDirectories(al);
} | void function(long txid, NameNodeFile fromNnf, NameNodeFile toNnf, boolean renameMD5) throws IOException { ArrayList<StorageDirectory> al = null; for (StorageDirectory sd : storage.dirIterable(NameNodeDirType.IMAGE)) { try { renameImageFileInDir(sd, fromNnf, toNnf, txid, renameMD5); } catch (IOException ioe) { LOG.warn(STR + sd, ioe); if (al == null) { al = Lists.newArrayList(); } al.add(sd); } } if(al != null) storage.reportErrorsOnDirectories(al); } | /**
* Rename FSImage with the specific txid
*/ | Rename FSImage with the specific txid | renameCheckpoint | {
"repo_name": "oza/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSImage.java",
"license": "apache-2.0",
"size": 54078
} | [
"com.google.common.collect.Lists",
"java.io.IOException",
"java.util.ArrayList",
"org.apache.hadoop.hdfs.server.common.Storage",
"org.apache.hadoop.hdfs.server.namenode.NNStorage"
] | import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.namenode.NNStorage; | import com.google.common.collect.*; import java.io.*; import java.util.*; import org.apache.hadoop.hdfs.server.common.*; import org.apache.hadoop.hdfs.server.namenode.*; | [
"com.google.common",
"java.io",
"java.util",
"org.apache.hadoop"
] | com.google.common; java.io; java.util; org.apache.hadoop; | 205,298 |
public void revokePermission(String packageName, Permission permission) {
Preconditions.checkNotNull(packageName);
Preconditions.checkNotNull(permission);
if (System.getSecurityManager() != null) {
System.getSecurityManager().checkPermission(ModuleSecurityManager.UPDATE_ALLOWED_PERMISSIONS);
}
logger.debug("Revoking permission '{}' from '{}.*'", permission, packageName);
allowedPackagePermissionInstances.remove(permission, packageName);
Iterator<Class> iterator = allowedPermissionInstances.get(permission).iterator();
while (iterator.hasNext()) {
Class clazz = iterator.next();
if (packageName.equals(clazz.getPackage().getName())) {
iterator.remove();
}
}
} | void function(String packageName, Permission permission) { Preconditions.checkNotNull(packageName); Preconditions.checkNotNull(permission); if (System.getSecurityManager() != null) { System.getSecurityManager().checkPermission(ModuleSecurityManager.UPDATE_ALLOWED_PERMISSIONS); } logger.debug(STR, permission, packageName); allowedPackagePermissionInstances.remove(permission, packageName); Iterator<Class> iterator = allowedPermissionInstances.get(permission).iterator(); while (iterator.hasNext()) { Class clazz = iterator.next(); if (packageName.equals(clazz.getPackage().getName())) { iterator.remove(); } } } | /**
* Remove a permission that has previously been granted to a calls passing through a given package.
* This will also revoke permissions granted at a class level, for classes within the package
*
* @param packageName The package to revoke the permission from
* @param permission The permission to revoke
*/ | Remove a permission that has previously been granted to a calls passing through a given package. This will also revoke permissions granted at a class level, for classes within the package | revokePermission | {
"repo_name": "immortius/gestalt-module",
"path": "src/main/java/org/terasology/module/sandbox/PermissionSet.java",
"license": "apache-2.0",
"size": 15179
} | [
"com.google.common.base.Preconditions",
"java.security.Permission",
"java.util.Iterator"
] | import com.google.common.base.Preconditions; import java.security.Permission; import java.util.Iterator; | import com.google.common.base.*; import java.security.*; import java.util.*; | [
"com.google.common",
"java.security",
"java.util"
] | com.google.common; java.security; java.util; | 152,846 |
List<IntegerStringBean> historyFields = new LinkedList<IntegerStringBean>();
//all fields with explicit history
Map<Integer, String> historyFieldLabelsMap = FieldConfigBL.loadAllWithExplicitHistory(locale);
for (Map.Entry<Integer, String> historyFieldEntry : historyFieldLabelsMap.entrySet()) {
historyFields.add(new IntegerStringBean(historyFieldEntry.getValue(), historyFieldEntry.getKey()));
}
//compound fields (string value concatenated of all fields without explicit history)
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMON_FIELD_KEY, locale), TFieldChangeBean.COMPOUND_HISTORY_FIELD));
//attachment changes
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_ADDED_FIELD_KEY, locale), SystemFields.ATTACHMENT_ADD_HISTORY_FIELD));
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_MODIFIED_FIELD_KEY, locale), SystemFields.ATTACHMENT_MODIFY_HISTORY_FIELD));
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_DELETED_FIELD_KEY, locale), SystemFields.ATTACHMENT_DELETE_HISTORY_FIELD));
//comment changes
if (historyFieldLabelsMap.containsKey(SystemFields.INTEGER_COMMENT)) {
//comment is historized
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMENT_MODIFIED_FIELD_KEY, locale), SystemFields.COMMENT_MODIFY_HISTORY_FIELD));
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMENT_DELETED_FIELD_KEY, locale), SystemFields.COMMENT_DELETE_HISTORY_FIELD));
} else {
//comment is not historized but that means that modification and delete of comments is not historized. Adding a comment should always appear in history
TFieldConfigBean fieldConfigBean = FieldRuntimeBL.getDefaultFieldConfig(SystemFields.INTEGER_COMMENT, locale);
historyFields.add(new IntegerStringBean(fieldConfigBean.getLabel(), SystemFields.INTEGER_COMMENT));
}
List<TProjectTypeBean> projectBeans = ProjectTypesBL.loadAll();
boolean planBudgetExpense = false;
boolean versionControl = false;
if (projectBeans!=null) {
for (TProjectTypeBean projectTypeBean : projectBeans) {
if (projectTypeBean.getUseAccounting()) {
planBudgetExpense = true;
}
if (projectTypeBean.getUseVersionControl()) {
versionControl = true;
}
if (planBudgetExpense && versionControl) {
break;
}
}
}
if (!ApplicationBean.getInstance().isGenji() && planBudgetExpense) {
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COST, locale), SystemFields.INTEGER_COST_HISTORY));
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.PLAN, locale), SystemFields.INTEGER_PLAN_HISTORY));
if (ApplicationBean.getInstance().getSiteBean().getSummaryItemsBehavior()) {
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.BUDGET, locale), SystemFields.INTEGER_BUDGET_HISTORY));
}
}
if (versionControl) {
historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.VERSION_CONTROL, locale), SystemFields.INTEGER_VERSION_CONTROL));
}
Collections.sort(historyFields);
return historyFields;
}
| List<IntegerStringBean> historyFields = new LinkedList<IntegerStringBean>(); Map<Integer, String> historyFieldLabelsMap = FieldConfigBL.loadAllWithExplicitHistory(locale); for (Map.Entry<Integer, String> historyFieldEntry : historyFieldLabelsMap.entrySet()) { historyFields.add(new IntegerStringBean(historyFieldEntry.getValue(), historyFieldEntry.getKey())); } historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMON_FIELD_KEY, locale), TFieldChangeBean.COMPOUND_HISTORY_FIELD)); historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_ADDED_FIELD_KEY, locale), SystemFields.ATTACHMENT_ADD_HISTORY_FIELD)); historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_MODIFIED_FIELD_KEY, locale), SystemFields.ATTACHMENT_MODIFY_HISTORY_FIELD)); historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.ATTACHMENT_DELETED_FIELD_KEY, locale), SystemFields.ATTACHMENT_DELETE_HISTORY_FIELD)); if (historyFieldLabelsMap.containsKey(SystemFields.INTEGER_COMMENT)) { historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMENT_MODIFIED_FIELD_KEY, locale), SystemFields.COMMENT_MODIFY_HISTORY_FIELD)); historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COMMENT_DELETED_FIELD_KEY, locale), SystemFields.COMMENT_DELETE_HISTORY_FIELD)); } else { TFieldConfigBean fieldConfigBean = FieldRuntimeBL.getDefaultFieldConfig(SystemFields.INTEGER_COMMENT, locale); historyFields.add(new IntegerStringBean(fieldConfigBean.getLabel(), SystemFields.INTEGER_COMMENT)); } List<TProjectTypeBean> projectBeans = ProjectTypesBL.loadAll(); boolean planBudgetExpense = false; boolean versionControl = false; if (projectBeans!=null) { for (TProjectTypeBean projectTypeBean : projectBeans) { if (projectTypeBean.getUseAccounting()) { planBudgetExpense = true; } if (projectTypeBean.getUseVersionControl()) { versionControl = true; } if (planBudgetExpense && versionControl) { break; } } } if (!ApplicationBean.getInstance().isGenji() && planBudgetExpense) { historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.COST, locale), SystemFields.INTEGER_COST_HISTORY)); historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.PLAN, locale), SystemFields.INTEGER_PLAN_HISTORY)); if (ApplicationBean.getInstance().getSiteBean().getSummaryItemsBehavior()) { historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.BUDGET, locale), SystemFields.INTEGER_BUDGET_HISTORY)); } } if (versionControl) { historyFields.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(HistoryLoaderBL.VERSION_CONTROL, locale), SystemFields.INTEGER_VERSION_CONTROL)); } Collections.sort(historyFields); return historyFields; } | /**
* Gets the possible change types
* @param locale
* @return
*/ | Gets the possible change types | getPossibleHistoryFields | {
"repo_name": "trackplus/Genji",
"path": "src/main/java/com/aurel/track/item/history/HistoryLoaderBL.java",
"license": "gpl-3.0",
"size": 65673
} | [
"com.aurel.track.admin.customize.projectType.ProjectTypesBL",
"com.aurel.track.admin.customize.treeConfig.field.FieldConfigBL",
"com.aurel.track.beans.TFieldChangeBean",
"com.aurel.track.beans.TFieldConfigBean",
"com.aurel.track.beans.TProjectTypeBean",
"com.aurel.track.fieldType.constants.SystemFields",
"com.aurel.track.fieldType.runtime.bl.FieldRuntimeBL",
"com.aurel.track.prop.ApplicationBean",
"com.aurel.track.resources.LocalizeUtil",
"com.aurel.track.util.IntegerStringBean",
"java.util.Collections",
"java.util.LinkedList",
"java.util.List",
"java.util.Map"
] | import com.aurel.track.admin.customize.projectType.ProjectTypesBL; import com.aurel.track.admin.customize.treeConfig.field.FieldConfigBL; import com.aurel.track.beans.TFieldChangeBean; import com.aurel.track.beans.TFieldConfigBean; import com.aurel.track.beans.TProjectTypeBean; import com.aurel.track.fieldType.constants.SystemFields; import com.aurel.track.fieldType.runtime.bl.FieldRuntimeBL; import com.aurel.track.prop.ApplicationBean; import com.aurel.track.resources.LocalizeUtil; import com.aurel.track.util.IntegerStringBean; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; | import com.aurel.track.*; import com.aurel.track.admin.customize.*; import com.aurel.track.beans.*; import com.aurel.track.prop.*; import com.aurel.track.resources.*; import com.aurel.track.util.*; import java.util.*; | [
"com.aurel.track",
"java.util"
] | com.aurel.track; java.util; | 2,252,061 |
MultiTree getMultiTree(Identifier htmlPage, Identifier container, Identifier childContent, String containerInstance)
throws DotDataException; | MultiTree getMultiTree(Identifier htmlPage, Identifier container, Identifier childContent, String containerInstance) throws DotDataException; | /**
* Gets a specific MultiTree entry
*
* @param htmlPage
* @param container
* @param childContent
* @param containerInstance
* @return
* @throws DotDataException
*/ | Gets a specific MultiTree entry | getMultiTree | {
"repo_name": "dotCMS/core",
"path": "dotCMS/src/main/java/com/dotmarketing/factories/MultiTreeAPI.java",
"license": "gpl-3.0",
"size": 13500
} | [
"com.dotmarketing.beans.Identifier",
"com.dotmarketing.beans.MultiTree",
"com.dotmarketing.exception.DotDataException"
] | import com.dotmarketing.beans.Identifier; import com.dotmarketing.beans.MultiTree; import com.dotmarketing.exception.DotDataException; | import com.dotmarketing.beans.*; import com.dotmarketing.exception.*; | [
"com.dotmarketing.beans",
"com.dotmarketing.exception"
] | com.dotmarketing.beans; com.dotmarketing.exception; | 1,726,851 |
@Override
public String toString() {
return getClass().getName() + "[color=" + color + (italic ? ",italic" : "") + (bold ? ",bold" : "") + "]";
}
// private members
private Color color;
private boolean italic;
private boolean bold;
private Font lastFont;
private Font lastStyledFont;
private FontMetrics fontMetrics;
| String function() { return getClass().getName() + STR + color + (italic ? STR : STR,boldSTRSTR]"; } private Color color; private boolean italic; private boolean bold; private Font lastFont; private Font lastStyledFont; private FontMetrics fontMetrics; | /**
* Returns a string representation of this object.
*/ | Returns a string representation of this object | toString | {
"repo_name": "aborg0/rapidminer-studio",
"path": "src/main/java/com/rapidminer/gui/tools/syntax/SyntaxStyle.java",
"license": "agpl-3.0",
"size": 4287
} | [
"java.awt.Color",
"java.awt.Font",
"java.awt.FontMetrics"
] | import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; | import java.awt.*; | [
"java.awt"
] | java.awt; | 2,473,002 |
@Named("addRecordToRRPool")
@POST
@XMLResponseParser(ElementTextHandler.Guid.class)
@Payload("<v01:addRecordToRRPool><transactionID /><roundRobinRecord lbPoolID=\"{lbPoolID}\" info1Value=\"{address}\" ZoneName=\"{zoneName}\" Type=\"1\" TTL=\"{ttl}\"/></v01:addRecordToRRPool>")
String addARecordWithAddressAndTTL(@PayloadParam("lbPoolID") String lbPoolID,
@PayloadParam("address") String ipv4Address, @PayloadParam("ttl") int ttl)
throws ResourceAlreadyExistsException;
/**
* updates an existing A or AAAA record in the pool.
*
* @param lbPoolID
* the pool to add the record to.
* @param guid
* the global unique identifier for the resource record {@see
* ResourceRecordMetadata#getGuid()} | @Named(STR) @XMLResponseParser(ElementTextHandler.Guid.class) @Payload(STR{lbPoolID}\STR{address}\STR{zoneName}\STR1\STR{ttl}\STR) String addARecordWithAddressAndTTL(@PayloadParam(STR) String lbPoolID, @PayloadParam(STR) String ipv4Address, @PayloadParam("ttl") int ttl) throws ResourceAlreadyExistsException; /** * updates an existing A or AAAA record in the pool. * * @param lbPoolID * the pool to add the record to. * @param guid * the global unique identifier for the resource record { * ResourceRecordMetadata#getGuid()} | /**
* adds a new {@code A} record to the pool
*
* @param lbPoolID
* the pool to add the record to.
* @param ipv4Address
* the ipv4 address
* @param ttl
* the {@link ResourceRecord#getTTL ttl} of the record
* @return the {@code guid} of the new record
* @throws ResourceAlreadyExistsException
* if a record already exists with the same attrs
*/ | adds a new A record to the pool | addARecordWithAddressAndTTL | {
"repo_name": "yanzhijun/jclouds-aliyun",
"path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/RoundRobinPoolApi.java",
"license": "apache-2.0",
"size": 7981
} | [
"javax.inject.Named",
"org.jclouds.rest.annotations.Payload",
"org.jclouds.rest.annotations.PayloadParam",
"org.jclouds.rest.annotations.XMLResponseParser",
"org.jclouds.ultradns.ws.UltraDNSWSExceptions",
"org.jclouds.ultradns.ws.xml.ElementTextHandler"
] | import javax.inject.Named; import org.jclouds.rest.annotations.Payload; import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.ultradns.ws.UltraDNSWSExceptions; import org.jclouds.ultradns.ws.xml.ElementTextHandler; | import javax.inject.*; import org.jclouds.rest.annotations.*; import org.jclouds.ultradns.ws.*; import org.jclouds.ultradns.ws.xml.*; | [
"javax.inject",
"org.jclouds.rest",
"org.jclouds.ultradns"
] | javax.inject; org.jclouds.rest; org.jclouds.ultradns; | 1,938,652 |
public IgniteModel<O1, O2> secondModel() {
return mdl2;
} | IgniteModel<O1, O2> function() { return mdl2; } | /**
* Get second model.
*
* @return Second model.
*/ | Get second model | secondModel | {
"repo_name": "ilantukh/ignite",
"path": "modules/ml/src/main/java/org/apache/ignite/ml/composition/combinators/sequential/ModelsSequentialComposition.java",
"license": "apache-2.0",
"size": 3300
} | [
"org.apache.ignite.ml.IgniteModel"
] | import org.apache.ignite.ml.IgniteModel; | import org.apache.ignite.ml.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 224,571 |
public Map<String, Object> getValues() {
return values;
} | Map<String, Object> function() { return values; } | /**
* Gets the values.
* @return the values
*/ | Gets the values | getValues | {
"repo_name": "rajeev3001/analytics-apim",
"path": "product/integration/tests-common/integration-test-utils/src/main/java/org/wso2/analytics/apim/analytics/rest/beans/RecordBean.java",
"license": "apache-2.0",
"size": 3179
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,566,397 |
public RowExpression rewriteExpression(RowExpression expression, Predicate<VariableReferenceExpression> variableScope)
{
checkArgument(determinismEvaluator.isDeterministic(expression), "Only deterministic expressions may be considered for rewrite");
return rewriteExpression(expression, variableScope, true);
} | RowExpression function(RowExpression expression, Predicate<VariableReferenceExpression> variableScope) { checkArgument(determinismEvaluator.isDeterministic(expression), STR); return rewriteExpression(expression, variableScope, true); } | /**
* Attempts to rewrite an RowExpression in terms of the symbols allowed by the symbol scope
* given the known equalities. Returns null if unsuccessful.
* This method checks if rewritten expression is non-deterministic.
*/ | Attempts to rewrite an RowExpression in terms of the symbols allowed by the symbol scope given the known equalities. Returns null if unsuccessful. This method checks if rewritten expression is non-deterministic | rewriteExpression | {
"repo_name": "prestodb/presto",
"path": "presto-main/src/main/java/com/facebook/presto/sql/planner/EqualityInference.java",
"license": "apache-2.0",
"size": 24022
} | [
"com.facebook.presto.spi.relation.RowExpression",
"com.facebook.presto.spi.relation.VariableReferenceExpression",
"com.google.common.base.Preconditions",
"com.google.common.base.Predicate"
] | import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; | import com.facebook.presto.spi.relation.*; import com.google.common.base.*; | [
"com.facebook.presto",
"com.google.common"
] | com.facebook.presto; com.google.common; | 2,090,961 |
public static void plusAssign(Matrix res, double v) {
int M = res.getRowDimension();
int N = res.getColumnDimension();
if (res instanceof SparseMatrix) {
} else if (res instanceof DenseMatrix) {
double[][] resData = ((DenseMatrix) res).getData();
double[] resRow = null;
for (int i = 0; i < M; i++) {
resRow = resData[i];
for (int j = 0; j < N; j++) {
resRow[j] += v;
}
}
}
} | static void function(Matrix res, double v) { int M = res.getRowDimension(); int N = res.getColumnDimension(); if (res instanceof SparseMatrix) { } else if (res instanceof DenseMatrix) { double[][] resData = ((DenseMatrix) res).getData(); double[] resRow = null; for (int i = 0; i < M; i++) { resRow = resData[i]; for (int j = 0; j < N; j++) { resRow[j] += v; } } } } | /**
* res = res + v
* @param res
* @param v
*/ | res = res + v | plusAssign | {
"repo_name": "MingjieQian/LAML",
"path": "src/ml/utils/InPlaceOperator.java",
"license": "apache-2.0",
"size": 114698
} | [
"la.matrix.DenseMatrix",
"la.matrix.Matrix",
"la.matrix.SparseMatrix"
] | import la.matrix.DenseMatrix; import la.matrix.Matrix; import la.matrix.SparseMatrix; | import la.matrix.*; | [
"la.matrix"
] | la.matrix; | 2,231,050 |
public Object getValue(boolean preferCD) throws ForceReattemptException {
final GetReplyMessage reply = this.getReply;
try {
if (reply != null) {
switch (reply.valueType) {
case GetReplyMessage.VALUE_IS_BYTES:
return reply.valueInBytes;
case GetReplyMessage.VALUE_IS_INVALID:
return Token.INVALID;
case GetReplyMessage.VALUE_IS_TOMBSTONE:
return Token.TOMBSTONE;
default:
if (reply.valueInBytes != null) {
if (preferCD) {
return CachedDeserializableFactory.create(reply.valueInBytes,
getDistributionManager().getCache());
} else {
return BlobHelper.deserializeBlob(reply.valueInBytes, reply.remoteVersion, null);
}
} else {
return null;
}
}
}
return null;
} catch (IOException e) {
throw new ForceReattemptException(
LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_IOEXCEPTION.toLocalizedString(),
e);
} catch (ClassNotFoundException e) {
throw new ForceReattemptException(
LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_CLASSNOTFOUNDEXCEPTION
.toLocalizedString(),
e);
}
} | Object function(boolean preferCD) throws ForceReattemptException { final GetReplyMessage reply = this.getReply; try { if (reply != null) { switch (reply.valueType) { case GetReplyMessage.VALUE_IS_BYTES: return reply.valueInBytes; case GetReplyMessage.VALUE_IS_INVALID: return Token.INVALID; case GetReplyMessage.VALUE_IS_TOMBSTONE: return Token.TOMBSTONE; default: if (reply.valueInBytes != null) { if (preferCD) { return CachedDeserializableFactory.create(reply.valueInBytes, getDistributionManager().getCache()); } else { return BlobHelper.deserializeBlob(reply.valueInBytes, reply.remoteVersion, null); } } else { return null; } } } return null; } catch (IOException e) { throw new ForceReattemptException( LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_IOEXCEPTION.toLocalizedString(), e); } catch (ClassNotFoundException e) { throw new ForceReattemptException( LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_CLASSNOTFOUNDEXCEPTION .toLocalizedString(), e); } } | /**
* De-seralize the value, if the value isn't already a byte array, this method should be called
* in the context of the requesting thread for the best scalability
*
* @param preferCD
* @see EntryEventImpl#deserialize(byte[])
* @return the value object
*/ | De-seralize the value, if the value isn't already a byte array, this method should be called in the context of the requesting thread for the best scalability | getValue | {
"repo_name": "smanvi-pivotal/geode",
"path": "geode-core/src/main/java/org/apache/geode/internal/cache/partitioned/GetMessage.java",
"license": "apache-2.0",
"size": 23154
} | [
"java.io.IOException",
"org.apache.geode.internal.cache.CachedDeserializableFactory",
"org.apache.geode.internal.cache.ForceReattemptException",
"org.apache.geode.internal.cache.Token",
"org.apache.geode.internal.i18n.LocalizedStrings",
"org.apache.geode.internal.util.BlobHelper"
] | import java.io.IOException; import org.apache.geode.internal.cache.CachedDeserializableFactory; import org.apache.geode.internal.cache.ForceReattemptException; import org.apache.geode.internal.cache.Token; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.util.BlobHelper; | import java.io.*; import org.apache.geode.internal.cache.*; import org.apache.geode.internal.i18n.*; import org.apache.geode.internal.util.*; | [
"java.io",
"org.apache.geode"
] | java.io; org.apache.geode; | 2,852,705 |
private String render_sections(String template, Map<String, String> context) {
while (true) {
Matcher match = sSection_re.matcher(template);
if (!match.find()) {
break;
}
String section = match.group(0);
String section_name = match.group(1);
String inner = match.group(2);
section_name = section_name.trim();
String it;
// check for cloze
Matcher m = fClozeSection.matcher(section_name);
if (m.find()) {
// get full field text
String txt = get_or_attr(context, m.group(2), null);
Matcher mm = Pattern.compile(String.format(clozeReg, m.group(1))).matcher(txt);
if (mm.find()) {
it = mm.group(1);
} else {
it = null;
}
} else {
it = get_or_attr(context, section_name, null);
}
String replacer = "";
if (!TextUtils.isEmpty(it)) {
it = Utils.stripHTMLMedia(it).trim();
}
if (!TextUtils.isEmpty(it)) {
if (section.charAt(2) != '^') {
replacer = inner;
}
} else if (TextUtils.isEmpty(it) && section.charAt(2) == '^') {
replacer = inner;
}
template = template.replace(section, replacer);
}
return template;
} | String function(String template, Map<String, String> context) { while (true) { Matcher match = sSection_re.matcher(template); if (!match.find()) { break; } String section = match.group(0); String section_name = match.group(1); String inner = match.group(2); section_name = section_name.trim(); String it; Matcher m = fClozeSection.matcher(section_name); if (m.find()) { String txt = get_or_attr(context, m.group(2), null); Matcher mm = Pattern.compile(String.format(clozeReg, m.group(1))).matcher(txt); if (mm.find()) { it = mm.group(1); } else { it = null; } } else { it = get_or_attr(context, section_name, null); } String replacer = ""; if (!TextUtils.isEmpty(it)) { it = Utils.stripHTMLMedia(it).trim(); } if (!TextUtils.isEmpty(it)) { if (section.charAt(2) != '^') { replacer = inner; } } else if (TextUtils.isEmpty(it) && section.charAt(2) == '^') { replacer = inner; } template = template.replace(section, replacer); } return template; } | /**
* Expands sections.
*/ | Expands sections | render_sections | {
"repo_name": "gef756/Anki-Android",
"path": "AnkiDroid/src/main/java/com/ichi2/libanki/template/Template.java",
"license": "gpl-3.0",
"size": 12350
} | [
"android.text.TextUtils",
"com.ichi2.libanki.Utils",
"java.util.Map",
"java.util.regex.Matcher",
"java.util.regex.Pattern"
] | import android.text.TextUtils; import com.ichi2.libanki.Utils; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; | import android.text.*; import com.ichi2.libanki.*; import java.util.*; import java.util.regex.*; | [
"android.text",
"com.ichi2.libanki",
"java.util"
] | android.text; com.ichi2.libanki; java.util; | 460,545 |
private void fillInCQRoutingInfo(CacheEvent event, boolean processLocalProfile,
Profile[] peerProfiles, FilterRoutingInfo frInfo) {
CqService cqService = getCqService(event.getRegion());
if (cqService != null) {
try {
Profile local = processLocalProfile ? this.localProfile : null;
cqService.processEvents(event, local, peerProfiles, frInfo);
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
// If this ever returns, re-throw the error. We're poisoned
// now, so don't let this thread continue.
throw err;
} catch (Throwable t) {
SystemFailure.checkFailure();
logger.error(LocalizedMessage.create(
LocalizedStrings.CacheClientNotifier_EXCEPTION_OCCURRED_WHILE_PROCESSING_CQS), t);
}
}
} | void function(CacheEvent event, boolean processLocalProfile, Profile[] peerProfiles, FilterRoutingInfo frInfo) { CqService cqService = getCqService(event.getRegion()); if (cqService != null) { try { Profile local = processLocalProfile ? this.localProfile : null; cqService.processEvents(event, local, peerProfiles, frInfo); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); throw err; } catch (Throwable t) { SystemFailure.checkFailure(); logger.error(LocalizedMessage.create( LocalizedStrings.CacheClientNotifier_EXCEPTION_OCCURRED_WHILE_PROCESSING_CQS), t); } } } | /**
* get continuous query routing information
*
* @param event the event to process
* @param peerProfiles the profiles getting this event
* @param frInfo the routing table to update
*/ | get continuous query routing information | fillInCQRoutingInfo | {
"repo_name": "charliemblack/geode",
"path": "geode-core/src/main/java/org/apache/geode/internal/cache/FilterProfile.java",
"license": "apache-2.0",
"size": 78958
} | [
"org.apache.geode.SystemFailure",
"org.apache.geode.cache.CacheEvent",
"org.apache.geode.cache.query.internal.cq.CqService",
"org.apache.geode.distributed.internal.DistributionAdvisor",
"org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier",
"org.apache.geode.internal.i18n.LocalizedStrings",
"org.apache.geode.internal.logging.log4j.LocalizedMessage"
] | import org.apache.geode.SystemFailure; import org.apache.geode.cache.CacheEvent; import org.apache.geode.cache.query.internal.cq.CqService; import org.apache.geode.distributed.internal.DistributionAdvisor; import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.log4j.LocalizedMessage; | import org.apache.geode.*; import org.apache.geode.cache.*; import org.apache.geode.cache.query.internal.cq.*; import org.apache.geode.distributed.internal.*; import org.apache.geode.internal.cache.tier.sockets.*; import org.apache.geode.internal.i18n.*; import org.apache.geode.internal.logging.log4j.*; | [
"org.apache.geode"
] | org.apache.geode; | 1,623,826 |
private void reInitLayoutElements() {
m_panel.clear();
for (CmsCheckBox cb : m_checkBoxes) {
m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb));
}
} | void function() { m_panel.clear(); for (CmsCheckBox cb : m_checkBoxes) { m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb)); } } | /**
* Refresh the layout element.
*/ | Refresh the layout element | reInitLayoutElements | {
"repo_name": "alkacon/opencms-core",
"path": "src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsCheckableDatePanel.java",
"license": "lgpl-2.1",
"size": 11037
} | [
"com.google.gwt.user.client.ui.Label",
"org.opencms.gwt.client.ui.input.CmsCheckBox"
] | import com.google.gwt.user.client.ui.Label; import org.opencms.gwt.client.ui.input.CmsCheckBox; | import com.google.gwt.user.client.ui.*; import org.opencms.gwt.client.ui.input.*; | [
"com.google.gwt",
"org.opencms.gwt"
] | com.google.gwt; org.opencms.gwt; | 1,288,488 |
public static RelCollation apply(
Mappings.TargetMapping mapping,
RelCollation collation) {
List<RelFieldCollation> fieldCollations =
applyFields(mapping, collation.getFieldCollations());
return fieldCollations.equals(collation.getFieldCollations())
? collation
: RelCollations.of(fieldCollations);
} | static RelCollation function( Mappings.TargetMapping mapping, RelCollation collation) { List<RelFieldCollation> fieldCollations = applyFields(mapping, collation.getFieldCollations()); return fieldCollations.equals(collation.getFieldCollations()) ? collation : RelCollations.of(fieldCollations); } | /**
* Applies a mapping to a collation.
*
* @param mapping Mapping
* @param collation Collation
* @return collation with mapping applied
*/ | Applies a mapping to a collation | apply | {
"repo_name": "vlsi/calcite",
"path": "core/src/main/java/org/apache/calcite/rex/RexUtil.java",
"license": "apache-2.0",
"size": 89555
} | [
"java.util.List",
"org.apache.calcite.rel.RelCollation",
"org.apache.calcite.rel.RelCollations",
"org.apache.calcite.rel.RelFieldCollation",
"org.apache.calcite.util.mapping.Mappings"
] | import java.util.List; import org.apache.calcite.rel.RelCollation; import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.RelFieldCollation; import org.apache.calcite.util.mapping.Mappings; | import java.util.*; import org.apache.calcite.rel.*; import org.apache.calcite.util.mapping.*; | [
"java.util",
"org.apache.calcite"
] | java.util; org.apache.calcite; | 54,370 |
public org.ontoware.rdfreactor.schema.rdfs.Class getAccessToClass() {
return Base.getAll_as(this.model, this.getResource(), ACCESS_TO_CLASS,
org.ontoware.rdfreactor.schema.rdfs.Class.class).firstValue();
} | org.ontoware.rdfreactor.schema.rdfs.Class function() { return Base.getAll_as(this.model, this.getResource(), ACCESS_TO_CLASS, org.ontoware.rdfreactor.schema.rdfs.Class.class).firstValue(); } | /**
* Get all values of property AccessToClass * @return a ClosableIterator of
* $type [Generated from RDFReactor template rule #get12dynamic]
*/ | Get all values of property AccessToClass $type [Generated from RDFReactor template rule #get12dynamic] | getAccessToClass | {
"repo_name": "m0ep/master-thesis",
"path": "source/apis/rdf2go/rdf2go-w3-wacl/src/main/java/org/w3/ns/auth/acl/Authorization.java",
"license": "mit",
"size": 78044
} | [
"org.ontoware.rdfreactor.runtime.Base"
] | import org.ontoware.rdfreactor.runtime.Base; | import org.ontoware.rdfreactor.runtime.*; | [
"org.ontoware.rdfreactor"
] | org.ontoware.rdfreactor; | 675,199 |
public static void disableAdmin(Context context) {
DevicePolicyManager devicePolicyManager;
ComponentName demoDeviceAdmin;
devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
demoDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class);
devicePolicyManager.removeActiveAdmin(demoDeviceAdmin);
} | static void function(Context context) { DevicePolicyManager devicePolicyManager; ComponentName demoDeviceAdmin; devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); demoDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class); devicePolicyManager.removeActiveAdmin(demoDeviceAdmin); } | /**
* Disable admin privileges.
* @param context - Application context.
*/ | Disable admin privileges | disableAdmin | {
"repo_name": "Gayany/product-mdm",
"path": "modules/mobile-agents/android/client/client/src/main/java/org/wso2/emm/agent/utils/CommonUtils.java",
"license": "apache-2.0",
"size": 11917
} | [
"android.app.admin.DevicePolicyManager",
"android.content.ComponentName",
"android.content.Context",
"org.wso2.emm.agent.services.AgentDeviceAdminReceiver"
] | import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import org.wso2.emm.agent.services.AgentDeviceAdminReceiver; | import android.app.admin.*; import android.content.*; import org.wso2.emm.agent.services.*; | [
"android.app",
"android.content",
"org.wso2.emm"
] | android.app; android.content; org.wso2.emm; | 202,537 |
public void mv(String oldPath, String newPath) throws IOException
{
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(oldPath, charsetName);
tw.writeString(newPath, charsetName);
sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
public static final int SSH_FXF_READ = 0x00000001;
public static final int SSH_FXF_WRITE = 0x00000002;
public static final int SSH_FXF_APPEND = 0x00000004;
public static final int SSH_FXF_CREAT = 0x00000008;
public static final int SSH_FXF_TRUNC = 0x00000010;
public static final int SSH_FXF_EXCL = 0x00000020;
| void function(String oldPath, String newPath) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(oldPath, charsetName); tw.writeString(newPath, charsetName); sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } public static final int SSH_FXF_READ = 0x00000001; public static final int SSH_FXF_WRITE = 0x00000002; public static final int SSH_FXF_APPEND = 0x00000004; public static final int SSH_FXF_CREAT = 0x00000008; public static final int SSH_FXF_TRUNC = 0x00000010; public static final int SSH_FXF_EXCL = 0x00000020; | /**
* Move a file or directory.
*
* @param oldPath See the {@link SFTPv3Client comment} for the class for more details.
* @param newPath See the {@link SFTPv3Client comment} for the class for more details.
* @throws IOException
*/ | Move a file or directory | mv | {
"repo_name": "nickman/heliosutils",
"path": "src/main/java/ch/ethz/ssh2/SFTPv3Client.java",
"license": "apache-2.0",
"size": 46713
} | [
"ch.ethz.ssh2.packets.TypesWriter",
"ch.ethz.ssh2.sftp.Packet",
"java.io.IOException"
] | import ch.ethz.ssh2.packets.TypesWriter; import ch.ethz.ssh2.sftp.Packet; import java.io.IOException; | import ch.ethz.ssh2.packets.*; import ch.ethz.ssh2.sftp.*; import java.io.*; | [
"ch.ethz.ssh2",
"java.io"
] | ch.ethz.ssh2; java.io; | 2,847,582 |
protected AnalysisGraphConfiguration createConfiguration() {
List<BuildResultGraph> availableGraphs = getAvailableGraphs();
availableGraphs.add(0, new OriginGraph());
return new AnalysisGraphConfiguration(availableGraphs);
} | AnalysisGraphConfiguration function() { List<BuildResultGraph> availableGraphs = getAvailableGraphs(); availableGraphs.add(0, new OriginGraph()); return new AnalysisGraphConfiguration(availableGraphs); } | /**
* Creates the graph configuration.
*
* @return the graph configuration
*/ | Creates the graph configuration | createConfiguration | {
"repo_name": "amuniz/analysis-collector-plugin",
"path": "src/main/java/hudson/plugins/analysis/collector/AnalysisProjectAction.java",
"license": "mit",
"size": 6182
} | [
"hudson.plugins.analysis.graph.BuildResultGraph",
"java.util.List"
] | import hudson.plugins.analysis.graph.BuildResultGraph; import java.util.List; | import hudson.plugins.analysis.graph.*; import java.util.*; | [
"hudson.plugins.analysis",
"java.util"
] | hudson.plugins.analysis; java.util; | 2,694,300 |
@Nullable
@ObjectiveCName("joinGroupViaLinkCommandWithUrl:")
public Command<Integer> joinGroupViaLink(String url) {
return modules.getGroupsModule().joinGroupViaLink(url);
} | @ObjectiveCName(STR) Command<Integer> function(String url) { return modules.getGroupsModule().joinGroupViaLink(url); } | /**
* Join group using invite link
*
* @param url invite link
* @return Command for execution
*/ | Join group using invite link | joinGroupViaLink | {
"repo_name": "boneyao/actor-platform",
"path": "actor-apps/core/src/main/java/im/actor/model/Messenger.java",
"license": "mit",
"size": 50580
} | [
"com.google.j2objc.annotations.ObjectiveCName",
"im.actor.model.concurrency.Command"
] | import com.google.j2objc.annotations.ObjectiveCName; import im.actor.model.concurrency.Command; | import com.google.j2objc.annotations.*; import im.actor.model.concurrency.*; | [
"com.google.j2objc",
"im.actor.model"
] | com.google.j2objc; im.actor.model; | 851,428 |
private static float adjustBottom(float y, Rect imageRect, float imageSnapRadius, float aspectRatio) {
float resultY = y;
if (imageRect.bottom - y < imageSnapRadius)
resultY = imageRect.bottom;
else
{
// Select the maximum of the three possible values to use
float resultYVert = Float.NEGATIVE_INFINITY;
float resultYHoriz = Float.NEGATIVE_INFINITY;
// Checks if the window is too small vertically
if (y <= Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX)
resultYVert = Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX;
// Checks if the window is too small horizontally
if (((y - Edge.TOP.getCoordinate()) * aspectRatio) <= MIN_CROP_LENGTH_PX)
resultYHoriz = Edge.TOP.getCoordinate() + (MIN_CROP_LENGTH_PX / aspectRatio);
resultY = Math.max(resultY, Math.max(resultYHoriz, resultYVert));
}
return resultY;
} | static float function(float y, Rect imageRect, float imageSnapRadius, float aspectRatio) { float resultY = y; if (imageRect.bottom - y < imageSnapRadius) resultY = imageRect.bottom; else { float resultYVert = Float.NEGATIVE_INFINITY; float resultYHoriz = Float.NEGATIVE_INFINITY; if (y <= Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX) resultYVert = Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX; if (((y - Edge.TOP.getCoordinate()) * aspectRatio) <= MIN_CROP_LENGTH_PX) resultYHoriz = Edge.TOP.getCoordinate() + (MIN_CROP_LENGTH_PX / aspectRatio); resultY = Math.max(resultY, Math.max(resultYHoriz, resultYVert)); } return resultY; } | /**
* Get the resulting y-position of the bottom edge of the crop window given
* the handle's position and the image's bounding box and snap radius.
*
* @param y the x-position that the bottom edge is dragged to
* @param imageRect the bounding box of the image that is being cropped
* @param imageSnapRadius the snap distance to the image edge (in pixels)
* @return the actual y-position of the bottom edge
*/ | Get the resulting y-position of the bottom edge of the crop window given the handle's position and the image's bounding box and snap radius | adjustBottom | {
"repo_name": "devsoulwolf/PictureChooseLib",
"path": "library/src/main/java/net/soulwolf/image/picturelib/view/cropwindow/edge/Edge.java",
"license": "apache-2.0",
"size": 19836
} | [
"android.graphics.Rect"
] | import android.graphics.Rect; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 1,749,853 |
private String makeDateAgo(ProjectViewModel element){
if(element == null || ((ProjectViewModel) element).getLastChange() == null){
return null;
}
long diff = System.currentTimeMillis() - ((ProjectViewModel) element).getLastChange().getTime();
TimeAgo ago = TimeAgo.getAgo(diff);
StringBuilder buff = new StringBuilder();
diff = ago.getValue(diff);
switch(ago){
case Now:
buff.append("just now");
break;
case Mins:
buff.append(diff);
buff.append(" mins ago");
break;
case Hours:
buff.append(diff);
buff.append(" hours ago");
break;
case Yesterday:
buff.append(" yesterday");
break;
case Days:
buff.append(diff);
buff.append(" days ago");
break;
case Months:
buff.append(diff);
buff.append(" month ago");
break;
case Years:
buff.append(diff);
buff.append(" years ago");
break;
}
return buff.toString();
}
| String function(ProjectViewModel element){ if(element == null ((ProjectViewModel) element).getLastChange() == null){ return null; } long diff = System.currentTimeMillis() - ((ProjectViewModel) element).getLastChange().getTime(); TimeAgo ago = TimeAgo.getAgo(diff); StringBuilder buff = new StringBuilder(); diff = ago.getValue(diff); switch(ago){ case Now: buff.append(STR); break; case Mins: buff.append(diff); buff.append(STR); break; case Hours: buff.append(diff); buff.append(STR); break; case Yesterday: buff.append(STR); break; case Days: buff.append(diff); buff.append(STR); break; case Months: buff.append(diff); buff.append(STR); break; case Years: buff.append(diff); buff.append(STR); break; } return buff.toString(); } | /**
* Calculate time ago as string
*
* @param date
* @return Relative time string
*/ | Calculate time ago as string | makeDateAgo | {
"repo_name": "baloise/egitblit",
"path": "com.baloise.egitblit.plugin/src/com/baloise/egitblit/view/StyledLabelProvider.java",
"license": "apache-2.0",
"size": 21667
} | [
"com.baloise.egitblit.view.model.ProjectViewModel"
] | import com.baloise.egitblit.view.model.ProjectViewModel; | import com.baloise.egitblit.view.model.*; | [
"com.baloise.egitblit"
] | com.baloise.egitblit; | 2,629,699 |
@Override
public void setCollectionNameMap(
java.util.Map<java.util.Locale, java.lang.String> collectionNameMap,
java.util.Locale defaultLocale) {
_dictCollection.setCollectionNameMap(collectionNameMap, defaultLocale);
} | void function( java.util.Map<java.util.Locale, java.lang.String> collectionNameMap, java.util.Locale defaultLocale) { _dictCollection.setCollectionNameMap(collectionNameMap, defaultLocale); } | /**
* Sets the localized collection names of this dict collection from the map of locales and localized collection names, and sets the default locale.
*
* @param collectionNameMap the locales and localized collection names of this dict collection
* @param defaultLocale the default locale
*/ | Sets the localized collection names of this dict collection from the map of locales and localized collection names, and sets the default locale | setCollectionNameMap | {
"repo_name": "hltn/opencps",
"path": "portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/datamgt/model/DictCollectionWrapper.java",
"license": "agpl-3.0",
"size": 16794
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 566,696 |
public com.cellarhq.generated.tables.pojos.Category fetchOneById(Long value) {
return fetchOne(Category.CATEGORY.ID, value);
} | com.cellarhq.generated.tables.pojos.Category function(Long value) { return fetchOne(Category.CATEGORY.ID, value); } | /**
* Fetch a unique record that has <code>id = value</code>
*/ | Fetch a unique record that has <code>id = value</code> | fetchOneById | {
"repo_name": "CellarHQ/cellarhq.com",
"path": "model/src/main/generated/com/cellarhq/generated/tables/daos/CategoryDao.java",
"license": "mit",
"size": 7484
} | [
"com.cellarhq.generated.tables.Category"
] | import com.cellarhq.generated.tables.Category; | import com.cellarhq.generated.tables.*; | [
"com.cellarhq.generated"
] | com.cellarhq.generated; | 1,287,976 |
public static void unregister(final JTextComponent text) {
SpellChecker.enableShortKey(text, false);
SpellChecker.enablePopup(text, false);
SpellChecker.enableAutoSpell(text, false);
}
private SpellChecker() {
}
| static void function(final JTextComponent text) { SpellChecker.enableShortKey(text, false); SpellChecker.enablePopup(text, false); SpellChecker.enableAutoSpell(text, false); } private SpellChecker() { } | /**
* Removes all spell checker features from the JTextComponent. This does not need to be called
* if the text component is no longer needed.
* @param text the JTextComponent
*/ | Removes all spell checker features from the JTextComponent. This does not need to be called if the text component is no longer needed | unregister | {
"repo_name": "SDX2000/freeplane",
"path": "JOrtho_0.4_freeplane/src/com/inet/jortho/SpellChecker.java",
"license": "gpl-2.0",
"size": 27117
} | [
"javax.swing.text.JTextComponent"
] | import javax.swing.text.JTextComponent; | import javax.swing.text.*; | [
"javax.swing"
] | javax.swing; | 496,060 |
public static void validate(int[] oid) {
if (oid == null) {
throw new IllegalArgumentException(Messages.getString("security.98")); //$NON-NLS-1$
}
if (oid.length < 2) {
throw new IllegalArgumentException(
Messages.getString("security.99")); //$NON-NLS-1$
}
if (oid[0] > 2) {
throw new IllegalArgumentException(
Messages.getString("security.9A")); //$NON-NLS-1$
} else if (oid[0] != 2 && oid[1] > 39) {
throw new IllegalArgumentException(
Messages.getString("security.9B")); //$NON-NLS-1$
}
for (int i = 0; i < oid.length; i++) {
if (oid[i] < 0) {
throw new IllegalArgumentException(
Messages.getString("security.9C")); //$NON-NLS-1$
}
}
}
// FIXME: implement me
//
// public static void validate(String oid) {
//
// if (oid == null) {
// throw new NullPointerException();
// }
//
// int length = oid.length();
// if (length < 3 || oid.charAt(1) != '.') {
// throw new IllegalArgumentException("Invalid oid string");
// }
//
// int pos = 2;
// int subidentifier = 0;
// switch (oid.charAt(0)) {
// case '0':
// case '1':
// for (char c = oid.charAt(pos);;) {
// if (c < '0' || c > '9') {
// throw new IllegalArgumentException("Invalid oid string");
// } else {
// subidentifier = subidentifier * 10 + c - '0';
// }
//
// pos++;
// if (pos == length) {
// break;
// }
//
// c = oid.charAt(pos);
// if (c == '.') {
// pos++;
// if (pos == length) {
// throw new IllegalArgumentException("Invalid oid string");
// }
// break;
// }
// }
//
// if (subidentifier > 39) {
// throw new IllegalArgumentException(
// "If the first subidentifier has 0 or 1 value the second "
// + "subidentifier value MUST be less then 40.");
// }
// break;
// case '2':
// break;
// default:
// throw new IllegalArgumentException(
// "Valid values for first subidentifier are 0, 1 and 2");
// }
//
// if (pos == length) {
// return;
// }
//
// for (char c = oid.charAt(pos);;) {
// if (c < '0' || c > '9') {
// throw new IllegalArgumentException("Invalid oid string");
// }
//
// pos++;
// if (pos == length) {
// return;
// }
//
// c = oid.charAt(pos);
// if (c == '.') {
// pos++;
// if (pos == length) {
// throw new IllegalArgumentException("Invalid oid string");
// }
// }
// }
// } | static void function(int[] oid) { if (oid == null) { throw new IllegalArgumentException(Messages.getString(STR)); } if (oid.length < 2) { throw new IllegalArgumentException( Messages.getString(STR)); } if (oid[0] > 2) { throw new IllegalArgumentException( Messages.getString(STR)); } else if (oid[0] != 2 && oid[1] > 39) { throw new IllegalArgumentException( Messages.getString(STR)); } for (int i = 0; i < oid.length; i++) { if (oid[i] < 0) { throw new IllegalArgumentException( Messages.getString(STR)); } } } | /**
* Validates ObjectIdentifier (OID).
*
* @param oid - oid as array of integers
* @throws IllegalArgumentException - if oid is invalid or null
*/ | Validates ObjectIdentifier (OID) | validate | {
"repo_name": "freeVM/freeVM",
"path": "enhanced/java/classlib/modules/security/src/main/java/common/org/apache/harmony/security/asn1/ObjectIdentifier.java",
"license": "apache-2.0",
"size": 10324
} | [
"org.apache.harmony.security.internal.nls.Messages"
] | import org.apache.harmony.security.internal.nls.Messages; | import org.apache.harmony.security.internal.nls.*; | [
"org.apache.harmony"
] | org.apache.harmony; | 1,256,047 |
public JTextField getCriterion3() {
return criterion3;
}
| JTextField function() { return criterion3; } | /**
* Getter for criterion3.
*
* @return JTextField
* @author Heiko Müller
* @since 1.0
*/ | Getter for criterion3 | getCriterion3 | {
"repo_name": "hmueller80/VCF.Filter",
"path": "VCFFilter/src/at/ac/oeaw/cemm/bsf/vcffilter/filter/Filter.java",
"license": "gpl-3.0",
"size": 27069
} | [
"javax.swing.JTextField"
] | import javax.swing.JTextField; | import javax.swing.*; | [
"javax.swing"
] | javax.swing; | 2,724,174 |
public Packet createRgbaImageFrame(ByteBuffer buffer, int width, int height) {
if (buffer.capacity() != width * height * 4) {
throw new RuntimeException("buffer doesn't have the correct size.");
}
return Packet.create(
nativeCreateRgbaImageFrame(mediapipeGraph.getNativeHandle(), buffer, width, height));
} | Packet function(ByteBuffer buffer, int width, int height) { if (buffer.capacity() != width * height * 4) { throw new RuntimeException(STR); } return Packet.create( nativeCreateRgbaImageFrame(mediapipeGraph.getNativeHandle(), buffer, width, height)); } | /**
* Creates a 4 channel RGBA ImageFrame packet from an RGBA buffer.
*
* <p>Use {@link ByteBuffer#allocateDirect} when allocating the buffer.
*/ | Creates a 4 channel RGBA ImageFrame packet from an RGBA buffer. Use <code>ByteBuffer#allocateDirect</code> when allocating the buffer | createRgbaImageFrame | {
"repo_name": "google/mediapipe",
"path": "mediapipe/java/com/google/mediapipe/framework/PacketCreator.java",
"license": "apache-2.0",
"size": 17320
} | [
"java.nio.ByteBuffer"
] | import java.nio.ByteBuffer; | import java.nio.*; | [
"java.nio"
] | java.nio; | 1,245,824 |
List<Node> getAllNodes(); | List<Node> getAllNodes(); | /**
* Get all {@link Node}s.
*
* @return all nodes
*/ | Get all <code>Node</code>s | getAllNodes | {
"repo_name": "OpenWiseSolutions/openhub-framework",
"path": "core-spi/src/main/java/org/openhubframework/openhub/spi/node/NodeService.java",
"license": "apache-2.0",
"size": 1281
} | [
"java.util.List",
"org.openhubframework.openhub.api.entity.Node"
] | import java.util.List; import org.openhubframework.openhub.api.entity.Node; | import java.util.*; import org.openhubframework.openhub.api.entity.*; | [
"java.util",
"org.openhubframework.openhub"
] | java.util; org.openhubframework.openhub; | 1,229,316 |
public Point getTile(Point co); | Point function(Point co); | /**
* Returns the indixes of the current tile. These are the horizontal and
* vertical indexes of the current tile.
*
* @param co If not null this object is used to return the information. If
* null a new one is created and returned.
*
* @return The current tile's indices (vertical and horizontal indexes).
* */ | Returns the indixes of the current tile. These are the horizontal and vertical indexes of the current tile | getTile | {
"repo_name": "stelfrich/bioformats",
"path": "components/forks/jai/src/jj2000/j2k/image/ImgData.java",
"license": "gpl-2.0",
"size": 11860
} | [
"java.awt.Point"
] | import java.awt.Point; | import java.awt.*; | [
"java.awt"
] | java.awt; | 237,612 |
public static ims.pathways.configuration.domain.objects.Pathway extractPathway(ims.domain.ILightweightDomainFactory domainFactory, ims.pathways.vo.PathwayShortVo valueObject)
{
return extractPathway(domainFactory, valueObject, new HashMap());
} | static ims.pathways.configuration.domain.objects.Pathway function(ims.domain.ILightweightDomainFactory domainFactory, ims.pathways.vo.PathwayShortVo valueObject) { return extractPathway(domainFactory, valueObject, new HashMap()); } | /**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/ | Create the domain object from the value object | extractPathway | {
"repo_name": "open-health-hub/openMAXIMS",
"path": "openmaxims_workspace/ValueObjects/src/ims/pathways/vo/domain/PathwayShortVoAssembler.java",
"license": "agpl-3.0",
"size": 22664
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,071,698 |
public Future<Integer> scaleDown(Reconciliation reconciliation, String namespace, String name, int scaleTo) {
Promise<Integer> promise = Promise.promise();
vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking(
future -> {
try {
Integer nextReplicas = currentScale(namespace, name);
if (nextReplicas != null) {
while (nextReplicas > scaleTo) {
nextReplicas--;
LOGGER.infoCr(reconciliation, "Scaling down from {} to {}", nextReplicas + 1, nextReplicas);
resource(namespace, name).scale(nextReplicas, true);
}
}
future.complete(nextReplicas);
} catch (Exception e) {
LOGGER.errorCr(reconciliation, "Caught exception while scaling down", e);
future.fail(e);
}
},
false,
promise
);
return promise.future();
} | Future<Integer> function(Reconciliation reconciliation, String namespace, String name, int scaleTo) { Promise<Integer> promise = Promise.promise(); vertx.createSharedWorkerExecutor(STR).executeBlocking( future -> { try { Integer nextReplicas = currentScale(namespace, name); if (nextReplicas != null) { while (nextReplicas > scaleTo) { nextReplicas--; LOGGER.infoCr(reconciliation, STR, nextReplicas + 1, nextReplicas); resource(namespace, name).scale(nextReplicas, true); } } future.complete(nextReplicas); } catch (Exception e) { LOGGER.errorCr(reconciliation, STR, e); future.fail(e); } }, false, promise ); return promise.future(); } | /**
* Asynchronously scale down the resource given by {@code namespace} and {@code name} to have the scale given by
* {@code scaleTo}, returning a future for the outcome.
* If the resource does not exists, is has a current scale <= the given {@code scaleTo} then complete successfully.
* @param reconciliation The reconciliation
* @param namespace The namespace of the resource to scale.
* @param name The name of the resource to scale.
* @param scaleTo The desired scale.
* @return A future whose value is the scale after the operation.
* If the scale was initially < the given {@code scaleTo} then this value will be the original scale,
* The value will be null if the resource didn't exist (hence no scaling occurred).
*/ | Asynchronously scale down the resource given by namespace and name to have the scale given by scaleTo, returning a future for the outcome. If the resource does not exists, is has a current scale <= the given scaleTo then complete successfully | scaleDown | {
"repo_name": "ppatierno/kaas",
"path": "operator-common/src/main/java/io/strimzi/operator/common/operator/resource/AbstractScalableResourceOperator.java",
"license": "apache-2.0",
"size": 5832
} | [
"io.strimzi.operator.common.Reconciliation",
"io.vertx.core.Future",
"io.vertx.core.Promise"
] | import io.strimzi.operator.common.Reconciliation; import io.vertx.core.Future; import io.vertx.core.Promise; | import io.strimzi.operator.common.*; import io.vertx.core.*; | [
"io.strimzi.operator",
"io.vertx.core"
] | io.strimzi.operator; io.vertx.core; | 2,476,948 |
public BulkResponse withSyncBackoff(Client client, BulkRequest bulkRequest) throws Exception {
return SyncRetryHandler
.create(retryOnThrowable, backoffPolicy, client)
.executeBlocking(bulkRequest)
.actionGet();
}
static class AbstractRetryHandler implements ActionListener<BulkResponse> {
private final ESLogger logger;
private final Client client;
private final ActionListener<BulkResponse> listener;
private final Iterator<TimeValue> backoff;
private final Class<? extends Throwable> retryOnThrowable;
// Access only when holding a client-side lock, see also #addResponses()
private final List<BulkItemResponse> responses = new ArrayList<>();
private final long startTimestampNanos;
// needed to construct the next bulk request based on the response to the previous one
// volatile as we're called from a scheduled thread
private volatile BulkRequest currentBulkRequest;
private volatile ScheduledFuture<?> scheduledRequestFuture;
public AbstractRetryHandler(Class<? extends Throwable> retryOnThrowable, BackoffPolicy backoffPolicy, Client client, ActionListener<BulkResponse> listener) {
this.retryOnThrowable = retryOnThrowable;
this.backoff = backoffPolicy.iterator();
this.client = client;
this.listener = listener;
this.logger = Loggers.getLogger(getClass(), client.settings());
// in contrast to System.currentTimeMillis(), nanoTime() uses a monotonic clock under the hood
this.startTimestampNanos = System.nanoTime();
} | BulkResponse function(Client client, BulkRequest bulkRequest) throws Exception { return SyncRetryHandler .create(retryOnThrowable, backoffPolicy, client) .executeBlocking(bulkRequest) .actionGet(); } static class AbstractRetryHandler implements ActionListener<BulkResponse> { private final ESLogger logger; private final Client client; private final ActionListener<BulkResponse> listener; private final Iterator<TimeValue> backoff; private final Class<? extends Throwable> retryOnThrowable; private final List<BulkItemResponse> responses = new ArrayList<>(); private final long startTimestampNanos; private volatile BulkRequest currentBulkRequest; private volatile ScheduledFuture<?> scheduledRequestFuture; public AbstractRetryHandler(Class<? extends Throwable> retryOnThrowable, BackoffPolicy backoffPolicy, Client client, ActionListener<BulkResponse> listener) { this.retryOnThrowable = retryOnThrowable; this.backoff = backoffPolicy.iterator(); this.client = client; this.listener = listener; this.logger = Loggers.getLogger(getClass(), client.settings()); this.startTimestampNanos = System.nanoTime(); } | /**
* Invokes #bulk(BulkRequest) on the provided client. Backs off on the provided exception.
*
* @param client Client invoking the bulk request.
* @param bulkRequest The bulk request that should be executed.
* @return the bulk response as returned by the client.
* @throws Exception Any exception thrown by the callable.
*/ | Invokes #bulk(BulkRequest) on the provided client. Backs off on the provided exception | withSyncBackoff | {
"repo_name": "xuzha/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/action/bulk/Retry.java",
"license": "apache-2.0",
"size": 10160
} | [
"java.util.ArrayList",
"java.util.Iterator",
"java.util.List",
"java.util.concurrent.ScheduledFuture",
"org.elasticsearch.action.ActionListener",
"org.elasticsearch.client.Client",
"org.elasticsearch.common.logging.ESLogger",
"org.elasticsearch.common.logging.Loggers",
"org.elasticsearch.common.unit.TimeValue"
] | import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ScheduledFuture; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.unit.TimeValue; | import java.util.*; import java.util.concurrent.*; import org.elasticsearch.action.*; import org.elasticsearch.client.*; import org.elasticsearch.common.logging.*; import org.elasticsearch.common.unit.*; | [
"java.util",
"org.elasticsearch.action",
"org.elasticsearch.client",
"org.elasticsearch.common"
] | java.util; org.elasticsearch.action; org.elasticsearch.client; org.elasticsearch.common; | 2,567,711 |
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
} | int function() { return KeyCodes.KEY_UP; } | /**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/ | Get the key that moves the selection head upwards. By default it is the up arrow key but by overriding this you can change the key to whatever you want | getNavigationUpKey | {
"repo_name": "udayinfy/vaadin",
"path": "client/src/com/vaadin/client/ui/VScrollTable.java",
"license": "apache-2.0",
"size": 315709
} | [
"com.google.gwt.event.dom.client.KeyCodes"
] | import com.google.gwt.event.dom.client.KeyCodes; | import com.google.gwt.event.dom.client.*; | [
"com.google.gwt"
] | com.google.gwt; | 296,417 |
public Cell maybeCloneWithAllocator(Cell cell) {
if (this.memStoreLAB == null) {
return cell;
}
Cell cellFromMslab = this.memStoreLAB.copyCellInto(cell);
return (cellFromMslab != null) ? cellFromMslab : cell;
}
/**
* Get cell length after serialized in {@link KeyValue} | Cell function(Cell cell) { if (this.memStoreLAB == null) { return cell; } Cell cellFromMslab = this.memStoreLAB.copyCellInto(cell); return (cellFromMslab != null) ? cellFromMslab : cell; } /** * Get cell length after serialized in {@link KeyValue} | /**
* If the segment has a memory allocator the cell is being cloned to this space, and returned;
* otherwise the given cell is returned
* @return either the given cell or its clone
*/ | If the segment has a memory allocator the cell is being cloned to this space, and returned; otherwise the given cell is returned | maybeCloneWithAllocator | {
"repo_name": "vincentpoon/hbase",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Segment.java",
"license": "apache-2.0",
"size": 11529
} | [
"org.apache.hadoop.hbase.Cell",
"org.apache.hadoop.hbase.KeyValue"
] | import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.KeyValue; | import org.apache.hadoop.hbase.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 202,356 |
public static Set<IFile> getDbFilesFromProject(IProject project)
{
// Result containing the .db resources
HashSet<IFile> dbCollection = new HashSet<IFile>();
// List of candidate folder to be inspected
HashSet<IFolder> folderCollection = new HashSet<IFolder>();
// First, retrieve and check if the folders likely to contain the .db files exist
folderCollection.add(project.getFolder(ASSESTS_FOLDER));
folderCollection.add(project.getFolder(RAW_FOLDER));
// Iterate through the folders and retrieve the .db IFiles
for (IFolder folder : folderCollection)
{
if (folder.exists())
{
// Get a list of files in the folder and try to find the .db files
try
{
for (IResource resource : folder.members())
{
// Check if it's a file
if (resource.getType() == IResource.FILE)
{
IFile file = (IFile) resource;
// Check if the file is a valid database
try
{
if (file.exists()
& isValidSQLiteDatabase(file.getLocation().toFile()))
{
dbCollection.add(file);
}
}
catch (IOException e)
{
StudioLogger
.warn(DatabaseUtils.class,
"It was not possible verify if the file is a valid SQLite database",
e);
}
}
}
}
catch (CoreException e)
{
// Log error
StudioLogger.error(DatabaseUtils.class,
"An error ocurred while looking for .db files.", e); //$NON-NLS-1$
}
}
}
return dbCollection;
} | static Set<IFile> function(IProject project) { HashSet<IFile> dbCollection = new HashSet<IFile>(); HashSet<IFolder> folderCollection = new HashSet<IFolder>(); folderCollection.add(project.getFolder(ASSESTS_FOLDER)); folderCollection.add(project.getFolder(RAW_FOLDER)); for (IFolder folder : folderCollection) { if (folder.exists()) { try { for (IResource resource : folder.members()) { if (resource.getType() == IResource.FILE) { IFile file = (IFile) resource; try { if (file.exists() & isValidSQLiteDatabase(file.getLocation().toFile())) { dbCollection.add(file); } } catch (IOException e) { StudioLogger .warn(DatabaseUtils.class, STR, e); } } } } catch (CoreException e) { StudioLogger.error(DatabaseUtils.class, STR, e); } } } return dbCollection; } | /**
* Retrieve a collections of .db resources declared inside an IProject in the workspace.
* @param project The project to be considered.
*/ | Retrieve a collections of .db resources declared inside an IProject in the workspace | getDbFilesFromProject | {
"repo_name": "rex-xxx/mt6572_x201",
"path": "tools/motodev/src/plugins/android.codeutils/src/com/motorola/studio/android/codeutils/db/utils/DatabaseUtils.java",
"license": "gpl-2.0",
"size": 46539
} | [
"com.motorola.studio.android.common.log.StudioLogger",
"java.io.IOException",
"java.util.HashSet",
"java.util.Set",
"org.eclipse.core.resources.IFile",
"org.eclipse.core.resources.IFolder",
"org.eclipse.core.resources.IProject",
"org.eclipse.core.resources.IResource",
"org.eclipse.core.runtime.CoreException"
] | import com.motorola.studio.android.common.log.StudioLogger; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; | import com.motorola.studio.android.common.log.*; import java.io.*; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; | [
"com.motorola.studio",
"java.io",
"java.util",
"org.eclipse.core"
] | com.motorola.studio; java.io; java.util; org.eclipse.core; | 1,503,977 |
public EntityTypeInvocationHandler getEntity(final EntityUUID uuid) {
return searchableEntities.get(uuid);
} | EntityTypeInvocationHandler function(final EntityUUID uuid) { return searchableEntities.get(uuid); } | /**
* Searches an entity with the specified key.
*
* @param uuid entity key.
* @return retrieved entity.
*/ | Searches an entity with the specified key | getEntity | {
"repo_name": "sujianping/Office-365-SDK-for-Android",
"path": "sdk/office365-mail-calendar-contact-sdk/proxy/proxy-odata/src/main/java/com/msopentech/odatajclient/proxy/api/context/EntityContext.java",
"license": "apache-2.0",
"size": 6702
} | [
"com.msopentech.odatajclient.proxy.api.impl.EntityTypeInvocationHandler"
] | import com.msopentech.odatajclient.proxy.api.impl.EntityTypeInvocationHandler; | import com.msopentech.odatajclient.proxy.api.impl.*; | [
"com.msopentech.odatajclient"
] | com.msopentech.odatajclient; | 160,794 |
int updateByPrimaryKey(User record); | int updateByPrimaryKey(User record); | /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/ | This method was generated by MyBatis Generator. This method corresponds to the database table user | updateByPrimaryKey | {
"repo_name": "nicefishcn/nicefish-backend",
"path": "nicefish-dao/src/main/java/com/nicefish/gen/UserMapperGen.java",
"license": "mit",
"size": 1345
} | [
"com.nicefish.model.User"
] | import com.nicefish.model.User; | import com.nicefish.model.*; | [
"com.nicefish.model"
] | com.nicefish.model; | 2,782,756 |
public boolean supportsCredentialChanges(UserModel user) {
return (user != null && user.isLocalAccount()) || userService.supportsCredentialChanges();
}
| boolean function(UserModel user) { return (user != null && user.isLocalAccount()) userService.supportsCredentialChanges(); } | /**
* Returns true if the user's credentials can be changed.
*
* @param user
* @return true if the user service supports credential changes
*/ | Returns true if the user's credentials can be changed | supportsCredentialChanges | {
"repo_name": "BullShark/IRCBlit",
"path": "src/main/java/com/gitblit/GitBlit.java",
"license": "apache-2.0",
"size": 119961
} | [
"com.gitblit.models.UserModel"
] | import com.gitblit.models.UserModel; | import com.gitblit.models.*; | [
"com.gitblit.models"
] | com.gitblit.models; | 1,491,061 |
public static String encodeToString(byte[] input, int flags) {
try {
return new String(encode(input, flags), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
} | static String function(byte[] input, int flags) { try { return new String(encode(input, flags), STR); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } | /**
* Base64-encode the given data and return a newly allocated
* String with the result.
*
* @param input the data to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/ | Base64-encode the given data and return a newly allocated String with the result | encodeToString | {
"repo_name": "njflabs/evenflow",
"path": "webdroid/src/com/njfsoft_utils/core/Base64Android.java",
"license": "mit",
"size": 28702
} | [
"java.io.UnsupportedEncodingException"
] | import java.io.UnsupportedEncodingException; | import java.io.*; | [
"java.io"
] | java.io; | 1,095,511 |
private void validateAndSetAPISecurity(APIProduct apiProduct) {
String apiSecurity = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
String security = apiProduct.getApiSecurity();
if (security!= null) {
apiSecurity = security;
ArrayList<String> securityLevels = selectSecurityLevels(apiSecurity);
apiSecurity = String.join(",", securityLevels);
}
if (log.isDebugEnabled()) {
log.debug("APIProduct " + apiProduct.getId() + " has following enabled protocols : " + apiSecurity);
}
apiProduct.setApiSecurity(apiSecurity);
} | void function(APIProduct apiProduct) { String apiSecurity = APIConstants.DEFAULT_API_SECURITY_OAUTH2; String security = apiProduct.getApiSecurity(); if (security!= null) { apiSecurity = security; ArrayList<String> securityLevels = selectSecurityLevels(apiSecurity); apiSecurity = String.join(",", securityLevels); } if (log.isDebugEnabled()) { log.debug(STR + apiProduct.getId() + STR + apiSecurity); } apiProduct.setApiSecurity(apiSecurity); } | /**
* To validate the API Security options and set it.
*
* @param apiProduct Relevant APIProduct that need to be validated.
*/ | To validate the API Security options and set it | validateAndSetAPISecurity | {
"repo_name": "malinthaprasan/carbon-apimgt",
"path": "components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java",
"license": "apache-2.0",
"size": 479940
} | [
"java.util.ArrayList",
"org.wso2.carbon.apimgt.api.model.APIProduct"
] | import java.util.ArrayList; import org.wso2.carbon.apimgt.api.model.APIProduct; | import java.util.*; import org.wso2.carbon.apimgt.api.model.*; | [
"java.util",
"org.wso2.carbon"
] | java.util; org.wso2.carbon; | 262,488 |
private void reportErrors( Collection<RoboconfError> errors ) throws IOException {
// Add a log entry
getLog().info( "Generating a report for validation errors under " + MavenPluginConstants.VALIDATION_RESULT_PATH );
// Generate the report (file and console too)
StringBuilder sb = MavenPluginUtils.formatErrors( errors, getLog());
// Write the report.
// Reporting only makes sense when there is an error or a warning.
File targetFile = new File( this.project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH );
Utils.createDirectory( targetFile.getParentFile());
Utils.writeStringInto( sb.toString(), targetFile );
} | void function( Collection<RoboconfError> errors ) throws IOException { getLog().info( STR + MavenPluginConstants.VALIDATION_RESULT_PATH ); StringBuilder sb = MavenPluginUtils.formatErrors( errors, getLog()); File targetFile = new File( this.project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH ); Utils.createDirectory( targetFile.getParentFile()); Utils.writeStringInto( sb.toString(), targetFile ); } | /**
* Reports errors (in the logger and in a file).
* @param errors
* @throws IOException
*/ | Reports errors (in the logger and in a file) | reportErrors | {
"repo_name": "gibello/roboconf",
"path": "miscellaneous/roboconf-maven-plugin/src/main/java/net/roboconf/maven/ValidateApplicationMojo.java",
"license": "apache-2.0",
"size": 6873
} | [
"java.io.File",
"java.io.IOException",
"java.util.Collection",
"net.roboconf.core.errors.RoboconfError",
"net.roboconf.core.utils.Utils"
] | import java.io.File; import java.io.IOException; import java.util.Collection; import net.roboconf.core.errors.RoboconfError; import net.roboconf.core.utils.Utils; | import java.io.*; import java.util.*; import net.roboconf.core.errors.*; import net.roboconf.core.utils.*; | [
"java.io",
"java.util",
"net.roboconf.core"
] | java.io; java.util; net.roboconf.core; | 2,674,418 |
@RequestMapping(method = RequestMethod.POST, value = { "/identity/register" })
public String register(@Valid RegistrationForm registration, BindingResult result) {
logger.trace("Entering Register");
if (result.hasErrors()) {
return "basic/main/index";
}
this.identityService.registerIdentity(registration);
return "basic/main/index";
}
| @RequestMapping(method = RequestMethod.POST, value = { STR }) String function(@Valid RegistrationForm registration, BindingResult result) { logger.trace(STR); if (result.hasErrors()) { return STR; } this.identityService.registerIdentity(registration); return STR; } | /**
* Handles the submission from the registration form.
*
* @param registration
* @param result
* @param model
* @return
*/ | Handles the submission from the registration form | register | {
"repo_name": "Feolive/EmploymentWebsite",
"path": "src/main/java/com/charmyin/cmstudio/basic/authorize/controller/IdentityController.java",
"license": "mit",
"size": 12374
} | [
"com.charmyin.cmstudio.basic.authorize.form.RegistrationForm",
"javax.validation.Valid",
"org.springframework.validation.BindingResult",
"org.springframework.web.bind.annotation.RequestMapping",
"org.springframework.web.bind.annotation.RequestMethod"
] | import com.charmyin.cmstudio.basic.authorize.form.RegistrationForm; import javax.validation.Valid; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; | import com.charmyin.cmstudio.basic.authorize.form.*; import javax.validation.*; import org.springframework.validation.*; import org.springframework.web.bind.annotation.*; | [
"com.charmyin.cmstudio",
"javax.validation",
"org.springframework.validation",
"org.springframework.web"
] | com.charmyin.cmstudio; javax.validation; org.springframework.validation; org.springframework.web; | 941,905 |
public static <K extends Serializable, V extends Serializable> CacheAccess<K, V> defineRegion( String name, ICompositeCacheAttributes cattr )
throws CacheException
{
CompositeCache<K, V> cache = getCacheManager().getCache( name, cattr );
return new CacheAccess<K, V>( cache );
} | static <K extends Serializable, V extends Serializable> CacheAccess<K, V> function( String name, ICompositeCacheAttributes cattr ) throws CacheException { CompositeCache<K, V> cache = getCacheManager().getCache( name, cattr ); return new CacheAccess<K, V>( cache ); } | /**
* Define a new cache region with the specified name and attributes.
* <p>
* @param name Name that will identify the region
* @param cattr CompositeCacheAttributes for the region
* @return CacheAccess instance for the new region
* @exception CacheException
*/ | Define a new cache region with the specified name and attributes. | defineRegion | {
"repo_name": "tikue/jcs2-snapshot",
"path": "src/java/org/apache/commons/jcs/JCS.java",
"license": "apache-2.0",
"size": 8519
} | [
"java.io.Serializable",
"org.apache.commons.jcs.access.CacheAccess",
"org.apache.commons.jcs.access.exception.CacheException",
"org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes",
"org.apache.commons.jcs.engine.control.CompositeCache"
] | import java.io.Serializable; import org.apache.commons.jcs.access.CacheAccess; import org.apache.commons.jcs.access.exception.CacheException; import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes; import org.apache.commons.jcs.engine.control.CompositeCache; | import java.io.*; import org.apache.commons.jcs.access.*; import org.apache.commons.jcs.access.exception.*; import org.apache.commons.jcs.engine.behavior.*; import org.apache.commons.jcs.engine.control.*; | [
"java.io",
"org.apache.commons"
] | java.io; org.apache.commons; | 712,173 |
public TargetModuleID []getNonRunningModules(ModuleType moduleType,
Target []targetList)
throws TargetException, IllegalStateException; | public TargetModuleID []getNonRunningModules(ModuleType moduleType, Target []targetList) throws TargetException, IllegalStateException; | /**
* Returns the current non-running modules.
*/ | Returns the current non-running modules | getNonRunningModules | {
"repo_name": "christianchristensen/resin",
"path": "modules/j2ee-deploy/src/javax/enterprise/deploy/spi/DeploymentManager.java",
"license": "gpl-2.0",
"size": 5097
} | [
"javax.enterprise.deploy.shared.ModuleType",
"javax.enterprise.deploy.spi.exceptions.TargetException"
] | import javax.enterprise.deploy.shared.ModuleType; import javax.enterprise.deploy.spi.exceptions.TargetException; | import javax.enterprise.deploy.shared.*; import javax.enterprise.deploy.spi.exceptions.*; | [
"javax.enterprise"
] | javax.enterprise; | 2,313,320 |
public void finish() {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Finishing " + this);
}
// if there is a print writer, flush any content unless it is already
// closed. We don't need to do this with streams.
if (null != this.outWriter) {
this.outWriter.checkError();
}
} | void function() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, STR + this); } if (null != this.outWriter) { this.outWriter.checkError(); } } | /**
* Finish any processing necessary before the connection begins it's
* own final work and completes this request/response exchange.
*/ | Finish any processing necessary before the connection begins it's own final work and completes this request/response exchange | finish | {
"repo_name": "kgibm/open-liberty",
"path": "dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/servlet/internal/ResponseMessage.java",
"license": "epl-1.0",
"size": 23361
} | [
"com.ibm.websphere.ras.Tr",
"com.ibm.websphere.ras.TraceComponent"
] | import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; | import com.ibm.websphere.ras.*; | [
"com.ibm.websphere"
] | com.ibm.websphere; | 2,070,093 |
public void testClassGetName() throws IOException {
String source = "Class cls = getClass(); String s1 = cls.getName();"
+ "String s2 = cls.getSimpleName(); String s3 = cls.getCanonicalName();";
List<Statement> stmts = translateStatements(source);
assertEquals(4, stmts.size());
String result = generateStatement(stmts.get(1));
assertEquals("NSString *s1 = [cls getName];", result);
result = generateStatement(stmts.get(2));
assertEquals("NSString *s2 = [cls getSimpleName];", result);
result = generateStatement(stmts.get(3));
assertEquals("NSString *s3 = [cls getCanonicalName];", result);
} | void function() throws IOException { String source = STR + STR; List<Statement> stmts = translateStatements(source); assertEquals(4, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals(STR, result); result = generateStatement(stmts.get(2)); assertEquals(STR, result); result = generateStatement(stmts.get(3)); assertEquals(STR, result); } | /**
* Verify that Class.getName() and Class.getSimpleName() return the
* Obj-C class name. They are the same because Obj-C has a flat class
* namespace.
*/ | Verify that Class.getName() and Class.getSimpleName() return the Obj-C class name. They are the same because Obj-C has a flat class namespace | testClassGetName | {
"repo_name": "groschovskiy/j2objc",
"path": "translator/src/test/java/com/google/devtools/j2objc/translate/JavaToIOSMethodTranslatorTest.java",
"license": "apache-2.0",
"size": 11055
} | [
"com.google.devtools.j2objc.ast.Statement",
"java.io.IOException",
"java.util.List"
] | import com.google.devtools.j2objc.ast.Statement; import java.io.IOException; import java.util.List; | import com.google.devtools.j2objc.ast.*; import java.io.*; import java.util.*; | [
"com.google.devtools",
"java.io",
"java.util"
] | com.google.devtools; java.io; java.util; | 9,217 |
Set<AnnotatedDocument> getDocuments(Entity entity);
| Set<AnnotatedDocument> getDocuments(Entity entity); | /**
* Returns a set of documents based on how the underlying index is processing the given
* search string.
*
* @param searchString query specifying the documents to retrieve
* @return set of documents retrieved based on the given query string
*/ | Returns a set of documents based on how the underlying index is processing the given search string | getDocuments | {
"repo_name": "daftano/dl-learner",
"path": "components-core/src/main/java/org/dllearner/algorithms/isle/index/Index.java",
"license": "gpl-3.0",
"size": 1368
} | [
"java.util.Set",
"org.dllearner.core.owl.Entity"
] | import java.util.Set; import org.dllearner.core.owl.Entity; | import java.util.*; import org.dllearner.core.owl.*; | [
"java.util",
"org.dllearner.core"
] | java.util; org.dllearner.core; | 791,554 |
public static Object instantiate(Class klass, Object ... args) {
if(klass == null) {
return null;
}
//LOG.info(" At instantiattion of: " + klass.getName());
Constructor []constructors = klass.getConstructors();
for (Constructor constructor : constructors) {
try {
//LOG.info(" At instantiattion of: " + constructor.getName());
return constructor.newInstance(args);
} catch (InvocationTargetException e) {
LOG.debug("Can't instantiate object.", e);
} catch (InstantiationException e) {
LOG.trace("Can't instantiate object.", e);
} catch (IllegalAccessException e) {
LOG.trace("Can't instantiate object.", e);
} catch (IllegalArgumentException e) {
LOG.trace("Can't instantiate object.", e);
}
}
return null;
} | static Object function(Class klass, Object ... args) { if(klass == null) { return null; } Constructor []constructors = klass.getConstructors(); for (Constructor constructor : constructors) { try { return constructor.newInstance(args); } catch (InvocationTargetException e) { LOG.debug(STR, e); } catch (InstantiationException e) { LOG.trace(STR, e); } catch (IllegalAccessException e) { LOG.trace(STR, e); } catch (IllegalArgumentException e) { LOG.trace(STR, e); } } return null; } | /**
* Create instance of given class and given parameters.
*
* Please note that due to inherited limitations from Java languge, this
* method can't handle primitive types and NULL values.
*
* @param klass Class object
* @param args Objects that should be passed as constructor arguments.
* @return Instance of new class or NULL in case of any error
*/ | Create instance of given class and given parameters. Please note that due to inherited limitations from Java languge, this method can't handle primitive types and NULL values | instantiate | {
"repo_name": "vybs/sqoop-on-spark",
"path": "common/src/main/java/org/apache/sqoop/utils/ClassUtils.java",
"license": "apache-2.0",
"size": 5262
} | [
"java.lang.reflect.Constructor",
"java.lang.reflect.InvocationTargetException"
] | import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 928,364 |
@Test(expected = GenieNotFoundException.class)
public void testGetTagsForClusterNoCluster() throws GenieException {
final String id = UUID.randomUUID().toString();
Mockito.when(this.clusterRepository.findOne(id)).thenReturn(null);
this.service.getTagsForCluster(id);
} | @Test(expected = GenieNotFoundException.class) void function() throws GenieException { final String id = UUID.randomUUID().toString(); Mockito.when(this.clusterRepository.findOne(id)).thenReturn(null); this.service.getTagsForCluster(id); } | /**
* Test get tags to cluster.
*
* @throws GenieException For any problem
*/ | Test get tags to cluster | testGetTagsForClusterNoCluster | {
"repo_name": "sensaid/genie",
"path": "genie-core/src/test/java/com/netflix/genie/core/services/impl/jpa/TestClusterConfigServiceJPAImpl.java",
"license": "apache-2.0",
"size": 17701
} | [
"com.netflix.genie.common.exceptions.GenieException",
"com.netflix.genie.common.exceptions.GenieNotFoundException",
"java.util.UUID",
"org.junit.Test",
"org.mockito.Mockito"
] | import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieNotFoundException; import java.util.UUID; import org.junit.Test; import org.mockito.Mockito; | import com.netflix.genie.common.exceptions.*; import java.util.*; import org.junit.*; import org.mockito.*; | [
"com.netflix.genie",
"java.util",
"org.junit",
"org.mockito"
] | com.netflix.genie; java.util; org.junit; org.mockito; | 1,978,793 |
public static String generateClassNames(String classNames, Model model) {
if (classNames == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (String s : StringUtil.tokenize(classNames)) {
sb.append(model.getPackageName() + "." + XmlUtil.getFragmentFromURI(s + " "));
}
return sb.toString().trim();
} | static String function(String classNames, Model model) { if (classNames == null) { return null; } StringBuffer sb = new StringBuffer(); for (String s : StringUtil.tokenize(classNames)) { sb.append(model.getPackageName() + "." + XmlUtil.getFragmentFromURI(s + " ")); } return sb.toString().trim(); } | /**
* Generate a package qualified class name within the specified model from a space separated
* list of namespace qualified names
*
* @param classNames the list of namepace qualified names
* @param model the relevant model
* @return the package qualified names
*/ | Generate a package qualified class name within the specified model from a space separated list of namespace qualified names | generateClassNames | {
"repo_name": "julie-sullivan/phytomine",
"path": "intermine/integrate/main/src/org/intermine/xml/full/ItemHelper.java",
"license": "lgpl-2.1",
"size": 5180
} | [
"org.intermine.metadata.Model",
"org.intermine.metadata.StringUtil",
"org.intermine.util.XmlUtil"
] | import org.intermine.metadata.Model; import org.intermine.metadata.StringUtil; import org.intermine.util.XmlUtil; | import org.intermine.metadata.*; import org.intermine.util.*; | [
"org.intermine.metadata",
"org.intermine.util"
] | org.intermine.metadata; org.intermine.util; | 1,971,083 |
public Set<X509Certificate> listCertificates() throws CAException;
| Set<X509Certificate> function() throws CAException; | /**
* Lists certificates signed by this CA
*
* @return a Set of certificates signed by this CA
*
* @throws CAException
*/ | Lists certificates signed by this CA | listCertificates | {
"repo_name": "RomanKisilenko/ca",
"path": "src/main/java/me/it_result/ca/CA.java",
"license": "gpl-3.0",
"size": 2721
} | [
"java.security.cert.X509Certificate",
"java.util.Set"
] | import java.security.cert.X509Certificate; import java.util.Set; | import java.security.cert.*; import java.util.*; | [
"java.security",
"java.util"
] | java.security; java.util; | 1,925,322 |
public void test_022_omitDatatype()
throws Exception
{
Connection conn = getConnection();
//
// Verify basic ALTER TABLE without a column datatype
//
goodStatement
(
conn,
"create table t_nd_1( a int )"
);
goodStatement
(
conn,
"alter table t_nd_1 add b generated always as ( -a )"
);
goodStatement
(
conn,
"insert into t_nd_1( a ) values ( 1 )"
);
assertColumnTypes
(
conn,
"T_ND_1",
new String[][]
{
{ "A", "INTEGER" },
{ "B", "INTEGER" },
}
);
assertResults
(
conn,
"select * from t_nd_1 order by a",
new String[][]
{
{ "1", "-1" },
},
false
);
//
// Verify that you can't omit the datatype for other types of columns.
//
expectCompilationError
(
NEED_EXPLICIT_DATATYPE,
"create table t_nd_2( a generated always as identity )"
);
expectCompilationError
(
CANT_ADD_IDENTITY,
"alter table t_nd_1 add c generated always as identity"
);
//
// Verify basic CREATE TABLE omitting datatype on generated column
//
goodStatement
(
conn,
"create table t_nd_3( a int, b generated always as ( -a ) )"
);
goodStatement
(
conn,
"insert into t_nd_3( a ) values ( 100 )"
);
assertColumnTypes
(
conn,
"T_ND_3",
new String[][]
{
{ "A", "INTEGER" },
{ "B", "INTEGER" },
}
);
assertResults
(
conn,
"select * from t_nd_3 order by a",
new String[][]
{
{ "100", "-100" },
},
false
);
//
// Now verify various datatypes are correctly resolved.
//
goodStatement
(
conn,
"create table t_nd_smallint\n" +
"(\n" +
" a smallint,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_smallint( a ) values ( 1 )"
);
assertColumnTypes
(
conn,
"T_ND_SMALLINT",
new String[][]
{
{ "A", "SMALLINT" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_smallint order by a",
new String[][]
{
{ "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_int\n" +
"(\n" +
" a int,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_int( a ) values ( 1 )"
);
assertColumnTypes
(
conn,
"T_ND_INT",
new String[][]
{
{ "A", "INTEGER" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_int order by a",
new String[][]
{
{ "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_bigint\n" +
"(\n" +
" a bigint,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_bigint( a ) values ( 1 )"
);
assertColumnTypes
(
conn,
"T_ND_BIGINT",
new String[][]
{
{ "A", "BIGINT" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_bigint order by a",
new String[][]
{
{ "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_decimal\n" +
"(\n" +
" a decimal,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_decimal( a ) values ( 1.0 )"
);
assertColumnTypes
(
conn,
"T_ND_DECIMAL",
new String[][]
{
{ "A", "DECIMAL(5,0)" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_decimal order by a",
new String[][]
{
{ "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_real\n" +
"(\n" +
" a real,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_real( a ) values ( 1.0 )"
);
assertColumnTypes
(
conn,
"T_ND_REAL",
new String[][]
{
{ "A", "REAL" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_real order by a",
new String[][]
{
{ "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_double\n" +
"(\n" +
" a double,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_double( a ) values ( 1.0 )"
);
assertColumnTypes
(
conn,
"T_ND_DOUBLE",
new String[][]
{
{ "A", "DOUBLE" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_double order by a",
new String[][]
{
{ "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_float\n" +
"(\n" +
" a float,\n" +
" b generated always as ( cast ( -a as smallint ) ),\n" +
" c generated always as ( cast ( -a as int ) ),\n" +
" d generated always as ( cast( -a as bigint ) ),\n" +
" e generated always as ( cast ( -a as decimal ) ),\n" +
" f generated always as ( cast ( -a as real ) ),\n" +
" g generated always as ( cast ( -a as double ) ),\n" +
" h generated always as ( cast ( -a as float ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_float( a ) values ( 1.0 )"
);
assertColumnTypes
(
conn,
"T_ND_FLOAT",
new String[][]
{
{ "A", "DOUBLE" },
{ "B", "SMALLINT" },
{ "C", "INTEGER" },
{ "D", "BIGINT" },
{ "E", "DECIMAL(5,0)" },
{ "F", "REAL" },
{ "G", "DOUBLE" },
{ "H", "DOUBLE" },
}
);
assertResults
(
conn,
"select * from t_nd_float order by a",
new String[][]
{
{ "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" },
},
false
);
goodStatement
(
conn,
"create table t_nd_char\n" +
"(\n" +
" a char( 20 ),\n" +
" b generated always as ( cast ( upper( a ) as char( 20 ) ) ),\n" +
" c generated always as ( cast ( upper( a ) as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( upper( a ) as long varchar ) ),\n" +
" e generated always as ( cast ( upper( a ) as clob ) ),\n" +
" f generated always as ( cast( a as date ) ),\n" +
" g generated always as ( cast( '15:09:02' as time ) ),\n" +
" h generated always as ( cast( ( trim( a ) || ' 03:23:34.234' ) as timestamp ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_char( a ) values ( '1994-02-23' )"
);
assertColumnTypes
(
conn,
"T_ND_CHAR",
new String[][]
{
{ "A", "CHAR(20)" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "LONG VARCHAR" },
{ "E", "CLOB(2147483647)" },
{ "F", "DATE" },
{ "G", "TIME NOT NULL" },
{ "H", "TIMESTAMP" },
}
);
assertResults
(
conn,
"select * from t_nd_char order by a",
new String[][]
{
{ "1994-02-23 " , "1994-02-23 ", "1994-02-23 ", "1994-02-23 ", "1994-02-23 ", "1994-02-23", "15:09:02", "1994-02-23 03:23:34.234" },
},
false
);
goodStatement
(
conn,
"create table t_nd_varchar\n" +
"(\n" +
" a varchar( 20 ),\n" +
" b generated always as ( cast ( upper( a ) as char( 20 ) ) ),\n" +
" c generated always as ( cast ( upper( a ) as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( upper( a ) as long varchar ) ),\n" +
" e generated always as ( cast ( upper( a ) as clob ) ),\n" +
" f generated always as ( cast( a as date ) ),\n" +
" g generated always as ( cast( '15:09:02' as time ) ),\n" +
" h generated always as ( cast( ( trim( a ) || ' 03:23:34.234' ) as timestamp ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_varchar( a ) values ( '1994-02-23' )"
);
assertColumnTypes
(
conn,
"T_ND_VARCHAR",
new String[][]
{
{ "A", "VARCHAR(20)" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "LONG VARCHAR" },
{ "E", "CLOB(2147483647)" },
{ "F", "DATE" },
{ "G", "TIME NOT NULL" },
{ "H", "TIMESTAMP" },
}
);
assertResults
(
conn,
"select * from t_nd_varchar order by a",
new String[][]
{
{ "1994-02-23" , "1994-02-23 ", "1994-02-23", "1994-02-23", "1994-02-23", "1994-02-23", "15:09:02", "1994-02-23 03:23:34.234" },
},
false
);
goodStatement
(
conn,
"create table t_nd_longvarchar\n" +
"(\n" +
" a long varchar,\n" +
" b generated always as ( cast ( upper( a ) as char( 20 ) ) ),\n" +
" c generated always as ( cast ( upper( a ) as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( upper( a ) as long varchar ) ),\n" +
" e generated always as ( cast ( upper( a ) as clob ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_longvarchar( a ) values ( 'foo' )"
);
assertColumnTypes
(
conn,
"T_ND_LONGVARCHAR",
new String[][]
{
{ "A", "LONG VARCHAR" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "LONG VARCHAR" },
{ "E", "CLOB(2147483647)" },
}
);
assertResults
(
conn,
"select * from t_nd_longvarchar",
new String[][]
{
{ "foo" , "FOO ", "FOO", "FOO", "FOO", },
},
false
);
goodStatement
(
conn,
"create table t_nd_clob\n" +
"(\n" +
" a clob,\n" +
" b generated always as ( cast ( upper( a ) as char( 20 ) ) ),\n" +
" c generated always as ( cast ( upper( a ) as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( upper( a ) as long varchar ) ),\n" +
" e generated always as ( cast ( upper( a ) as clob ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_clob( a ) values ( 'foo' )"
);
assertColumnTypes
(
conn,
"T_ND_CLOB",
new String[][]
{
{ "A", "CLOB(2147483647)" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "LONG VARCHAR" },
{ "E", "CLOB(2147483647)" },
}
);
assertResults
(
conn,
"select * from t_nd_clob",
new String[][]
{
{ "foo" , "FOO ", "FOO", "FOO", "FOO", },
},
false
);
goodStatement
(
conn,
"create table t_nd_charforbitdata\n" +
"(\n" +
" a char( 4 ) for bit data,\n" +
" b generated always as ( cast ( a as char( 4 ) for bit data ) ),\n" +
" c generated always as ( cast ( a as varchar( 4 ) for bit data ) ),\n" +
" d generated always as ( cast ( a as long varchar for bit data ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_charforbitdata( a ) values ( X'ABCDEFAB' )"
);
assertColumnTypes
(
conn,
"T_ND_CHARFORBITDATA",
new String[][]
{
{ "A", "CHAR (4) FOR BIT DATA" },
{ "B", "CHAR (4) FOR BIT DATA" },
{ "C", "VARCHAR (4) FOR BIT DATA" },
{ "D", "LONG VARCHAR FOR BIT DATA" },
}
);
assertResults
(
conn,
"select * from t_nd_charforbitdata",
new String[][]
{
{ "abcdefab", "abcdefab", "abcdefab", "abcdefab", },
},
false
);
goodStatement
(
conn,
"create table t_nd_varcharforbitdata\n" +
"(\n" +
" a varchar( 4 ) for bit data,\n" +
" b generated always as ( cast ( a as char( 4 ) for bit data ) ),\n" +
" c generated always as ( cast ( a as varchar( 4 ) for bit data ) ),\n" +
" d generated always as ( cast ( a as long varchar for bit data ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_varcharforbitdata( a ) values ( X'ABCDEFAB' )"
);
assertColumnTypes
(
conn,
"T_ND_VARCHARFORBITDATA",
new String[][]
{
{ "A", "VARCHAR (4) FOR BIT DATA" },
{ "B", "CHAR (4) FOR BIT DATA" },
{ "C", "VARCHAR (4) FOR BIT DATA" },
{ "D", "LONG VARCHAR FOR BIT DATA" },
}
);
assertResults
(
conn,
"select * from t_nd_varcharforbitdata",
new String[][]
{
{ "abcdefab", "abcdefab", "abcdefab", "abcdefab", },
},
false
);
goodStatement
(
conn,
"create table t_nd_longvarcharforbitdata\n" +
"(\n" +
" a long varchar for bit data,\n" +
" b generated always as ( cast ( a as char( 4 ) for bit data ) ),\n" +
" c generated always as ( cast ( a as varchar( 4 ) for bit data ) ),\n" +
" d generated always as ( cast ( a as long varchar for bit data ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_longvarcharforbitdata( a ) values ( X'ABCDEFAB' )"
);
assertColumnTypes
(
conn,
"T_ND_LONGVARCHARFORBITDATA",
new String[][]
{
{ "A", "LONG VARCHAR FOR BIT DATA" },
{ "B", "CHAR (4) FOR BIT DATA" },
{ "C", "VARCHAR (4) FOR BIT DATA" },
{ "D", "LONG VARCHAR FOR BIT DATA" },
}
);
assertResults
(
conn,
"select * from t_nd_longvarcharforbitdata",
new String[][]
{
{ "abcdefab", "abcdefab", "abcdefab", "abcdefab", },
},
false
);
goodStatement
(
conn,
"create table t_nd_date\n" +
"(\n" +
" a date,\n" +
" b generated always as ( cast ( a as char( 20 ) ) ),\n" +
" c generated always as ( cast ( a as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( a as date ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_date( a ) values ( date('1994-02-23') )"
);
assertColumnTypes
(
conn,
"T_ND_DATE",
new String[][]
{
{ "A", "DATE" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "DATE" },
}
);
assertResults
(
conn,
"select * from t_nd_date",
new String[][]
{
{ "1994-02-23", "1994-02-23 ", "1994-02-23", "1994-02-23", },
},
false
);
goodStatement
(
conn,
"create table t_nd_time\n" +
"(\n" +
" a time,\n" +
" b generated always as ( cast ( a as char( 20 ) ) ),\n" +
" c generated always as ( cast ( a as varchar( 20 ) ) ),\n" +
" d generated always as ( cast ( a as time ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_time( a ) values ( time('15:09:02') )"
);
assertColumnTypes
(
conn,
"T_ND_TIME",
new String[][]
{
{ "A", "TIME" },
{ "B", "CHAR(20)" },
{ "C", "VARCHAR(20)" },
{ "D", "TIME" },
}
);
assertResults
(
conn,
"select * from t_nd_time",
new String[][]
{
{ "15:09:02", "15:09:02 ", "15:09:02", "15:09:02", },
},
false
);
goodStatement
(
conn,
"create table t_nd_timestamp\n" +
"(\n" +
" a timestamp,\n" +
" b char( 30 ) generated always as ( cast( a as char( 30 ) ) ),\n" +
" c varchar( 30 ) generated always as ( cast ( a as varchar( 30 ) ) ),\n" +
" d timestamp generated always as ( cast ( a as timestamp ) )\n" +
")\n"
);
goodStatement
(
conn,
"insert into t_nd_timestamp( a ) values ( timestamp('1962-09-23 03:23:34.234') )"
);
assertColumnTypes
(
conn,
"T_ND_TIMESTAMP",
new String[][]
{
{ "A", "TIMESTAMP" },
{ "B", "CHAR(30)" },
{ "C", "VARCHAR(30)" },
{ "D", "TIMESTAMP" },
}
);
assertResults
(
conn,
"select * from t_nd_timestamp",
new String[][]
{
{ "1962-09-23 03:23:34.234", "1962-09-23 03:23:34.234 ", "1962-09-23 03:23:34.234", "1962-09-23 03:23:34.234", },
},
false
);
} | void function() throws Exception { Connection conn = getConnection(); ( conn, STR ); goodStatement ( conn, STR ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, } ); assertResults ( conn, STR, new String[][] { { "1", "-1" }, }, false ); ( NEED_EXPLICIT_DATATYPE, STR ); expectCompilationError ( CANT_ADD_IDENTITY, STR ); ( conn, STR ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, } ); assertResults ( conn, STR, new String[][] { { "100", "-100" }, }, false ); ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", "REAL" }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "REAL" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { "1.0" , "-1", "-1", "-1", "-1", "-1.0", "-1.0", "-1.0" }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "DATE" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { STR , STR, STR, STR, STR, STR, STR, STR }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, { "F", "DATE" }, { "G", STR }, { "H", STR }, } ); assertResults ( conn, STR, new String[][] { { STR , STR, STR, STR, STR, STR, STR, STR }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, } ); assertResults ( conn, STR, new String[][] { { "foo" , STR, "FOO", "FOO", "FOO", }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, { "E", STR }, } ); assertResults ( conn, STR, new String[][] { { "foo" , STR, "FOO", "FOO", "FOO", }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", "DATE" }, { "B", STR }, { "C", STR }, { "D", "DATE" }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", "TIME" }, { "B", STR }, { "C", STR }, { "D", "TIME" }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); goodStatement ( conn, STR + "(\n" + STR + STR + STR + STR + ")\n" ); goodStatement ( conn, STR ); assertColumnTypes ( conn, STR, new String[][] { { "A", STR }, { "B", STR }, { "C", STR }, { "D", STR }, } ); assertResults ( conn, STR, new String[][] { { STR, STR, STR, STR, }, }, false ); } | /**
* <p>
* Test that CREATE/ALTER TABLE can omit the column datatype if there is a
* generation clause.
* </p>
*/ | Test that CREATE/ALTER TABLE can omit the column datatype if there is a generation clause. | test_022_omitDatatype | {
"repo_name": "kavin256/Derby",
"path": "java/testing/org/apache/derbyTesting/functionTests/tests/lang/GeneratedColumnsTest.java",
"license": "apache-2.0",
"size": 173723
} | [
"java.sql.Connection"
] | import java.sql.Connection; | import java.sql.*; | [
"java.sql"
] | java.sql; | 2,798,013 |
private Object onFill(DatasetContext context, FillCallback callback, IsFill defaultValue) {
// gets value
Object result = ScriptableUtils.getOptionValue(context, callback);
// checks and transforms result
Object transformed = IsFill.transform(result);
// checks if consistent
if (transformed != null) {
// returns the result
return transformed;
}
// if here, result is null
// then checks and returns default
return IsFill.toObject(Checker.checkAndGetIfValid(defaultValue, "Default fill argument"));
}
/**
* Returns a {@link Stepped} when the callback has been activated.
*
* @param context native object as context.
* @param callback stepped callback instance
* @param defaultValue default value of stepped
* @return a object property value, as {@link Stepped} | Object function(DatasetContext context, FillCallback callback, IsFill defaultValue) { Object result = ScriptableUtils.getOptionValue(context, callback); Object transformed = IsFill.transform(result); if (transformed != null) { return transformed; } return IsFill.toObject(Checker.checkAndGetIfValid(defaultValue, STR)); } /** * Returns a {@link Stepped} when the callback has been activated. * * @param context native object as context. * @param callback stepped callback instance * @param defaultValue default value of stepped * @return a object property value, as {@link Stepped} | /**
* Returns a object which can be a boolean, integer, string or {@link IsFill} when the callback has been activated.
*
* @param context native object as context.
* @param callback fill callback instance
* @param defaultValue default value of fill mode
* @return a object property value
*/ | Returns a object which can be a boolean, integer, string or <code>IsFill</code> when the callback has been activated | onFill | {
"repo_name": "pepstock-org/Charba",
"path": "src/org/pepstock/charba/client/configuration/Line.java",
"license": "apache-2.0",
"size": 27516
} | [
"org.pepstock.charba.client.callbacks.DatasetContext",
"org.pepstock.charba.client.callbacks.FillCallback",
"org.pepstock.charba.client.callbacks.ScriptableUtils",
"org.pepstock.charba.client.commons.Checker",
"org.pepstock.charba.client.enums.IsFill",
"org.pepstock.charba.client.enums.Stepped"
] | import org.pepstock.charba.client.callbacks.DatasetContext; import org.pepstock.charba.client.callbacks.FillCallback; import org.pepstock.charba.client.callbacks.ScriptableUtils; import org.pepstock.charba.client.commons.Checker; import org.pepstock.charba.client.enums.IsFill; import org.pepstock.charba.client.enums.Stepped; | import org.pepstock.charba.client.callbacks.*; import org.pepstock.charba.client.commons.*; import org.pepstock.charba.client.enums.*; | [
"org.pepstock.charba"
] | org.pepstock.charba; | 2,031,274 |
public boolean validate(RegistryEntry registryEntry, String pid, ConfigID id, List<? extends ConfigElement> elements) {
Map<String, ConfigElementList> conflictedElementLists = generateConflictMap(registryEntry, elements);
if (conflictedElementLists.isEmpty()) {
return true;
}
logRegistryEntry(registryEntry);
String validationMessage = generateCollisionMessage(pid, id, registryEntry, conflictedElementLists);
Tr.audit(tc, "info.config.conflict", validationMessage);
return false;
} | boolean function(RegistryEntry registryEntry, String pid, ConfigID id, List<? extends ConfigElement> elements) { Map<String, ConfigElementList> conflictedElementLists = generateConflictMap(registryEntry, elements); if (conflictedElementLists.isEmpty()) { return true; } logRegistryEntry(registryEntry); String validationMessage = generateCollisionMessage(pid, id, registryEntry, conflictedElementLists); Tr.audit(tc, STR, validationMessage); return false; } | /**
* Valid configuration elements. If a validation problem is found, generate a validation
* message and emit this as a trace warning. A validation message, if generated, will
* usually be a multi-line message, with a half-dozen lines or more per problem which
* is detected.
*
* @param registryEntry The registry entry associated with the PID of the configuration elements.
* @param pid TBD
* @param id TBD
* @param elements The configuration elements which are to be validated.
*
* @return True or false telling if the configuration elements are valid.
*/ | Valid configuration elements. If a validation problem is found, generate a validation message and emit this as a trace warning. A validation message, if generated, will usually be a multi-line message, with a half-dozen lines or more per problem which is detected | validate | {
"repo_name": "OpenLiberty/open-liberty",
"path": "dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ConfigValidator.java",
"license": "epl-1.0",
"size": 18992
} | [
"com.ibm.websphere.ras.Tr",
"com.ibm.ws.config.admin.ConfigID",
"com.ibm.ws.config.xml.internal.MetaTypeRegistry",
"java.util.List",
"java.util.Map"
] | import com.ibm.websphere.ras.Tr; import com.ibm.ws.config.admin.ConfigID; import com.ibm.ws.config.xml.internal.MetaTypeRegistry; import java.util.List; import java.util.Map; | import com.ibm.websphere.ras.*; import com.ibm.ws.config.admin.*; import com.ibm.ws.config.xml.internal.*; import java.util.*; | [
"com.ibm.websphere",
"com.ibm.ws",
"java.util"
] | com.ibm.websphere; com.ibm.ws; java.util; | 2,571,407 |
Connection getUnderLyingConnection() throws DataException; | Connection getUnderLyingConnection() throws DataException; | /**
* Returns the data base connection on which the data base subsystem builds
* its queries.
*
* @return the underlying data base connection as a java.sql.Connection
* objec
* @throws DataException
* if the underlying data base connection could not be accessed
*/ | Returns the data base connection on which the data base subsystem builds its queries | getUnderLyingConnection | {
"repo_name": "dsp/projectsonar",
"path": "src/edu/kit/ipd/sonar/server/Database.java",
"license": "gpl-2.0",
"size": 2570
} | [
"java.sql.Connection"
] | import java.sql.Connection; | import java.sql.*; | [
"java.sql"
] | java.sql; | 132,952 |
public void setLayer(VectorLayer aLayer) {
_layer = aLayer;
LabelSet labelSet = _layer.getLabelSet();
_font = labelSet.getLabelFont();
_color = labelSet.getLabelColor();
_shadowColor = labelSet.getShadowColor();
int i;
//Set fields
this.jComboBox_Field.removeAllItems();
for (i = 0; i < _layer.getFieldNumber(); i++) {
this.jComboBox_Field.addItem(_layer.getFieldName(i));
}
if (this.jComboBox_Field.getItemCount() > 0) {
if (labelSet.getFieldName() != null && !labelSet.getFieldName().isEmpty()) {
this.jComboBox_Field.setSelectedItem(labelSet.getFieldName());
} else {
this.jComboBox_Field.setSelectedIndex(0);
}
}
//Set align type
this.jComboBox_Align.removeAllItems();
for (AlignType align : AlignType.values()) {
this.jComboBox_Align.addItem(align.toString());
}
this.jComboBox_Align.setSelectedItem(labelSet.getLabelAlignType().toString());
//Set offset
this.jTextField_XOffset.setText(String.valueOf(labelSet.getXOffset()));
this.jTextField_YOffset.setText(String.valueOf(labelSet.getYOffset()));
//Set avoid collision
this.jCheckBox_AvoidCollision.setSelected(labelSet.isAvoidCollision());
//Set draw shadow
this.jCheckBox_ShadowColor.setSelected(labelSet.isDrawShadow());
//Set color by legend
this.jCheckBox_ColorByLegend.setSelected(labelSet.isColorByLegend());
//Set contour dynamic label
this.jCheckBox_ContourDynamic.setSelected(labelSet.isDynamicContourLabel());
if (_layer.getShapeType() == ShapeTypes.Polyline) {
this.jCheckBox_ContourDynamic.setEnabled(true);
} else {
this.jCheckBox_ContourDynamic.setEnabled(false);
}
//Set auto decimal digits
this.jCheckBox_AutoDecimal.setSelected(labelSet.isAutoDecimal());
autoDecimal_CheckedChanged();
} | void function(VectorLayer aLayer) { _layer = aLayer; LabelSet labelSet = _layer.getLabelSet(); _font = labelSet.getLabelFont(); _color = labelSet.getLabelColor(); _shadowColor = labelSet.getShadowColor(); int i; this.jComboBox_Field.removeAllItems(); for (i = 0; i < _layer.getFieldNumber(); i++) { this.jComboBox_Field.addItem(_layer.getFieldName(i)); } if (this.jComboBox_Field.getItemCount() > 0) { if (labelSet.getFieldName() != null && !labelSet.getFieldName().isEmpty()) { this.jComboBox_Field.setSelectedItem(labelSet.getFieldName()); } else { this.jComboBox_Field.setSelectedIndex(0); } } this.jComboBox_Align.removeAllItems(); for (AlignType align : AlignType.values()) { this.jComboBox_Align.addItem(align.toString()); } this.jComboBox_Align.setSelectedItem(labelSet.getLabelAlignType().toString()); this.jTextField_XOffset.setText(String.valueOf(labelSet.getXOffset())); this.jTextField_YOffset.setText(String.valueOf(labelSet.getYOffset())); this.jCheckBox_AvoidCollision.setSelected(labelSet.isAvoidCollision()); this.jCheckBox_ShadowColor.setSelected(labelSet.isDrawShadow()); this.jCheckBox_ColorByLegend.setSelected(labelSet.isColorByLegend()); this.jCheckBox_ContourDynamic.setSelected(labelSet.isDynamicContourLabel()); if (_layer.getShapeType() == ShapeTypes.Polyline) { this.jCheckBox_ContourDynamic.setEnabled(true); } else { this.jCheckBox_ContourDynamic.setEnabled(false); } this.jCheckBox_AutoDecimal.setSelected(labelSet.isAutoDecimal()); autoDecimal_CheckedChanged(); } | /**
* Set vector layer
*
* @param aLayer The vector layer
*/ | Set vector layer | setLayer | {
"repo_name": "meteoinfo/meteoinfolib",
"path": "src/org/meteoinfo/layer/FrmLabelSet.java",
"license": "lgpl-3.0",
"size": 30009
} | [
"org.meteoinfo.data.mapdata.Field",
"org.meteoinfo.legend.AlignType",
"org.meteoinfo.shape.ShapeTypes"
] | import org.meteoinfo.data.mapdata.Field; import org.meteoinfo.legend.AlignType; import org.meteoinfo.shape.ShapeTypes; | import org.meteoinfo.data.mapdata.*; import org.meteoinfo.legend.*; import org.meteoinfo.shape.*; | [
"org.meteoinfo.data",
"org.meteoinfo.legend",
"org.meteoinfo.shape"
] | org.meteoinfo.data; org.meteoinfo.legend; org.meteoinfo.shape; | 199,737 |
public static byte[] getBytes(URL url) throws IOException {
final String path = url.getPath();
final File file = new File(path);
if (file.exists()) {
return getFileBytes(file);
}
return null;
} | static byte[] function(URL url) throws IOException { final String path = url.getPath(); final File file = new File(path); if (file.exists()) { return getFileBytes(file); } return null; } | /**
* Common code for getting the bytes of a url.
*
* @param url the url to read.
*/ | Common code for getting the bytes of a url | getBytes | {
"repo_name": "jtietema/telegraph",
"path": "app/libs/asmack-android-16-source/org/jivesoftware/smackx/packet/VCard.java",
"license": "gpl-3.0",
"size": 27081
} | [
"java.io.File",
"java.io.IOException"
] | import java.io.File; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,216,259 |
public void setAttributes( int hourOfDay, int minute, boolean is24, TextView timeView ) {
this.hourOfDay = hourOfDay;
this.minute = minute;
this.is24 = is24;
this.timeView = timeView;
} | void function( int hourOfDay, int minute, boolean is24, TextView timeView ) { this.hourOfDay = hourOfDay; this.minute = minute; this.is24 = is24; this.timeView = timeView; } | /**
* Set attributes.
*
* @param hourOfDay hour
* @param minute minute
* @param is24 format
* @param timeView view
*/ | Set attributes | setAttributes | {
"repo_name": "gabrielmancilla/mtisig",
"path": "geopaparazzilibrary/src/eu/geopaparazzi/library/forms/FormTimePickerFragment.java",
"license": "gpl-3.0",
"size": 2353
} | [
"android.widget.TextView"
] | import android.widget.TextView; | import android.widget.*; | [
"android.widget"
] | android.widget; | 2,681,055 |
private void notifyLightListeners(int group, LightEvent event) {
// check group number
if (1 > group || group > 4) {
throw new IllegalArgumentException(
"The group number must be between 1 and 4");
}
// notify listeners
for (LightListener listener : lightListeners[group - 1]) {
listener.lightsChanged(event);
}
} | void function(int group, LightEvent event) { if (1 > group group > 4) { throw new IllegalArgumentException( STR); } for (LightListener listener : lightListeners[group - 1]) { listener.lightsChanged(event); } } | /**
* This function sends a LightEvent to all listeners listening on a certain
* group of lights.
*
* @param group
* is the number of the group to notify
* @param event
* is the LightEvent to send to all listeners
* @throws IllegalArgumentException
* if group is not between 1 and 4
*/ | This function sends a LightEvent to all listeners listening on a certain group of lights | notifyLightListeners | {
"repo_name": "stoman/MilightAPI",
"path": "src/de/toman/milight/WiFiBox.java",
"license": "mit",
"size": 39506
} | [
"de.toman.milight.events.LightEvent",
"de.toman.milight.events.LightListener"
] | import de.toman.milight.events.LightEvent; import de.toman.milight.events.LightListener; | import de.toman.milight.events.*; | [
"de.toman.milight"
] | de.toman.milight; | 2,256,138 |
public void dragTo(float fromX, float toX, float fromY,
float toY, int stepCount, long downTime) {
float x = fromX;
float y = fromY;
float yStep = (toY - fromY) / stepCount;
float xStep = (toX - fromX) / stepCount;
for (int i = 0; i < stepCount; ++i) {
y += yStep;
x += xStep;
long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(downTime, eventTime,
MotionEvent.ACTION_MOVE, x, y, 0);
dispatchTouchEvent(event);
}
} | void function(float fromX, float toX, float fromY, float toY, int stepCount, long downTime) { float x = fromX; float y = fromY; float yStep = (toY - fromY) / stepCount; float xStep = (toX - fromX) / stepCount; for (int i = 0; i < stepCount; ++i) { y += yStep; x += xStep; long eventTime = SystemClock.uptimeMillis(); MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0); dispatchTouchEvent(event); } } | /**
* Drags / moves (synchronously) to the specified coordinates. Normally preceeded by
* dragStart() and followed by dragEnd()
*
* @param fromX
* @param toX
* @param fromY
* @param toY
* @param stepCount
* @param downTime (in ms)
* @see TouchUtils
*/ | Drags / moves (synchronously) to the specified coordinates. Normally preceeded by dragStart() and followed by dragEnd() | dragTo | {
"repo_name": "zcbenz/cefode-chromium",
"path": "content/public/test/android/javatests/src/org/chromium/content/browser/test/util/TouchCommon.java",
"license": "bsd-3-clause",
"size": 7876
} | [
"android.os.SystemClock",
"android.view.MotionEvent"
] | import android.os.SystemClock; import android.view.MotionEvent; | import android.os.*; import android.view.*; | [
"android.os",
"android.view"
] | android.os; android.view; | 1,136,186 |
public List<Message> getValidationMessages() {
return this.validationMessages;
} | List<Message> function() { return this.validationMessages; } | /**
* Return validation message for given severity.
*
* Return either associated message for given severity or null in case
* that there is no message with given severity.
*/ | Return validation message for given severity. Return either associated message for given severity or null in case that there is no message with given severity | getValidationMessages | {
"repo_name": "vybs/sqoop-on-spark",
"path": "common/src/main/java/org/apache/sqoop/model/MValidatedElement.java",
"license": "apache-2.0",
"size": 3192
} | [
"java.util.List",
"org.apache.sqoop.validation.Message"
] | import java.util.List; import org.apache.sqoop.validation.Message; | import java.util.*; import org.apache.sqoop.validation.*; | [
"java.util",
"org.apache.sqoop"
] | java.util; org.apache.sqoop; | 1,137,481 |
Date resolve(String duedateDescription, ClockReader clockReader, TimeZone timeZone);
| Date resolve(String duedateDescription, ClockReader clockReader, TimeZone timeZone); | /**
* Resolves a due date using the specified time zone (if supported)
*
* @param duedateDescription
* An original schedule string in either ISO or CRON format
* @param clockReader
* The time provider
* @param timeZone
* The time zone to use in the calculations
* @return The due date
*/ | Resolves a due date using the specified time zone (if supported) | resolve | {
"repo_name": "motorina0/flowable-engine",
"path": "modules/flowable-engine/src/main/java/org/flowable/engine/impl/calendar/AdvancedSchedulerResolver.java",
"license": "apache-2.0",
"size": 1325
} | [
"java.util.Date",
"java.util.TimeZone",
"org.flowable.engine.common.runtime.ClockReader"
] | import java.util.Date; import java.util.TimeZone; import org.flowable.engine.common.runtime.ClockReader; | import java.util.*; import org.flowable.engine.common.runtime.*; | [
"java.util",
"org.flowable.engine"
] | java.util; org.flowable.engine; | 1,096,183 |
public InboundPatientDiscovery getInboundPatientDiscovery() {
return this.inboundPatientDiscovery;
} | InboundPatientDiscovery function() { return this.inboundPatientDiscovery; } | /**
* Gets the inbound patient discovery dependency.
*
* @return the inbound patient discovery
*/ | Gets the inbound patient discovery dependency | getInboundPatientDiscovery | {
"repo_name": "AurionProject/Aurion",
"path": "Product/Production/Gateway/PatientDiscovery_10/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/_10/gateway/ws/NhinPatientDiscovery.java",
"license": "bsd-3-clause",
"size": 6362
} | [
"gov.hhs.fha.nhinc.patientdiscovery.inbound.InboundPatientDiscovery"
] | import gov.hhs.fha.nhinc.patientdiscovery.inbound.InboundPatientDiscovery; | import gov.hhs.fha.nhinc.patientdiscovery.inbound.*; | [
"gov.hhs.fha"
] | gov.hhs.fha; | 2,321,358 |
@Override
public boolean isGranted(NodeBase node, String user, int permissions) throws PrincipalAdapterException, DatabaseException {
List<String> roles = CommonAuthModule.getPrincipalAdapter().getRolesByUser(user);
return isGranted(node, user, new HashSet<String>(roles), permissions);
}
| boolean function(NodeBase node, String user, int permissions) throws PrincipalAdapterException, DatabaseException { List<String> roles = CommonAuthModule.getPrincipalAdapter().getRolesByUser(user); return isGranted(node, user, new HashSet<String>(roles), permissions); } | /**
* Check for permissions.
*/ | Check for permissions | isGranted | {
"repo_name": "papamas/DMS-KANGREG-XI-MANADO",
"path": "src/main/java/com/openkm/module/db/stuff/DbRecursiveAccessManager.java",
"license": "gpl-3.0",
"size": 5889
} | [
"com.openkm.core.DatabaseException",
"com.openkm.dao.bean.NodeBase",
"com.openkm.module.common.CommonAuthModule",
"com.openkm.principal.PrincipalAdapterException",
"java.util.HashSet",
"java.util.List"
] | import com.openkm.core.DatabaseException; import com.openkm.dao.bean.NodeBase; import com.openkm.module.common.CommonAuthModule; import com.openkm.principal.PrincipalAdapterException; import java.util.HashSet; import java.util.List; | import com.openkm.core.*; import com.openkm.dao.bean.*; import com.openkm.module.common.*; import com.openkm.principal.*; import java.util.*; | [
"com.openkm.core",
"com.openkm.dao",
"com.openkm.module",
"com.openkm.principal",
"java.util"
] | com.openkm.core; com.openkm.dao; com.openkm.module; com.openkm.principal; java.util; | 186,016 |
@Test(groups="fast")
public void testEventOneWithErrors() throws Exception {
MockRoundtrip trip = new MockRoundtrip(StripesTestFixture.getServletContext(), getClass());
trip.addParameter("numberZero", "100");
trip.addParameter("numberOne", ""); // required field for event one
trip.execute("eventOne");
ValidationFlowTest test = trip.getActionBean(getClass());
Assert.assertEquals(0, test.validateAlwaysRan);
Assert.assertEquals(0, test.validateOneRan);
Assert.assertEquals(0, test.validateTwoRan);
Assert.assertEquals(test.numberZero, 100);
Assert.assertEquals(1, test.getContext().getValidationErrors().size());
} | @Test(groups="fast") void function() throws Exception { MockRoundtrip trip = new MockRoundtrip(StripesTestFixture.getServletContext(), getClass()); trip.addParameter(STR, "100"); trip.addParameter(STR, STReventOne"); ValidationFlowTest test = trip.getActionBean(getClass()); Assert.assertEquals(0, test.validateAlwaysRan); Assert.assertEquals(0, test.validateOneRan); Assert.assertEquals(0, test.validateTwoRan); Assert.assertEquals(test.numberZero, 100); Assert.assertEquals(1, test.getContext().getValidationErrors().size()); } | /**
* Tests that a required field error is raised this time for numberOne which is only
* required for this event. Again this single error should prevent both validateAlways
* and validateOne from running.
*/ | Tests that a required field error is raised this time for numberOne which is only required for this event. Again this single error should prevent both validateAlways and validateOne from running | testEventOneWithErrors | {
"repo_name": "mcs/Stripes",
"path": "tests/src/net/sourceforge/stripes/validation/ValidationFlowTest.java",
"license": "apache-2.0",
"size": 9056
} | [
"net.sourceforge.stripes.StripesTestFixture",
"net.sourceforge.stripes.mock.MockRoundtrip",
"org.testng.Assert",
"org.testng.annotations.Test"
] | import net.sourceforge.stripes.StripesTestFixture; import net.sourceforge.stripes.mock.MockRoundtrip; import org.testng.Assert; import org.testng.annotations.Test; | import net.sourceforge.stripes.*; import net.sourceforge.stripes.mock.*; import org.testng.*; import org.testng.annotations.*; | [
"net.sourceforge.stripes",
"org.testng",
"org.testng.annotations"
] | net.sourceforge.stripes; org.testng; org.testng.annotations; | 480,837 |
public void setUserData(String key, UserData<Object> data) {
synchronized (this.userDataLock) {
if (this.userData == null) {
this.userData = new TreeMap<>();
}
this.userData.put(key, data);
}
} | void function(String key, UserData<Object> data) { synchronized (this.userDataLock) { if (this.userData == null) { this.userData = new TreeMap<>(); } this.userData.put(key, data); } } | /**
* Stores arbitrary {@link UserData}.
*
* @param key
* The key to used to identify the data.
* @param data
* The user data.
*/ | Stores arbitrary <code>UserData</code> | setUserData | {
"repo_name": "aborg0/rapidminer-studio",
"path": "src/main/java/com/rapidminer/operator/ExecutionUnit.java",
"license": "agpl-3.0",
"size": 32040
} | [
"java.util.TreeMap"
] | import java.util.TreeMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,070,130 |
public static void setItemLore(final ItemStack stack, final List<String> lore) {
if (stack == null)
return;
NBTTagCompound nbt = stack.getTagCompound();
if (nbt == null)
nbt = new NBTTagCompound();
final NBTTagList l = new NBTTagList();
for (final String s : lore)
l.appendTag(new NBTTagString(s));
NBTTagCompound display = nbt.getCompoundTag("display");
if (display == null)
display = new NBTTagCompound();
display.setTag("Lore", l);
nbt.setTag("display", display);
stack.setTagCompound(nbt);
} | static void function(final ItemStack stack, final List<String> lore) { if (stack == null) return; NBTTagCompound nbt = stack.getTagCompound(); if (nbt == null) nbt = new NBTTagCompound(); final NBTTagList l = new NBTTagList(); for (final String s : lore) l.appendTag(new NBTTagString(s)); NBTTagCompound display = nbt.getCompoundTag(STR); if (display == null) display = new NBTTagCompound(); display.setTag("Lore", l); nbt.setTag(STR, display); stack.setTagCompound(nbt); } | /**
* Sets the lore of the ItemStack.
*
* @param stack
* @param lore
*/ | Sets the lore of the ItemStack | setItemLore | {
"repo_name": "OreCruncher/ThermalRecycling",
"path": "src/main/java/org/blockartistry/mod/ThermalRecycling/util/ItemStackHelper.java",
"license": "mit",
"size": 11275
} | [
"java.util.List",
"net.minecraft.item.ItemStack",
"net.minecraft.nbt.NBTTagCompound",
"net.minecraft.nbt.NBTTagList",
"net.minecraft.nbt.NBTTagString"
] | import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; | import java.util.*; import net.minecraft.item.*; import net.minecraft.nbt.*; | [
"java.util",
"net.minecraft.item",
"net.minecraft.nbt"
] | java.util; net.minecraft.item; net.minecraft.nbt; | 1,394,334 |
public java.util.List<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI> getSubterm_lists_MakeListHLAPI(){
java.util.List<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI> retour = new ArrayList<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI>();
for (Term elemnt : getSubterm()) {
if(elemnt.getClass().equals(fr.lip6.move.pnml.hlpn.lists.impl.MakeListImpl.class)){
retour.add(new fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI(
(fr.lip6.move.pnml.hlpn.lists.MakeList)elemnt
));
}
}
return retour;
}
| java.util.List<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI> function(){ java.util.List<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI> retour = new ArrayList<fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI>(); for (Term elemnt : getSubterm()) { if(elemnt.getClass().equals(fr.lip6.move.pnml.hlpn.lists.impl.MakeListImpl.class)){ retour.add(new fr.lip6.move.pnml.hlpn.lists.hlapi.MakeListHLAPI( (fr.lip6.move.pnml.hlpn.lists.MakeList)elemnt )); } } return retour; } | /**
* This accessor return a list of encapsulated subelement, only of MakeListHLAPI kind.
* WARNING : this method can creates a lot of new object in memory.
*/ | This accessor return a list of encapsulated subelement, only of MakeListHLAPI kind. WARNING : this method can creates a lot of new object in memory | getSubterm_lists_MakeListHLAPI | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/strings/hlapi/LessThanOrEqualHLAPI.java",
"license": "epl-1.0",
"size": 108661
} | [
"fr.lip6.move.pnml.hlpn.terms.Term",
"java.util.ArrayList",
"java.util.List"
] | import fr.lip6.move.pnml.hlpn.terms.Term; import java.util.ArrayList; import java.util.List; | import fr.lip6.move.pnml.hlpn.terms.*; import java.util.*; | [
"fr.lip6.move",
"java.util"
] | fr.lip6.move; java.util; | 2,815,414 |
public static Predicate<SecurityGroup> nameMatches(final Predicate<String> name) {
checkNotNull(name, "name must be defined"); | static Predicate<SecurityGroup> function(final Predicate<String> name) { checkNotNull(name, STR); | /**
* matches name of the given security group
*
* @param name
* @return predicate that matches name
*/ | matches name of the given security group | nameMatches | {
"repo_name": "yanzhijun/jclouds-aliyun",
"path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/SecurityGroupPredicates.java",
"license": "apache-2.0",
"size": 7765
} | [
"com.google.common.base.Preconditions",
"com.google.common.base.Predicate",
"org.jclouds.cloudstack.domain.SecurityGroup"
] | import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import org.jclouds.cloudstack.domain.SecurityGroup; | import com.google.common.base.*; import org.jclouds.cloudstack.domain.*; | [
"com.google.common",
"org.jclouds.cloudstack"
] | com.google.common; org.jclouds.cloudstack; | 2,089,309 |
@Test
public void testListOutputJobFiles() throws URISyntaxException, PortalServiceException {
final BlobStore mockBlobStore = context.mock(BlobStore.class);
final BlobMetadataImpl mockStorageMetadata1 = context.mock(BlobMetadataImpl.class, "mockStorageMetadata1");
final BlobMetadataImpl mockStorageMetadata2 = context.mock(BlobMetadataImpl.class, "mockStorageMetadata2");
final BlobMetadataImpl mockStorageMetadata3 = context.mock(BlobMetadataImpl.class, "mockStorageMetadata3");
final MutableContentMetadata mockObj1ContentMetadata = context.mock(MutableContentMetadata.class, "mockObj1Md");
final MutableContentMetadata mockObj2ContentMetadata = context.mock(MutableContentMetadata.class, "mockObj2Md");
final MutableContentMetadata mockObj3ContentMetadata = context.mock(MutableContentMetadata.class, "mockObj3Md");
final PageSet<? extends StorageMetadata> mockPageSet = context.mock(PageSet.class);
LinkedList<MutableBlobMetadataImpl> ls = new LinkedList<>();
ls.add(context.mock(MutableBlobMetadataImpl.class, "mockObj1"));
ls.add(context.mock(MutableBlobMetadataImpl.class, "mockObj2"));
final String obj1Key = "key/obj1";
final String obj1Bucket = "bucket1";
final long obj1Length = 1234L;
final String obj2Key = "key/obj2";
final String obj2Bucket = "bucket2";
final long obj2Length = 4567L;
context.checking(new Expectations() {
{
oneOf(mockBlobStoreContext).close();
oneOf(mockBlobStoreContext).getBlobStore();
will(returnValue(mockBlobStore));
oneOf(mockBlobStore).list(with(equal(bucket)), with(any(ListContainerOptions.class)));
will(returnValue(mockPageSet));
allowing(mockPageSet).getNextMarker();
will(returnValue(null));
allowing(mockPageSet).iterator();
will(returnValue(Arrays.asList(mockStorageMetadata1, mockStorageMetadata2, mockStorageMetadata3).iterator()));
allowing(mockStorageMetadata1).getName();
will(returnValue(obj1Key));
allowing(mockStorageMetadata1).getUri();
will(returnValue(new URI(obj1Bucket)));
allowing(mockStorageMetadata1).getContentMetadata();
will(returnValue(mockObj1ContentMetadata));
allowing(mockStorageMetadata1).getType();
will(returnValue(StorageType.BLOB));
allowing(mockObj1ContentMetadata).getContentLength();
will(returnValue(obj1Length));
allowing(mockStorageMetadata1).getETag();
will(returnValue("sadgafsadfa"));
allowing(mockStorageMetadata2).getName();
will(returnValue(obj2Key));
allowing(mockStorageMetadata2).getUri();
will(returnValue(new URI(obj2Bucket)));
allowing(mockStorageMetadata2).getContentMetadata();
will(returnValue(mockObj2ContentMetadata));
allowing(mockStorageMetadata2).getType();
will(returnValue(StorageType.BLOB));
allowing(mockObj2ContentMetadata).getContentLength();
will(returnValue(obj2Length));
allowing(mockStorageMetadata2).getETag();
will(returnValue("mocoqqwiiluhqw"));
allowing(mockStorageMetadata3).getContentMetadata();
will(returnValue(mockObj3ContentMetadata));
allowing(mockStorageMetadata3).getType();
will(returnValue(StorageType.FOLDER));
}
});
CloudFileInformation[] fileInfo = service.listJobFiles(job);
Assert.assertNotNull(fileInfo);
Assert.assertEquals(ls.size(), fileInfo.length);
Assert.assertEquals(obj1Key, fileInfo[0].getCloudKey());
Assert.assertEquals(obj1Length, fileInfo[0].getSize());
Assert.assertEquals(obj2Key, fileInfo[1].getCloudKey());
Assert.assertEquals(obj2Length, fileInfo[1].getSize());
} | void function() throws URISyntaxException, PortalServiceException { final BlobStore mockBlobStore = context.mock(BlobStore.class); final BlobMetadataImpl mockStorageMetadata1 = context.mock(BlobMetadataImpl.class, STR); final BlobMetadataImpl mockStorageMetadata2 = context.mock(BlobMetadataImpl.class, STR); final BlobMetadataImpl mockStorageMetadata3 = context.mock(BlobMetadataImpl.class, STR); final MutableContentMetadata mockObj1ContentMetadata = context.mock(MutableContentMetadata.class, STR); final MutableContentMetadata mockObj2ContentMetadata = context.mock(MutableContentMetadata.class, STR); final MutableContentMetadata mockObj3ContentMetadata = context.mock(MutableContentMetadata.class, STR); final PageSet<? extends StorageMetadata> mockPageSet = context.mock(PageSet.class); LinkedList<MutableBlobMetadataImpl> ls = new LinkedList<>(); ls.add(context.mock(MutableBlobMetadataImpl.class, STR)); ls.add(context.mock(MutableBlobMetadataImpl.class, STR)); final String obj1Key = STR; final String obj1Bucket = STR; final long obj1Length = 1234L; final String obj2Key = STR; final String obj2Bucket = STR; final long obj2Length = 4567L; context.checking(new Expectations() { { oneOf(mockBlobStoreContext).close(); oneOf(mockBlobStoreContext).getBlobStore(); will(returnValue(mockBlobStore)); oneOf(mockBlobStore).list(with(equal(bucket)), with(any(ListContainerOptions.class))); will(returnValue(mockPageSet)); allowing(mockPageSet).getNextMarker(); will(returnValue(null)); allowing(mockPageSet).iterator(); will(returnValue(Arrays.asList(mockStorageMetadata1, mockStorageMetadata2, mockStorageMetadata3).iterator())); allowing(mockStorageMetadata1).getName(); will(returnValue(obj1Key)); allowing(mockStorageMetadata1).getUri(); will(returnValue(new URI(obj1Bucket))); allowing(mockStorageMetadata1).getContentMetadata(); will(returnValue(mockObj1ContentMetadata)); allowing(mockStorageMetadata1).getType(); will(returnValue(StorageType.BLOB)); allowing(mockObj1ContentMetadata).getContentLength(); will(returnValue(obj1Length)); allowing(mockStorageMetadata1).getETag(); will(returnValue(STR)); allowing(mockStorageMetadata2).getName(); will(returnValue(obj2Key)); allowing(mockStorageMetadata2).getUri(); will(returnValue(new URI(obj2Bucket))); allowing(mockStorageMetadata2).getContentMetadata(); will(returnValue(mockObj2ContentMetadata)); allowing(mockStorageMetadata2).getType(); will(returnValue(StorageType.BLOB)); allowing(mockObj2ContentMetadata).getContentLength(); will(returnValue(obj2Length)); allowing(mockStorageMetadata2).getETag(); will(returnValue(STR)); allowing(mockStorageMetadata3).getContentMetadata(); will(returnValue(mockObj3ContentMetadata)); allowing(mockStorageMetadata3).getType(); will(returnValue(StorageType.FOLDER)); } }); CloudFileInformation[] fileInfo = service.listJobFiles(job); Assert.assertNotNull(fileInfo); Assert.assertEquals(ls.size(), fileInfo.length); Assert.assertEquals(obj1Key, fileInfo[0].getCloudKey()); Assert.assertEquals(obj1Length, fileInfo[0].getSize()); Assert.assertEquals(obj2Key, fileInfo[1].getCloudKey()); Assert.assertEquals(obj2Length, fileInfo[1].getSize()); } | /**
* Tests that requests for listing files successfully call all dependencies
* @throws URISyntaxException
* @throws PortalServiceException
*/ | Tests that requests for listing files successfully call all dependencies | testListOutputJobFiles | {
"repo_name": "GeoscienceAustralia/portal-core",
"path": "src/test/java/org/auscope/portal/core/services/cloud/TestCloudStorageService.java",
"license": "lgpl-3.0",
"size": 17746
} | [
"java.net.URISyntaxException",
"java.util.Arrays",
"java.util.LinkedList",
"org.auscope.portal.core.cloud.CloudFileInformation",
"org.auscope.portal.core.services.PortalServiceException",
"org.jclouds.blobstore.BlobStore",
"org.jclouds.blobstore.domain.PageSet",
"org.jclouds.blobstore.domain.StorageMetadata",
"org.jclouds.blobstore.domain.StorageType",
"org.jclouds.blobstore.domain.internal.BlobMetadataImpl",
"org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl",
"org.jclouds.blobstore.options.ListContainerOptions",
"org.jclouds.io.MutableContentMetadata",
"org.jmock.Expectations",
"org.junit.Assert"
] | import java.net.URISyntaxException; import java.util.Arrays; import java.util.LinkedList; import org.auscope.portal.core.cloud.CloudFileInformation; import org.auscope.portal.core.services.PortalServiceException; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.internal.BlobMetadataImpl; import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.io.MutableContentMetadata; import org.jmock.Expectations; import org.junit.Assert; | import java.net.*; import java.util.*; import org.auscope.portal.core.cloud.*; import org.auscope.portal.core.services.*; import org.jclouds.blobstore.*; import org.jclouds.blobstore.domain.*; import org.jclouds.blobstore.domain.internal.*; import org.jclouds.blobstore.options.*; import org.jclouds.io.*; import org.jmock.*; import org.junit.*; | [
"java.net",
"java.util",
"org.auscope.portal",
"org.jclouds.blobstore",
"org.jclouds.io",
"org.jmock",
"org.junit"
] | java.net; java.util; org.auscope.portal; org.jclouds.blobstore; org.jclouds.io; org.jmock; org.junit; | 1,895,361 |
public static List<RingInstanceDetails> awaitRingHealthy(IInstance src)
{
return awaitRing(src, "Timeout waiting for ring to become healthy",
ring ->
ring.stream().allMatch(ClusterUtils::isRingInstanceDetailsHealthy));
} | static List<RingInstanceDetails> function(IInstance src) { return awaitRing(src, STR, ring -> ring.stream().allMatch(ClusterUtils::isRingInstanceDetailsHealthy)); } | /**
* Wait for the ring to only have instances that are Up and Normal.
*
* @param src instance to check on
* @return the ring
*/ | Wait for the ring to only have instances that are Up and Normal | awaitRingHealthy | {
"repo_name": "aholmberg/cassandra",
"path": "test/distributed/org/apache/cassandra/distributed/shared/ClusterUtils.java",
"license": "apache-2.0",
"size": 32254
} | [
"java.util.List",
"org.apache.cassandra.distributed.api.IInstance"
] | import java.util.List; import org.apache.cassandra.distributed.api.IInstance; | import java.util.*; import org.apache.cassandra.distributed.api.*; | [
"java.util",
"org.apache.cassandra"
] | java.util; org.apache.cassandra; | 1,269,469 |
public double ptSegDistSq(mxPoint pt) {
return new Line2D.Double(getX(), getY(), endPoint.getX(), endPoint.getY()).ptSegDistSq(pt.getX(), pt.getY());
} | double function(mxPoint pt) { return new Line2D.Double(getX(), getY(), endPoint.getX(), endPoint.getY()).ptSegDistSq(pt.getX(), pt.getY()); } | /**
* Returns the square of the shortest distance from a point to this
* line segment.
*
* @param pt the point whose distance is being measured
* @return the square of the distance from the specified point to this segment.
*/ | Returns the square of the shortest distance from a point to this line segment | ptSegDistSq | {
"repo_name": "ernestp/consulo",
"path": "platform/graph-impl/src/com/mxgraph/util/mxLine.java",
"license": "apache-2.0",
"size": 2262
} | [
"java.awt.geom.Line2D"
] | import java.awt.geom.Line2D; | import java.awt.geom.*; | [
"java.awt"
] | java.awt; | 2,293,217 |
@Generated("This method was generated using jOOQ-tools")
static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Seq<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>> zip(Seq<T1> s1, Seq<T2> s2, Seq<T3> s3, Seq<T4> s4, Seq<T5> s5, Seq<T6> s6, Seq<T7> s7, Seq<T8> s8, Seq<T9> s9, Seq<T10> s10, Seq<T11> s11, Seq<T12> s12, Seq<T13> s13) {
return zip(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> tuple(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13));
} | @Generated(STR) static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Seq<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>> zip(Seq<T1> s1, Seq<T2> s2, Seq<T3> s3, Seq<T4> s4, Seq<T5> s5, Seq<T6> s6, Seq<T7> s7, Seq<T8> s8, Seq<T9> s9, Seq<T10> s10, Seq<T11> s11, Seq<T12> s12, Seq<T13> s13) { return zip(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) -> tuple(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)); } | /**
* Zip 13 streams into one.
* <p>
* <code><pre>
* // (tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))
* Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"))
* </pre></code>
*/ | Zip 13 streams into one. <code><code> (tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")) </code></code> | zip | {
"repo_name": "stephenh/jOOL",
"path": "src/main/java/org/jooq/lambda/Seq.java",
"license": "apache-2.0",
"size": 198501
} | [
"javax.annotation.Generated",
"org.jooq.lambda.tuple.Tuple",
"org.jooq.lambda.tuple.Tuple13"
] | import javax.annotation.Generated; import org.jooq.lambda.tuple.Tuple; import org.jooq.lambda.tuple.Tuple13; | import javax.annotation.*; import org.jooq.lambda.tuple.*; | [
"javax.annotation",
"org.jooq.lambda"
] | javax.annotation; org.jooq.lambda; | 424,202 |
public Enumeration getEntryPaths(String path); | Enumeration function(String path); | /**
* Returns the paths to entries in the bundle
*/ | Returns the paths to entries in the bundle | getEntryPaths | {
"repo_name": "dlitz/resin",
"path": "modules/osgi/src/org/osgi/framework/Bundle.java",
"license": "gpl-2.0",
"size": 4166
} | [
"java.util.Enumeration"
] | import java.util.Enumeration; | import java.util.*; | [
"java.util"
] | java.util; | 1,371,890 |
private void init() { // WARNING: called from ctor so must not be overridden
// (i.e. must be private or final)
setLayout(new BorderLayout());
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
JPanel jmsQueueingPanel = new JPanel(new BorderLayout());
jmsQueueingPanel.setBorder(BorderFactory.createTitledBorder(
JMeterUtils.getResString("jms_queueing"))); //$NON-NLS-1$
JPanel qcfPanel = new JPanel(new BorderLayout(5, 0));
qcfPanel.add(queueConnectionFactory, BorderLayout.CENTER);
jmsQueueingPanel.add(qcfPanel, BorderLayout.NORTH);
JPanel sendQueuePanel = new JPanel(new BorderLayout(5, 0));
sendQueuePanel.add(sendQueue);
jmsQueueingPanel.add(sendQueuePanel, BorderLayout.CENTER);
JPanel receiveQueuePanel = new JPanel(new BorderLayout(5, 0));
receiveQueuePanel.add(jmsSelector, BorderLayout.SOUTH);
receiveQueuePanel.add(numberOfSamplesToAggregate, BorderLayout.CENTER);
receiveQueuePanel.add(receiveQueue, BorderLayout.NORTH);
jmsQueueingPanel.add(receiveQueuePanel, BorderLayout.SOUTH);
JPanel messagePanel = new JPanel(new BorderLayout());
messagePanel.setBorder(BorderFactory.createTitledBorder(
JMeterUtils.getResString("jms_message_title"))); //$NON-NLS-1$
JPanel correlationPanel = new HorizontalPanel();
correlationPanel.setBorder(BorderFactory.createTitledBorder(
JMeterUtils.getResString("jms_correlation_title"))); //$NON-NLS-1$
useReqMsgIdAsCorrelId = new JCheckBox(JMeterUtils.getResString("jms_use_req_msgid_as_correlid"), false); //$NON-NLS-1$
useResMsgIdAsCorrelId = new JCheckBox(JMeterUtils.getResString("jms_use_res_msgid_as_correlid"), false); //$NON-NLS-1$
correlationPanel.add(useReqMsgIdAsCorrelId);
correlationPanel.add(useResMsgIdAsCorrelId);
JPanel communicationStylePanel = new JPanel();
communicationStylePanel.add(jmsCommunicationStyle);
JPanel messageNorthPanel = new JPanel(new BorderLayout());
JPanel onewayPanel = new HorizontalPanel();
onewayPanel.add(communicationStylePanel);
onewayPanel.add(correlationPanel);
messageNorthPanel.add(onewayPanel, BorderLayout.NORTH);
useNonPersistentDelivery = new JCheckBox(JMeterUtils.getResString("jms_use_non_persistent_delivery"), false); //$NON-NLS-1$
JPanel timeoutPanel = new HorizontalPanel();
timeoutPanel.add(timeout);
timeoutPanel.add(expiration);
timeoutPanel.add(priority);
timeoutPanel.add(useNonPersistentDelivery);
messageNorthPanel.add(timeoutPanel, BorderLayout.SOUTH);
messagePanel.add(messageNorthPanel, BorderLayout.NORTH);
JPanel messageContentPanel = new JPanel(new BorderLayout());
messageContentPanel.add(new JLabel(JMeterUtils.getResString("jms_msg_content")), BorderLayout.NORTH);
messageContentPanel.add(JTextScrollPane.getInstance(messageContent), BorderLayout.CENTER);
messagePanel.add(messageContentPanel, BorderLayout.CENTER);
jmsPropertiesPanel = new JMSPropertiesPanel(); // $NON-NLS-1$
messagePanel.add(jmsPropertiesPanel, BorderLayout.SOUTH);
Box mainPanel = Box.createVerticalBox();
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(jmsQueueingPanel, BorderLayout.NORTH);
mainPanel.add(messagePanel, BorderLayout.CENTER);
JPanel jndiPanel = createJNDIPanel();
mainPanel.add(jndiPanel, BorderLayout.SOUTH);
} | void function() { setLayout(new BorderLayout()); setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); JPanel jmsQueueingPanel = new JPanel(new BorderLayout()); jmsQueueingPanel.setBorder(BorderFactory.createTitledBorder( JMeterUtils.getResString(STR))); JPanel qcfPanel = new JPanel(new BorderLayout(5, 0)); qcfPanel.add(queueConnectionFactory, BorderLayout.CENTER); jmsQueueingPanel.add(qcfPanel, BorderLayout.NORTH); JPanel sendQueuePanel = new JPanel(new BorderLayout(5, 0)); sendQueuePanel.add(sendQueue); jmsQueueingPanel.add(sendQueuePanel, BorderLayout.CENTER); JPanel receiveQueuePanel = new JPanel(new BorderLayout(5, 0)); receiveQueuePanel.add(jmsSelector, BorderLayout.SOUTH); receiveQueuePanel.add(numberOfSamplesToAggregate, BorderLayout.CENTER); receiveQueuePanel.add(receiveQueue, BorderLayout.NORTH); jmsQueueingPanel.add(receiveQueuePanel, BorderLayout.SOUTH); JPanel messagePanel = new JPanel(new BorderLayout()); messagePanel.setBorder(BorderFactory.createTitledBorder( JMeterUtils.getResString(STR))); JPanel correlationPanel = new HorizontalPanel(); correlationPanel.setBorder(BorderFactory.createTitledBorder( JMeterUtils.getResString(STR))); useReqMsgIdAsCorrelId = new JCheckBox(JMeterUtils.getResString(STR), false); useResMsgIdAsCorrelId = new JCheckBox(JMeterUtils.getResString(STR), false); correlationPanel.add(useReqMsgIdAsCorrelId); correlationPanel.add(useResMsgIdAsCorrelId); JPanel communicationStylePanel = new JPanel(); communicationStylePanel.add(jmsCommunicationStyle); JPanel messageNorthPanel = new JPanel(new BorderLayout()); JPanel onewayPanel = new HorizontalPanel(); onewayPanel.add(communicationStylePanel); onewayPanel.add(correlationPanel); messageNorthPanel.add(onewayPanel, BorderLayout.NORTH); useNonPersistentDelivery = new JCheckBox(JMeterUtils.getResString(STR), false); JPanel timeoutPanel = new HorizontalPanel(); timeoutPanel.add(timeout); timeoutPanel.add(expiration); timeoutPanel.add(priority); timeoutPanel.add(useNonPersistentDelivery); messageNorthPanel.add(timeoutPanel, BorderLayout.SOUTH); messagePanel.add(messageNorthPanel, BorderLayout.NORTH); JPanel messageContentPanel = new JPanel(new BorderLayout()); messageContentPanel.add(new JLabel(JMeterUtils.getResString(STR)), BorderLayout.NORTH); messageContentPanel.add(JTextScrollPane.getInstance(messageContent), BorderLayout.CENTER); messagePanel.add(messageContentPanel, BorderLayout.CENTER); jmsPropertiesPanel = new JMSPropertiesPanel(); messagePanel.add(jmsPropertiesPanel, BorderLayout.SOUTH); Box mainPanel = Box.createVerticalBox(); add(mainPanel, BorderLayout.CENTER); mainPanel.add(jmsQueueingPanel, BorderLayout.NORTH); mainPanel.add(messagePanel, BorderLayout.CENTER); JPanel jndiPanel = createJNDIPanel(); mainPanel.add(jndiPanel, BorderLayout.SOUTH); } | /**
* Initializes the configuration screen.
*
*/ | Initializes the configuration screen | init | {
"repo_name": "benbenw/jmeter",
"path": "src/protocol/jms/src/main/java/org/apache/jmeter/protocol/jms/control/gui/JMSSamplerGui.java",
"license": "apache-2.0",
"size": 13606
} | [
"java.awt.BorderLayout",
"javax.swing.BorderFactory",
"javax.swing.Box",
"javax.swing.JCheckBox",
"javax.swing.JLabel",
"javax.swing.JPanel",
"org.apache.jmeter.gui.util.HorizontalPanel",
"org.apache.jmeter.gui.util.JTextScrollPane",
"org.apache.jmeter.util.JMeterUtils"
] | import java.awt.BorderLayout; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.apache.jmeter.gui.util.HorizontalPanel; import org.apache.jmeter.gui.util.JTextScrollPane; import org.apache.jmeter.util.JMeterUtils; | import java.awt.*; import javax.swing.*; import org.apache.jmeter.gui.util.*; import org.apache.jmeter.util.*; | [
"java.awt",
"javax.swing",
"org.apache.jmeter"
] | java.awt; javax.swing; org.apache.jmeter; | 1,530,077 |
private void outputNameMaps() throws FlagUsageException,
IOException {
String propertyMapOutputPath = null;
String variableMapOutputPath = null;
String functionInformationMapOutputPath = null;
// Check the create_name_map_files FLAG.
if (config.createNameMapFiles) {
String basePath = getMapPath(config.jsOutputFile);
propertyMapOutputPath = basePath + "_props_map.out";
variableMapOutputPath = basePath + "_vars_map.out";
functionInformationMapOutputPath = basePath + "_functions_map.out";
}
// Check the individual FLAGS.
if (!config.variableMapOutputFile.isEmpty()) {
if (variableMapOutputPath != null) {
throw new FlagUsageException("The flags variable_map_output_file and "
+ "create_name_map_files cannot both be used simultaniously.");
}
variableMapOutputPath = config.variableMapOutputFile;
}
if (!config.propertyMapOutputFile.isEmpty()) {
if (propertyMapOutputPath != null) {
throw new FlagUsageException("The flags property_map_output_file and "
+ "create_name_map_files cannot both be used simultaniously.");
}
propertyMapOutputPath = config.propertyMapOutputFile;
}
// Output the maps.
if (variableMapOutputPath != null && compiler.getVariableMap() != null) {
compiler.getVariableMap().save(variableMapOutputPath);
}
if (propertyMapOutputPath != null && compiler.getPropertyMap() != null) {
compiler.getPropertyMap().save(propertyMapOutputPath);
}
if (functionInformationMapOutputPath != null
&& compiler.getFunctionalInformationMap() != null) {
try (final OutputStream file = filenameToOutputStream(functionInformationMapOutputPath)) {
CodedOutputStream outputStream = CodedOutputStream.newInstance(file);
compiler.getFunctionalInformationMap().writeTo(outputStream);
outputStream.flush();
}
}
} | void function() throws FlagUsageException, IOException { String propertyMapOutputPath = null; String variableMapOutputPath = null; String functionInformationMapOutputPath = null; if (config.createNameMapFiles) { String basePath = getMapPath(config.jsOutputFile); propertyMapOutputPath = basePath + STR; variableMapOutputPath = basePath + STR; functionInformationMapOutputPath = basePath + STR; } if (!config.variableMapOutputFile.isEmpty()) { if (variableMapOutputPath != null) { throw new FlagUsageException(STR + STR); } variableMapOutputPath = config.variableMapOutputFile; } if (!config.propertyMapOutputFile.isEmpty()) { if (propertyMapOutputPath != null) { throw new FlagUsageException(STR + STR); } propertyMapOutputPath = config.propertyMapOutputFile; } if (variableMapOutputPath != null && compiler.getVariableMap() != null) { compiler.getVariableMap().save(variableMapOutputPath); } if (propertyMapOutputPath != null && compiler.getPropertyMap() != null) { compiler.getPropertyMap().save(propertyMapOutputPath); } if (functionInformationMapOutputPath != null && compiler.getFunctionalInformationMap() != null) { try (final OutputStream file = filenameToOutputStream(functionInformationMapOutputPath)) { CodedOutputStream outputStream = CodedOutputStream.newInstance(file); compiler.getFunctionalInformationMap().writeTo(outputStream); outputStream.flush(); } } } | /**
* Outputs the variable and property name maps for the specified compiler if
* the proper FLAGS are set.
*/ | Outputs the variable and property name maps for the specified compiler if the proper FLAGS are set | outputNameMaps | {
"repo_name": "lgeorgieff/closure-compiler",
"path": "src/com/google/javascript/jscomp/AbstractCommandLineRunner.java",
"license": "apache-2.0",
"size": 83284
} | [
"com.google.protobuf.CodedOutputStream",
"java.io.IOException",
"java.io.OutputStream"
] | import com.google.protobuf.CodedOutputStream; import java.io.IOException; import java.io.OutputStream; | import com.google.protobuf.*; import java.io.*; | [
"com.google.protobuf",
"java.io"
] | com.google.protobuf; java.io; | 1,857,913 |
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<RouteFilterRuleInner> listByRouteFilterAsync(
String resourceGroupName, String routeFilterName, Context context) {
return new PagedFlux<>(
() -> listByRouteFilterSinglePageAsync(resourceGroupName, routeFilterName, context),
nextLink -> listByRouteFilterNextSinglePageAsync(nextLink, context));
} | @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<RouteFilterRuleInner> function( String resourceGroupName, String routeFilterName, Context context) { return new PagedFlux<>( () -> listByRouteFilterSinglePageAsync(resourceGroupName, routeFilterName, context), nextLink -> listByRouteFilterNextSinglePageAsync(nextLink, context)); } | /**
* Gets all RouteFilterRules in a route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all RouteFilterRules in a route filter as paginated response with {@link PagedFlux}.
*/ | Gets all RouteFilterRules in a route filter | listByRouteFilterAsync | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/RouteFilterRulesClientImpl.java",
"license": "mit",
"size": 56872
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.PagedFlux",
"com.azure.core.util.Context",
"com.azure.resourcemanager.network.fluent.models.RouteFilterRuleInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.util.Context; import com.azure.resourcemanager.network.fluent.models.RouteFilterRuleInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.core.util.*; import com.azure.resourcemanager.network.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 1,544,528 |
public static String copyToString(InputStream in, Charset charset) throws IOException {
Assert.notNull(in, "No InputStream specified");
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, bytesRead);
}
return out.toString();
} | static String function(InputStream in, Charset charset) throws IOException { Assert.notNull(in, STR); StringBuilder out = new StringBuilder(); InputStreamReader reader = new InputStreamReader(in, charset); char[] buffer = new char[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = reader.read(buffer)) != -1) { out.append(buffer, 0, bytesRead); } return out.toString(); } | /**
* Copy the contents of the given InputStream into a String.
* Leaves the stream open when done.
* @param in the InputStream to copy from
* @return the String that has been copied to
* @throws IOException in case of I/O errors
*/ | Copy the contents of the given InputStream into a String. Leaves the stream open when done | copyToString | {
"repo_name": "lj654548718/ispring",
"path": "src/main/java/io/ispring/ori/utils/StreamUtils.java",
"license": "apache-2.0",
"size": 7998
} | [
"java.io.IOException",
"java.io.InputStream",
"java.io.InputStreamReader",
"java.nio.charset.Charset"
] | import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; | import java.io.*; import java.nio.charset.*; | [
"java.io",
"java.nio"
] | java.io; java.nio; | 2,192,060 |
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Insert key: {} into table: {}", key, table);
}
try {
CosmosContainer container = AzureCosmosClient.containerCache.get(table);
if (container == null) {
container = AzureCosmosClient.database.getContainer(table);
AzureCosmosClient.containerCache.put(table, container);
}
PartitionKey pk = new PartitionKey(key);
ObjectNode node = OBJECT_MAPPER.createObjectNode();
node.put("id", key);
for (Map.Entry<String, ByteIterator> pair : values.entrySet()) {
node.put(pair.getKey(), pair.getValue().toString());
}
if (AzureCosmosClient.useUpsert) {
container.upsertItem(node, pk, new CosmosItemRequestOptions());
} else {
container.createItem(node, pk, new CosmosItemRequestOptions());
}
return Status.OK;
} catch (CosmosException e) {
if (!AzureCosmosClient.includeExceptionStackInLog) {
e = null;
}
LOGGER.error("Failed to insert key {} to collection {} in database {}", key, table,
AzureCosmosClient.databaseName, e);
}
return Status.ERROR;
} | Status function(String table, String key, Map<String, ByteIterator> values) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(STR, key, table); } try { CosmosContainer container = AzureCosmosClient.containerCache.get(table); if (container == null) { container = AzureCosmosClient.database.getContainer(table); AzureCosmosClient.containerCache.put(table, container); } PartitionKey pk = new PartitionKey(key); ObjectNode node = OBJECT_MAPPER.createObjectNode(); node.put("id", key); for (Map.Entry<String, ByteIterator> pair : values.entrySet()) { node.put(pair.getKey(), pair.getValue().toString()); } if (AzureCosmosClient.useUpsert) { container.upsertItem(node, pk, new CosmosItemRequestOptions()); } else { container.createItem(node, pk, new CosmosItemRequestOptions()); } return Status.OK; } catch (CosmosException e) { if (!AzureCosmosClient.includeExceptionStackInLog) { e = null; } LOGGER.error(STR, key, table, AzureCosmosClient.databaseName, e); } return Status.ERROR; } | /**
* Insert a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record key.
*
* @param table The name of the table
* @param key The record key of the record to insert.
* @param values A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error
*/ | Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified record key | insert | {
"repo_name": "brianfrankcooper/YCSB",
"path": "azurecosmos/src/main/java/site/ycsb/db/AzureCosmosClient.java",
"license": "apache-2.0",
"size": 20780
} | [
"com.azure.cosmos.CosmosContainer",
"com.azure.cosmos.CosmosException",
"com.azure.cosmos.models.CosmosItemRequestOptions",
"com.azure.cosmos.models.PartitionKey",
"com.fasterxml.jackson.databind.node.ObjectNode",
"java.util.Map",
"site.ycsb.ByteIterator",
"site.ycsb.Status"
] | import com.azure.cosmos.CosmosContainer; import com.azure.cosmos.CosmosException; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.cosmos.models.PartitionKey; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.Map; import site.ycsb.ByteIterator; import site.ycsb.Status; | import com.azure.cosmos.*; import com.azure.cosmos.models.*; import com.fasterxml.jackson.databind.node.*; import java.util.*; import site.ycsb.*; | [
"com.azure.cosmos",
"com.fasterxml.jackson",
"java.util",
"site.ycsb"
] | com.azure.cosmos; com.fasterxml.jackson; java.util; site.ycsb; | 2,062,349 |
@SuppressWarnings("unchecked")
public Object getObject(String parameterName, Class<?>[] classes, Object[] instanceParameters) throws ParameterNotAvailableException {
String className = (String) this.parameters.getValue(parameterName);
if (className != null) {
try {
Class<Object> classToLoad = (Class<Object>) Class.forName(className);
Constructor<Object> c = classToLoad.getConstructor(classes);
Object object = c.newInstance(instanceParameters);
return object;
} catch (ClassNotFoundException e) {
SimulationParametersProvider.LOG.error("Unable to find class " + className, e);
} catch (SecurityException e) {
SimulationParametersProvider.LOG.error("Unable to access constructor or package for " + className, e);
} catch (NoSuchMethodException e) {
SimulationParametersProvider.LOG.error("Constructor not found.", e);
} catch (InstantiationException e) {
SimulationParametersProvider.LOG.error("Class " + className + " is abstract", e);
} catch (IllegalAccessException e) {
SimulationParametersProvider.LOG.error("Constructor for " + className + " is inaccessible", e);
} catch (InvocationTargetException e) {
SimulationParametersProvider.LOG.error("Constructor for " + className + " threw an exception:");
SimulationParametersProvider.LOG.error(e.getMessage(), e);
}
}
return null;
}
| @SuppressWarnings(STR) Object function(String parameterName, Class<?>[] classes, Object[] instanceParameters) throws ParameterNotAvailableException { String className = (String) this.parameters.getValue(parameterName); if (className != null) { try { Class<Object> classToLoad = (Class<Object>) Class.forName(className); Constructor<Object> c = classToLoad.getConstructor(classes); Object object = c.newInstance(instanceParameters); return object; } catch (ClassNotFoundException e) { SimulationParametersProvider.LOG.error(STR + className, e); } catch (SecurityException e) { SimulationParametersProvider.LOG.error(STR + className, e); } catch (NoSuchMethodException e) { SimulationParametersProvider.LOG.error(STR, e); } catch (InstantiationException e) { SimulationParametersProvider.LOG.error(STR + className + STR, e); } catch (IllegalAccessException e) { SimulationParametersProvider.LOG.error(STR + className + STR, e); } catch (InvocationTargetException e) { SimulationParametersProvider.LOG.error(STR + className + STR); SimulationParametersProvider.LOG.error(e.getMessage(), e); } } return null; } | /**
* Gets an instance of an Object whose class is identified by the parameter and calls the constructor as identified
* by the provided classes and instance parameters. Returns {@link Object} values.
*
* @param parameterName
* the name of the parameter that contains the class name
* @param classes
* the classes of the parameters given to the constructor
* @param instanceParameters
* the values of the parameters given to the constructor
* @return an {@link Object} instance of the class identified by the parameter and initialized with the constructor
* the fits the given classes or <code>null</code> if the parameter wasn't found
* @throws ParameterNotAvailableException
* if the parameter wasn't found
*/ | Gets an instance of an Object whose class is identified by the parameter and calls the constructor as identified by the provided classes and instance parameters. Returns <code>Object</code> values | getObject | {
"repo_name": "Alexander-Schiendorfer/active-learning-collectives",
"path": "Utilities/src/utilities/parameters/SimulationParametersProvider.java",
"license": "mit",
"size": 11329
} | [
"java.lang.reflect.Constructor",
"java.lang.reflect.InvocationTargetException"
] | import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 2,291,550 |
public Collection<Serializable> getIds() {
return ids;
} | Collection<Serializable> function() { return ids; } | /**
* JAVADOC Method Level Comments
*
* @return JAVADOC.
*/ | JAVADOC Method Level Comments | getIds | {
"repo_name": "cucina/opencucina",
"path": "engine-server-api/src/main/java/org/cucina/engine/server/event/ListTransitionsEvent.java",
"license": "apache-2.0",
"size": 1278
} | [
"java.io.Serializable",
"java.util.Collection"
] | import java.io.Serializable; import java.util.Collection; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,720,299 |
protected Throwable getCause(Throwable t)
{
Throwable rv = null;
// ServletException is non-standard
if (t instanceof ServletException)
{
rv = ((ServletException) t).getRootCause();
}
// try for the standard cause
if (rv == null) rv = t.getCause();
// clear it if the cause is pointing at the throwable
if ((rv != null) && (rv == t)) rv = null;
return rv;
} | Throwable function(Throwable t) { Throwable rv = null; if (t instanceof ServletException) { rv = ((ServletException) t).getRootCause(); } if (rv == null) rv = t.getCause(); if ((rv != null) && (rv == t)) rv = null; return rv; } | /**
* Compute the cause of a throwable, checking for the special
* ServletException case, and the points-to-self case.
*
* @param t
* The throwable.
* @return The cause of the throwable, or null if there is none.
*/ | Compute the cause of a throwable, checking for the special ServletException case, and the points-to-self case | getCause | {
"repo_name": "kingmook/sakai",
"path": "portal/portal-util/util/src/java/org/sakaiproject/portal/util/ErrorReporter.java",
"license": "apache-2.0",
"size": 27994
} | [
"javax.servlet.ServletException"
] | import javax.servlet.ServletException; | import javax.servlet.*; | [
"javax.servlet"
] | javax.servlet; | 835,175 |
private void updateArrowsEnabled() {
Priority priority = raidModel.getPriority(targetType);
upArrow.setEnabled(priority.hasHigherPriority()
&& raidModel.isAssignablePriority(targetType, priority.higher()));
downArrow
.setEnabled(priority.hasLowerPriority()
&& raidModel.isAssignablePriority(targetType,
priority.lower()));
} | void function() { Priority priority = raidModel.getPriority(targetType); upArrow.setEnabled(priority.hasHigherPriority() && raidModel.isAssignablePriority(targetType, priority.higher())); downArrow .setEnabled(priority.hasLowerPriority() && raidModel.isAssignablePriority(targetType, priority.lower())); } | /**
* Update the enabled/disabled status of the arrows based on the
* {@link #raidModel}.
*/ | Update the enabled/disabled status of the arrows based on the <code>#raidModel</code> | updateArrowsEnabled | {
"repo_name": "shinnya/morgans-raid-mirror",
"path": "src/edu/bsu/jhm/ui/PriorityRaidWidget.java",
"license": "gpl-3.0",
"size": 11751
} | [
"edu.bsu.jhm.raid.Priority"
] | import edu.bsu.jhm.raid.Priority; | import edu.bsu.jhm.raid.*; | [
"edu.bsu.jhm"
] | edu.bsu.jhm; | 885,779 |
@Test
public void testCloning() throws CloneNotSupportedException {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator();
StandardCategoryToolTipGenerator g2
= (StandardCategoryToolTipGenerator) g1.clone();
assertTrue(g1 != g2);
assertTrue(g1.getClass() == g2.getClass());
assertTrue(g1.equals(g2));
} | void function() throws CloneNotSupportedException { StandardCategoryToolTipGenerator g1 = new StandardCategoryToolTipGenerator(); StandardCategoryToolTipGenerator g2 = (StandardCategoryToolTipGenerator) g1.clone(); assertTrue(g1 != g2); assertTrue(g1.getClass() == g2.getClass()); assertTrue(g1.equals(g2)); } | /**
* Confirm that cloning works.
*/ | Confirm that cloning works | testCloning | {
"repo_name": "simon04/jfreechart",
"path": "src/test/java/org/jfree/chart/labels/StandardCategoryToolTipGeneratorTest.java",
"license": "lgpl-2.1",
"size": 5520
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 1,676,262 |
private Result execute( final int nr, Result prev_result, final JobEntryCopy jobEntryCopy, JobEntryCopy previous,
String reason ) throws KettleException {
Result res = null;
if ( isStopped() ) {
res = new Result( nr );
res.stopped = true;
return res;
}
// if we didn't have a previous result, create one, otherwise, copy the content...
//
final Result newResult;
Result prevResult = null;
if ( prev_result != null ) {
prevResult = prev_result.clone();
} else {
prevResult = new Result();
}
JobExecutionExtension extension = new JobExecutionExtension( this, prevResult, jobEntryCopy, true );
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobBeforeJobEntryExecution.id, extension );
if ( extension.result != null ) {
prevResult = extension.result;
}
if ( !extension.executeEntry ) {
newResult = prevResult;
} else {
if ( log.isDetailed() ) {
log.logDetailed( "exec(" + nr + ", " + ( prev_result != null ? prev_result.getNrErrors() : 0 ) + ", "
+ ( jobEntryCopy != null ? jobEntryCopy.toString() : "null" ) + ")" );
}
// Which entry is next?
JobEntryInterface jobEntryInterface = jobEntryCopy.getEntry();
jobEntryInterface.getLogChannel().setLogLevel( logLevel );
// Track the fact that we are going to launch the next job entry...
JobEntryResult jerBefore =
new JobEntryResult( null, null, BaseMessages.getString( PKG, "Job.Comment.JobStarted" ), reason, jobEntryCopy
.getName(), jobEntryCopy.getNr(), environmentSubstitute( jobEntryCopy.getEntry().getFilename() ) );
jobTracker.addJobTracker( new JobTracker( jobMeta, jerBefore ) );
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader( jobEntryInterface.getClass().getClassLoader() );
// Execute this entry...
JobEntryInterface cloneJei = (JobEntryInterface) jobEntryInterface.clone();
( (VariableSpace) cloneJei ).copyVariablesFrom( this );
cloneJei.setRepository( rep );
if ( rep != null ) {
cloneJei.setMetaStore( rep.getMetaStore() );
}
cloneJei.setParentJob( this );
cloneJei.setParentJobMeta( this.getJobMeta() );
final long start = System.currentTimeMillis();
cloneJei.getLogChannel().logDetailed( "Starting job entry" );
for ( JobEntryListener jobEntryListener : jobEntryListeners ) {
jobEntryListener.beforeExecution( this, jobEntryCopy, cloneJei );
}
if ( interactive ) {
if ( jobEntryCopy.isTransformation() ) {
getActiveJobEntryTransformations().put( jobEntryCopy, (JobEntryTrans) cloneJei );
}
if ( jobEntryCopy.isJob() ) {
getActiveJobEntryJobs().put( jobEntryCopy, (JobEntryJob) cloneJei );
}
}
log.snap( Metrics.METRIC_JOBENTRY_START, cloneJei.toString() );
newResult = cloneJei.execute( prevResult, nr );
log.snap( Metrics.METRIC_JOBENTRY_STOP, cloneJei.toString() );
final long end = System.currentTimeMillis();
if ( interactive ) {
if ( jobEntryCopy.isTransformation() ) {
getActiveJobEntryTransformations().remove( jobEntryCopy );
}
if ( jobEntryCopy.isJob() ) {
getActiveJobEntryJobs().remove( jobEntryCopy );
}
}
if ( cloneJei instanceof JobEntryTrans ) {
String throughput = newResult.getReadWriteThroughput( (int) ( ( end - start ) / 1000 ) );
if ( throughput != null ) {
log.logMinimal( throughput );
}
}
for ( JobEntryListener jobEntryListener : jobEntryListeners ) {
jobEntryListener.afterExecution( this, jobEntryCopy, cloneJei, newResult );
}
Thread.currentThread().setContextClassLoader( cl );
addErrors( (int) newResult.getNrErrors() );
// Also capture the logging text after the execution...
//
LoggingBuffer loggingBuffer = KettleLogStore.getAppender();
StringBuffer logTextBuffer = loggingBuffer.getBuffer( cloneJei.getLogChannel().getLogChannelId(), false );
newResult.setLogText( logTextBuffer.toString() + newResult.getLogText() );
// Save this result as well...
//
JobEntryResult jerAfter =
new JobEntryResult( newResult, cloneJei.getLogChannel().getLogChannelId(), BaseMessages.getString( PKG,
"Job.Comment.JobFinished" ), null, jobEntryCopy.getName(), jobEntryCopy.getNr(), environmentSubstitute(
jobEntryCopy.getEntry().getFilename() ) );
jobTracker.addJobTracker( new JobTracker( jobMeta, jerAfter ) );
synchronized ( jobEntryResults ) {
jobEntryResults.add( jerAfter );
// Only keep the last X job entry results in memory
//
if ( maxJobEntriesLogged > 0 ) {
while ( jobEntryResults.size() > maxJobEntriesLogged ) {
// Remove the oldest.
jobEntryResults.removeFirst();
}
}
}
}
extension = new JobExecutionExtension( this, prevResult, jobEntryCopy, extension.executeEntry );
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobAfterJobEntryExecution.id, extension );
// Try all next job entries.
//
// Keep track of all the threads we fired in case of parallel execution...
// Keep track of the results of these executions too.
//
final List<Thread> threads = new ArrayList<Thread>();
// next 2 lists is being modified concurrently so must be synchronized for this case.
final Queue<Result> threadResults = new ConcurrentLinkedQueue<Result>();
final Queue<KettleException> threadExceptions = new ConcurrentLinkedQueue<KettleException>();
final List<JobEntryCopy> threadEntries = new ArrayList<JobEntryCopy>();
// Launch only those where the hop indicates true or false
//
int nrNext = jobMeta.findNrNextJobEntries( jobEntryCopy );
for ( int i = 0; i < nrNext && !isStopped(); i++ ) {
// The next entry is...
final JobEntryCopy nextEntry = jobMeta.findNextJobEntry( jobEntryCopy, i );
// See if we need to execute this...
final JobHopMeta hi = jobMeta.findJobHop( jobEntryCopy, nextEntry );
// The next comment...
final String nextComment;
if ( hi.isUnconditional() ) {
nextComment = BaseMessages.getString( PKG, "Job.Comment.FollowedUnconditional" );
} else {
if ( newResult.getResult() ) {
nextComment = BaseMessages.getString( PKG, "Job.Comment.FollowedSuccess" );
} else {
nextComment = BaseMessages.getString( PKG, "Job.Comment.FollowedFailure" );
}
}
//
// If the link is unconditional, execute the next job entry (entries).
// If the start point was an evaluation and the link color is correct:
// green or red, execute the next job entry...
//
if ( hi.isUnconditional() || ( jobEntryCopy.evaluates() && ( !( hi.getEvaluation() ^ newResult
.getResult() ) ) ) ) {
// Start this next step!
if ( log.isBasic() ) {
log.logBasic( BaseMessages.getString( PKG, "Job.Log.StartingEntry", nextEntry.getName() ) );
}
// Pass along the previous result, perhaps the next job can use it...
// However, set the number of errors back to 0 (if it should be reset)
// When an evaluation is executed the errors e.g. should not be reset.
if ( nextEntry.resetErrorsBeforeExecution() ) {
newResult.setNrErrors( 0 );
}
// Now execute!
//
// if (we launch in parallel, fire the execution off in a new thread...
//
if ( jobEntryCopy.isLaunchingInParallel() ) {
threadEntries.add( nextEntry ); | Result function( final int nr, Result prev_result, final JobEntryCopy jobEntryCopy, JobEntryCopy previous, String reason ) throws KettleException { Result res = null; if ( isStopped() ) { res = new Result( nr ); res.stopped = true; return res; } Result prevResult = null; if ( prev_result != null ) { prevResult = prev_result.clone(); } else { prevResult = new Result(); } JobExecutionExtension extension = new JobExecutionExtension( this, prevResult, jobEntryCopy, true ); ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobBeforeJobEntryExecution.id, extension ); if ( extension.result != null ) { prevResult = extension.result; } if ( !extension.executeEntry ) { newResult = prevResult; } else { if ( log.isDetailed() ) { log.logDetailed( "exec(" + nr + STR + ( prev_result != null ? prev_result.getNrErrors() : 0 ) + STR + ( jobEntryCopy != null ? jobEntryCopy.toString() : "null" ) + ")" ); } JobEntryInterface jobEntryInterface = jobEntryCopy.getEntry(); jobEntryInterface.getLogChannel().setLogLevel( logLevel ); JobEntryResult jerBefore = new JobEntryResult( null, null, BaseMessages.getString( PKG, STR ), reason, jobEntryCopy .getName(), jobEntryCopy.getNr(), environmentSubstitute( jobEntryCopy.getEntry().getFilename() ) ); jobTracker.addJobTracker( new JobTracker( jobMeta, jerBefore ) ); ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( jobEntryInterface.getClass().getClassLoader() ); JobEntryInterface cloneJei = (JobEntryInterface) jobEntryInterface.clone(); ( (VariableSpace) cloneJei ).copyVariablesFrom( this ); cloneJei.setRepository( rep ); if ( rep != null ) { cloneJei.setMetaStore( rep.getMetaStore() ); } cloneJei.setParentJob( this ); cloneJei.setParentJobMeta( this.getJobMeta() ); final long start = System.currentTimeMillis(); cloneJei.getLogChannel().logDetailed( STR ); for ( JobEntryListener jobEntryListener : jobEntryListeners ) { jobEntryListener.beforeExecution( this, jobEntryCopy, cloneJei ); } if ( interactive ) { if ( jobEntryCopy.isTransformation() ) { getActiveJobEntryTransformations().put( jobEntryCopy, (JobEntryTrans) cloneJei ); } if ( jobEntryCopy.isJob() ) { getActiveJobEntryJobs().put( jobEntryCopy, (JobEntryJob) cloneJei ); } } log.snap( Metrics.METRIC_JOBENTRY_START, cloneJei.toString() ); newResult = cloneJei.execute( prevResult, nr ); log.snap( Metrics.METRIC_JOBENTRY_STOP, cloneJei.toString() ); final long end = System.currentTimeMillis(); if ( interactive ) { if ( jobEntryCopy.isTransformation() ) { getActiveJobEntryTransformations().remove( jobEntryCopy ); } if ( jobEntryCopy.isJob() ) { getActiveJobEntryJobs().remove( jobEntryCopy ); } } if ( cloneJei instanceof JobEntryTrans ) { String throughput = newResult.getReadWriteThroughput( (int) ( ( end - start ) / 1000 ) ); if ( throughput != null ) { log.logMinimal( throughput ); } } for ( JobEntryListener jobEntryListener : jobEntryListeners ) { jobEntryListener.afterExecution( this, jobEntryCopy, cloneJei, newResult ); } Thread.currentThread().setContextClassLoader( cl ); addErrors( (int) newResult.getNrErrors() ); StringBuffer logTextBuffer = loggingBuffer.getBuffer( cloneJei.getLogChannel().getLogChannelId(), false ); newResult.setLogText( logTextBuffer.toString() + newResult.getLogText() ); new JobEntryResult( newResult, cloneJei.getLogChannel().getLogChannelId(), BaseMessages.getString( PKG, STR ), null, jobEntryCopy.getName(), jobEntryCopy.getNr(), environmentSubstitute( jobEntryCopy.getEntry().getFilename() ) ); jobTracker.addJobTracker( new JobTracker( jobMeta, jerAfter ) ); synchronized ( jobEntryResults ) { jobEntryResults.add( jerAfter ); while ( jobEntryResults.size() > maxJobEntriesLogged ) { jobEntryResults.removeFirst(); } } } } extension = new JobExecutionExtension( this, prevResult, jobEntryCopy, extension.executeEntry ); ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobAfterJobEntryExecution.id, extension ); final Queue<Result> threadResults = new ConcurrentLinkedQueue<Result>(); final Queue<KettleException> threadExceptions = new ConcurrentLinkedQueue<KettleException>(); final List<JobEntryCopy> threadEntries = new ArrayList<JobEntryCopy>(); for ( int i = 0; i < nrNext && !isStopped(); i++ ) { final JobEntryCopy nextEntry = jobMeta.findNextJobEntry( jobEntryCopy, i ); final JobHopMeta hi = jobMeta.findJobHop( jobEntryCopy, nextEntry ); final String nextComment; if ( hi.isUnconditional() ) { nextComment = BaseMessages.getString( PKG, STR ); } else { if ( newResult.getResult() ) { nextComment = BaseMessages.getString( PKG, STR ); } else { nextComment = BaseMessages.getString( PKG, STR ); } } .getResult() ) ) ) ) { if ( log.isBasic() ) { log.logBasic( BaseMessages.getString( PKG, STR, nextEntry.getName() ) ); } if ( nextEntry.resetErrorsBeforeExecution() ) { newResult.setNrErrors( 0 ); } threadEntries.add( nextEntry ); | /**
* Execute a job entry recursively and move to the next job entry automatically.<br>
* Uses a back-tracking algorithm.<br>
*
* @param nr
* @param prev_result
* @param jobEntryCopy
* @param previous
* @param reason
* @return
* @throws KettleException
*/ | Execute a job entry recursively and move to the next job entry automatically. Uses a back-tracking algorithm | execute | {
"repo_name": "wseyler/pentaho-kettle",
"path": "engine/src/main/java/org/pentaho/di/job/Job.java",
"license": "apache-2.0",
"size": 73161
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.Queue",
"java.util.concurrent.ConcurrentLinkedQueue",
"org.pentaho.di.core.Result",
"org.pentaho.di.core.exception.KettleException",
"org.pentaho.di.core.extension.ExtensionPointHandler",
"org.pentaho.di.core.extension.KettleExtensionPoint",
"org.pentaho.di.core.gui.JobTracker",
"org.pentaho.di.core.logging.Metrics",
"org.pentaho.di.core.variables.VariableSpace",
"org.pentaho.di.i18n.BaseMessages",
"org.pentaho.di.job.entries.job.JobEntryJob",
"org.pentaho.di.job.entries.trans.JobEntryTrans",
"org.pentaho.di.job.entry.JobEntryCopy",
"org.pentaho.di.job.entry.JobEntryInterface"
] | import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.pentaho.di.core.Result; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.extension.ExtensionPointHandler; import org.pentaho.di.core.extension.KettleExtensionPoint; import org.pentaho.di.core.gui.JobTracker; import org.pentaho.di.core.logging.Metrics; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.entries.job.JobEntryJob; import org.pentaho.di.job.entries.trans.JobEntryTrans; import org.pentaho.di.job.entry.JobEntryCopy; import org.pentaho.di.job.entry.JobEntryInterface; | import java.util.*; import java.util.concurrent.*; import org.pentaho.di.core.*; import org.pentaho.di.core.exception.*; import org.pentaho.di.core.extension.*; import org.pentaho.di.core.gui.*; import org.pentaho.di.core.logging.*; import org.pentaho.di.core.variables.*; import org.pentaho.di.i18n.*; import org.pentaho.di.job.entries.job.*; import org.pentaho.di.job.entries.trans.*; import org.pentaho.di.job.entry.*; | [
"java.util",
"org.pentaho.di"
] | java.util; org.pentaho.di; | 1,998,037 |
private HashMap<BasicBlock, BasicBlock> createOptimizedLoop(AnnotatedLSTNode loop,
HashMap<Register, Register> regMap,
ArrayList<Instruction> instrToEliminate,
HashMap<Register, BasicBlock> regToBlockMap) {
HashMap<BasicBlock, BasicBlock> originalToCloneBBMap = new HashMap<BasicBlock, BasicBlock>();
// After the newly created loop goto the old loop header
originalToCloneBBMap.put(loop.successor, loop.header);
// Create an empty block to be the loop predecessor
BasicBlock new_pred = loop.header.createSubBlock(SYNTH_LOOP_VERSIONING_BCI, ir);
ir.cfg.linkInCodeOrder(ir.cfg.lastInCodeOrder(), new_pred);
originalToCloneBBMap.put(loop.predecessor, new_pred);
// Create copy blocks
Enumeration<BasicBlock> blocks = loop.getBasicBlocks();
while (blocks.hasMoreElements()) {
BasicBlock block = blocks.nextElement();
// N.B. fall through will have been killed by unoptimized loop
// Create copy and register mapping
BasicBlock copy = block.copyWithoutLinks(ir);
originalToCloneBBMap.put(block, copy);
// Link into code order
ir.cfg.linkInCodeOrder(ir.cfg.lastInCodeOrder(), copy);
// Alter register definitions in copy
IREnumeration.AllInstructionsEnum instructions = new IREnumeration.AllInstructionsEnum(ir, copy);
loop_over_created_instructions:
while (instructions.hasMoreElements()) {
Instruction instruction = instructions.nextElement();
if (BoundsCheck.conforms(instruction)) {
for (Instruction anInstrToEliminate : instrToEliminate) {
if (instruction.similar(anInstrToEliminate)) {
instruction.remove();
continue loop_over_created_instructions;
}
}
} else if (NullCheck.conforms(instruction)) {
for (Instruction anInstrToEliminate : instrToEliminate) {
if (instruction.similar(anInstrToEliminate)) {
instruction.remove();
continue loop_over_created_instructions;
}
}
}
Enumeration<Operand> operands = instruction.getDefs();
while (operands.hasMoreElements()) {
Operand operand = operands.nextElement();
if (operand instanceof RegisterOperand) {
Register register = operand.asRegister().getRegister();
if (regMap.containsKey(register)) {
instruction.replaceRegister(register, regMap.get(register));
regToBlockMap.put(regMap.get(register), copy);
}
}
}
operands = instruction.getUses();
while (operands.hasMoreElements()) {
Operand operand = operands.nextElement();
if (operand.isRegister()) {
Register register = operand.asRegister().getRegister();
if (regMap.containsKey(register)) {
instruction.replaceRegister(register, regMap.get(register));
}
}
}
}
}
// Fix up outs
// loop predecessor
new_pred.redirectOuts(loop.header, originalToCloneBBMap.get(loop.header), ir);
blocks = loop.getBasicBlocks();
while (blocks.hasMoreElements()) {
BasicBlock block = blocks.nextElement();
BasicBlock copy = originalToCloneBBMap.get(block);
Enumeration<BasicBlock> outs = block.getOutNodes();
while (outs.hasMoreElements()) {
BasicBlock out = outs.nextElement();
if (originalToCloneBBMap.containsKey(out)) {
copy.redirectOuts(out, originalToCloneBBMap.get(out), ir);
}
}
}
// Fix up phis
blocks = loop.getBasicBlocks();
while (blocks.hasMoreElements()) {
BasicBlock block = blocks.nextElement();
BasicBlock copy = originalToCloneBBMap.get(block);
IREnumeration.AllInstructionsEnum instructions = new IREnumeration.AllInstructionsEnum(ir, copy);
while (instructions.hasMoreElements()) {
Instruction instruction = instructions.nextElement();
if (Phi.conforms(instruction)) {
for (int i = 0; i < Phi.getNumberOfValues(instruction); i++) {
BasicBlock phi_predecessor = Phi.getPred(instruction, i).block;
if (originalToCloneBBMap.containsKey(phi_predecessor)) {
Phi.setPred(instruction, i, new BasicBlockOperand(originalToCloneBBMap.get(phi_predecessor)));
} else {
throw new Error("There's > 1 route to this phi node from outside the loop: " + phi_predecessor);
}
}
}
}
}
return originalToCloneBBMap;
} | HashMap<BasicBlock, BasicBlock> function(AnnotatedLSTNode loop, HashMap<Register, Register> regMap, ArrayList<Instruction> instrToEliminate, HashMap<Register, BasicBlock> regToBlockMap) { HashMap<BasicBlock, BasicBlock> originalToCloneBBMap = new HashMap<BasicBlock, BasicBlock>(); originalToCloneBBMap.put(loop.successor, loop.header); BasicBlock new_pred = loop.header.createSubBlock(SYNTH_LOOP_VERSIONING_BCI, ir); ir.cfg.linkInCodeOrder(ir.cfg.lastInCodeOrder(), new_pred); originalToCloneBBMap.put(loop.predecessor, new_pred); Enumeration<BasicBlock> blocks = loop.getBasicBlocks(); while (blocks.hasMoreElements()) { BasicBlock block = blocks.nextElement(); BasicBlock copy = block.copyWithoutLinks(ir); originalToCloneBBMap.put(block, copy); ir.cfg.linkInCodeOrder(ir.cfg.lastInCodeOrder(), copy); IREnumeration.AllInstructionsEnum instructions = new IREnumeration.AllInstructionsEnum(ir, copy); loop_over_created_instructions: while (instructions.hasMoreElements()) { Instruction instruction = instructions.nextElement(); if (BoundsCheck.conforms(instruction)) { for (Instruction anInstrToEliminate : instrToEliminate) { if (instruction.similar(anInstrToEliminate)) { instruction.remove(); continue loop_over_created_instructions; } } } else if (NullCheck.conforms(instruction)) { for (Instruction anInstrToEliminate : instrToEliminate) { if (instruction.similar(anInstrToEliminate)) { instruction.remove(); continue loop_over_created_instructions; } } } Enumeration<Operand> operands = instruction.getDefs(); while (operands.hasMoreElements()) { Operand operand = operands.nextElement(); if (operand instanceof RegisterOperand) { Register register = operand.asRegister().getRegister(); if (regMap.containsKey(register)) { instruction.replaceRegister(register, regMap.get(register)); regToBlockMap.put(regMap.get(register), copy); } } } operands = instruction.getUses(); while (operands.hasMoreElements()) { Operand operand = operands.nextElement(); if (operand.isRegister()) { Register register = operand.asRegister().getRegister(); if (regMap.containsKey(register)) { instruction.replaceRegister(register, regMap.get(register)); } } } } } new_pred.redirectOuts(loop.header, originalToCloneBBMap.get(loop.header), ir); blocks = loop.getBasicBlocks(); while (blocks.hasMoreElements()) { BasicBlock block = blocks.nextElement(); BasicBlock copy = originalToCloneBBMap.get(block); Enumeration<BasicBlock> outs = block.getOutNodes(); while (outs.hasMoreElements()) { BasicBlock out = outs.nextElement(); if (originalToCloneBBMap.containsKey(out)) { copy.redirectOuts(out, originalToCloneBBMap.get(out), ir); } } } blocks = loop.getBasicBlocks(); while (blocks.hasMoreElements()) { BasicBlock block = blocks.nextElement(); BasicBlock copy = originalToCloneBBMap.get(block); IREnumeration.AllInstructionsEnum instructions = new IREnumeration.AllInstructionsEnum(ir, copy); while (instructions.hasMoreElements()) { Instruction instruction = instructions.nextElement(); if (Phi.conforms(instruction)) { for (int i = 0; i < Phi.getNumberOfValues(instruction); i++) { BasicBlock phi_predecessor = Phi.getPred(instruction, i).block; if (originalToCloneBBMap.containsKey(phi_predecessor)) { Phi.setPred(instruction, i, new BasicBlockOperand(originalToCloneBBMap.get(phi_predecessor))); } else { throw new Error(STR + phi_predecessor); } } } } } return originalToCloneBBMap; } | /**
* Create a clone of the loop replacing definitions in the cloned
* loop with those found in the register map and eliminate
* unnecessary bound checks
* @param loop - loop to clone
* @param regMap - mapping of original definition to new
* definition
* @param instrToEliminate - instructions to eliminate
* @param regToBlockMap - mapping of a register to its defining BB
* @return a mapping from original BBs to created BBs
*/ | Create a clone of the loop replacing definitions in the cloned loop with those found in the register map and eliminate unnecessary bound checks | createOptimizedLoop | {
"repo_name": "CodeOffloading/JikesRVM-CCO",
"path": "jikesrvm-3.1.3/rvm/src/org/jikesrvm/compilers/opt/ssa/LoopVersioning.java",
"license": "epl-1.0",
"size": 64303
} | [
"java.util.ArrayList",
"java.util.Enumeration",
"java.util.HashMap",
"org.jikesrvm.compilers.opt.controlflow.AnnotatedLSTNode",
"org.jikesrvm.compilers.opt.ir.BasicBlock",
"org.jikesrvm.compilers.opt.ir.BoundsCheck",
"org.jikesrvm.compilers.opt.ir.IREnumeration",
"org.jikesrvm.compilers.opt.ir.Instruction",
"org.jikesrvm.compilers.opt.ir.NullCheck",
"org.jikesrvm.compilers.opt.ir.Phi",
"org.jikesrvm.compilers.opt.ir.Register",
"org.jikesrvm.compilers.opt.ir.operand.BasicBlockOperand",
"org.jikesrvm.compilers.opt.ir.operand.Operand",
"org.jikesrvm.compilers.opt.ir.operand.RegisterOperand"
] | import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import org.jikesrvm.compilers.opt.controlflow.AnnotatedLSTNode; import org.jikesrvm.compilers.opt.ir.BasicBlock; import org.jikesrvm.compilers.opt.ir.BoundsCheck; import org.jikesrvm.compilers.opt.ir.IREnumeration; import org.jikesrvm.compilers.opt.ir.Instruction; import org.jikesrvm.compilers.opt.ir.NullCheck; import org.jikesrvm.compilers.opt.ir.Phi; import org.jikesrvm.compilers.opt.ir.Register; import org.jikesrvm.compilers.opt.ir.operand.BasicBlockOperand; import org.jikesrvm.compilers.opt.ir.operand.Operand; import org.jikesrvm.compilers.opt.ir.operand.RegisterOperand; | import java.util.*; import org.jikesrvm.compilers.opt.controlflow.*; import org.jikesrvm.compilers.opt.ir.*; import org.jikesrvm.compilers.opt.ir.operand.*; | [
"java.util",
"org.jikesrvm.compilers"
] | java.util; org.jikesrvm.compilers; | 326,322 |
private InputStream getInputStream() {
return new ByteArrayInputStream(bytes);
}
| InputStream function() { return new ByteArrayInputStream(bytes); } | /**
* Creates and returns a new ByteArrayInputStream
*
* @return a new ByteArrayInputStream
*/ | Creates and returns a new ByteArrayInputStream | getInputStream | {
"repo_name": "BackupTheBerlios/arara-svn",
"path": "core/tags/arara-1.0/src/main/java/net/indrix/arara/applets/sound/SoundPlayer.java",
"license": "gpl-2.0",
"size": 3696
} | [
"java.io.ByteArrayInputStream",
"java.io.InputStream"
] | import java.io.ByteArrayInputStream; import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 1,266,530 |
public void addBitmapToCache(String data, Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
addBitmapToMemoryCache(data, bitmap);
addBitmapToDiskCache(data, bitmap);
} | void function(String data, Bitmap bitmap) { if (data == null bitmap == null) { return; } addBitmapToMemoryCache(data, bitmap); addBitmapToDiskCache(data, bitmap); } | /**
* Adds a bitmap to both memory and disk cache.
*
* @param data Unique identifier for the bitmap to store
* @param bitmap The bitmap to store
*/ | Adds a bitmap to both memory and disk cache | addBitmapToCache | {
"repo_name": "kaaholst/android-squeezer",
"path": "Squeezer/src/main/java/uk/org/ngo/squeezer/util/ImageCache.java",
"license": "apache-2.0",
"size": 23185
} | [
"android.graphics.Bitmap"
] | import android.graphics.Bitmap; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 40,194 |
@GET
@Consumes({ MediaType.WILDCARD })
public void blockResourceCreatorAsHtml(@PathParam("serviceProviderId") final String serviceProviderId)
throws IOException, ServletException {
// Start of user code (MUST_FILL_IN) resourceCreatorAsHTML_init
// End of user code
httpServletRequest.setAttribute("serviceProviderId", serviceProviderId);
RequestDispatcher rd = httpServletRequest
.getRequestDispatcher("/hu/bme/mit/simulink/oslc/adaptor/blockresourcecreator_html.jsp");
rd.forward(httpServletRequest, httpServletResponse);
} | @Consumes({ MediaType.WILDCARD }) void function(@PathParam(STR) final String serviceProviderId) throws IOException, ServletException { httpServletRequest.setAttribute(STR, serviceProviderId); RequestDispatcher rd = httpServletRequest .getRequestDispatcher(STR); rd.forward(httpServletRequest, httpServletResponse); } | /**
* OSLC delegated creation dialog for a single change request
* <p>
* Forwards to changerequest_creator.jsp to build the html form
*
* @param productId
* @throws IOException
* @throws ServletException
*/ | OSLC delegated creation dialog for a single change request Forwards to changerequest_creator.jsp to build the html form | blockResourceCreatorAsHtml | {
"repo_name": "FTSRG/massif",
"path": "maven/hu.bme.mit.massif.oslc.adaptor/src/main/java/hu/bme/mit/massif/oslc/adaptor/services/BlockResourceService.java",
"license": "epl-1.0",
"size": 19501
} | [
"java.io.IOException",
"javax.servlet.RequestDispatcher",
"javax.servlet.ServletException",
"javax.ws.rs.Consumes",
"javax.ws.rs.PathParam",
"javax.ws.rs.core.MediaType"
] | import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.ws.rs.Consumes; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; | import java.io.*; import javax.servlet.*; import javax.ws.rs.*; import javax.ws.rs.core.*; | [
"java.io",
"javax.servlet",
"javax.ws"
] | java.io; javax.servlet; javax.ws; | 534,788 |
//ADDED
@ApiMethod(name = "getEmployees", httpMethod = "POST", path = "getEmployees")
public MasterObject getEmployees(User dto) throws Exception {
//TEST
//Check params first
if(dto == null){
throw new Exception("No object passed");
}
String sessionId = dto.getSessionId();
if(sessionId == null){
throw new Exception("No Session ID Passed");
}
if(sessionId.isEmpty()){
throw new Exception("No Session ID Passed");
}
boolean bool = false;
try {
bool = TESTDatastoreManager.validateSession(sessionId);
} catch (Exception e){
e.printStackTrace();
}
List<Employee> returnedList = new ArrayList<>();
MasterObject masterObject = new MasterObject();
//Error message Emp
MasterObject errorEmp = new MasterObject();
//If the session is not valid, send them back this
if(!bool){
errorEmp.setMessage("SessionId has expired!");
return masterObject;
}
//Once checked, get the list
try {
log.severe("" + 148);
returnedList = TESTDatastoreManager.getAllEmployees();
log.severe("" + 150);
if (returnedList != null){
log.severe("" + 152);
if(returnedList.size() > 0){
masterObject.setEmployees(returnedList);
log.severe("" + 154);
return masterObject;
} else {
log.severe("" + 157);
masterObject.setMessage("No Employees in the list!");
return masterObject;
}
} else {
errorEmp.setMessage("No Employees in the list!");
//Since it is null, will need to reInitialize
masterObject = new MasterObject();
masterObject.setMessage("No Employees In the list");
return masterObject;
}
} catch (Exception e){
e.printStackTrace();
throw new Exception(e.toString());
}
}
| @ApiMethod(name = STR, httpMethod = "POST", path = STR) MasterObject function(User dto) throws Exception { if(dto == null){ throw new Exception(STR); } String sessionId = dto.getSessionId(); if(sessionId == null){ throw new Exception(STR); } if(sessionId.isEmpty()){ throw new Exception(STR); } boolean bool = false; try { bool = TESTDatastoreManager.validateSession(sessionId); } catch (Exception e){ e.printStackTrace(); } List<Employee> returnedList = new ArrayList<>(); MasterObject masterObject = new MasterObject(); MasterObject errorEmp = new MasterObject(); if(!bool){ errorEmp.setMessage(STR); return masterObject; } try { log.severe(STRSTRSTRSTRSTRNo Employees in the list!STRNo Employees in the list!STRNo Employees In the list"); return masterObject; } } catch (Exception e){ e.printStackTrace(); throw new Exception(e.toString()); } } | /**
* Retrieve a list of all employees
* @param dto This is the User DTO to be taken in. Requires the SessionId
* @return Returns a list of Employees
* @throws Exception
*/ | Retrieve a list of all employees | getEmployees | {
"repo_name": "PGMacDesign/Google_App_Engine_AndroidTest",
"path": "src/com/pgmacdesign/androidtest/endpoints/TestEndpoint.java",
"license": "apache-2.0",
"size": 14052
} | [
"com.google.api.server.spi.config.ApiMethod",
"com.pgmacdesign.androidtest.datamanagement.TESTDatastoreManager",
"com.pgmacdesign.androidtest.dto.Employee",
"com.pgmacdesign.androidtest.dto.MasterObject",
"com.pgmacdesign.androidtest.dto.User",
"java.util.ArrayList",
"java.util.List"
] | import com.google.api.server.spi.config.ApiMethod; import com.pgmacdesign.androidtest.datamanagement.TESTDatastoreManager; import com.pgmacdesign.androidtest.dto.Employee; import com.pgmacdesign.androidtest.dto.MasterObject; import com.pgmacdesign.androidtest.dto.User; import java.util.ArrayList; import java.util.List; | import com.google.api.server.spi.config.*; import com.pgmacdesign.androidtest.datamanagement.*; import com.pgmacdesign.androidtest.dto.*; import java.util.*; | [
"com.google.api",
"com.pgmacdesign.androidtest",
"java.util"
] | com.google.api; com.pgmacdesign.androidtest; java.util; | 2,334,490 |
Subsets and Splits