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 FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Integer result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
result = new Integer(argumentOne.compareTo(argumentTwo));
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
} | FunctionResult function(final Evaluator evaluator, final String arguments) throws FunctionException { Integer result = null; String exceptionMessage = STR; ArrayList strings = FunctionHelper.getStrings(arguments, EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR); if (strings.size() != 2) { throw new FunctionException(exceptionMessage); } try { String argumentOne = FunctionHelper.trimAndRemoveQuoteChars( (String) strings.get(0), evaluator.getQuoteCharacter()); String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars( (String) strings.get(1), evaluator.getQuoteCharacter()); result = new Integer(argumentOne.compareTo(argumentTwo)); } catch (FunctionException fe) { throw new FunctionException(fe.getMessage(), fe); } catch (Exception e) { throw new FunctionException(exceptionMessage, e); } return new FunctionResult(result.toString(), FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC); } | /**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is the first string to compare
* and the second argument is the second string to compare. The
* string argument(s) HAS to be enclosed in quotes. White space
* that is not enclosed within quotes will be trimmed. Quote
* characters in the first and last positions of any string
* argument (after being trimmed) will be removed also. The quote
* characters used must be the same as the quote characters used
* by the current instance of Evaluator. If there are multiple
* arguments, they must be separated by a comma (",").
*
* @return Returns an integer value of zero if the strings are equal, an
* integer value less than zero if the first string precedes the
* second string or an integer value greater than zero if the first
* string follows the second string.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/ | Executes the function for the specified argument. This method is called internally by Evaluator | execute | {
"repo_name": "ijlalhussain/LogGenerator",
"path": "DeclareDesigner/src/net/sourceforge/jeval/function/string/CompareTo.java",
"license": "gpl-3.0",
"size": 3831
} | [
"java.util.ArrayList",
"net.sourceforge.jeval.EvaluationConstants",
"net.sourceforge.jeval.Evaluator",
"net.sourceforge.jeval.function.FunctionConstants",
"net.sourceforge.jeval.function.FunctionException",
"net.sourceforge.jeval.function.FunctionHelper",
"net.sourceforge.jeval.function.FunctionResult"
] | import java.util.ArrayList; import net.sourceforge.jeval.EvaluationConstants; import net.sourceforge.jeval.Evaluator; import net.sourceforge.jeval.function.FunctionConstants; import net.sourceforge.jeval.function.FunctionException; import net.sourceforge.jeval.function.FunctionHelper; import net.sourceforge.jeval.function.FunctionResult; | import java.util.*; import net.sourceforge.jeval.*; import net.sourceforge.jeval.function.*; | [
"java.util",
"net.sourceforge.jeval"
] | java.util; net.sourceforge.jeval; | 1,022,940 |
private JPanel getProgressBarPanel() {
if (progressBarPanel == null) {
progressBarPanel = new JPanel();
progressBarPanel.setLayout(new BorderLayout());
progressBarPanel.setSize(PROGRESS_SLIDER_DEFAULT_SIZE);
progressBarPanel.setPreferredSize(PROGRESS_SLIDER_DEFAULT_SIZE);
progressBarPanel.setMinimumSize(PROGRESS_SLIDER_MINIMUM_SIZE);
progressBarPanel.setMaximumSize(PROGRESS_SLIDER_MAXIMUM_SIZE);
progressBarPanel.add(getProgresSlider(), BorderLayout.NORTH);
}
return progressBarPanel;
}
| JPanel function() { if (progressBarPanel == null) { progressBarPanel = new JPanel(); progressBarPanel.setLayout(new BorderLayout()); progressBarPanel.setSize(PROGRESS_SLIDER_DEFAULT_SIZE); progressBarPanel.setPreferredSize(PROGRESS_SLIDER_DEFAULT_SIZE); progressBarPanel.setMinimumSize(PROGRESS_SLIDER_MINIMUM_SIZE); progressBarPanel.setMaximumSize(PROGRESS_SLIDER_MAXIMUM_SIZE); progressBarPanel.add(getProgresSlider(), BorderLayout.NORTH); } return progressBarPanel; } | /**
* This method initializes progressBarPanel
*
* @return javax.swing.JPanel
*/ | This method initializes progressBarPanel | getProgressBarPanel | {
"repo_name": "josdem/client",
"path": "client-view/src/main/java/com/all/client/view/InfoPlayerPanel.java",
"license": "apache-2.0",
"size": 39365
} | [
"java.awt.BorderLayout",
"javax.swing.JPanel"
] | import java.awt.BorderLayout; import javax.swing.JPanel; | import java.awt.*; import javax.swing.*; | [
"java.awt",
"javax.swing"
] | java.awt; javax.swing; | 1,168,134 |
public static Nullness getNullnessValue(ExpressionTree expr, VisitorState state,
NullnessAnalysis nullnessAnalysis) {
TreePath pathToExpr = new TreePath(state.getPath(), expr);
return nullnessAnalysis.getNullness(pathToExpr, state.context);
} | static Nullness function(ExpressionTree expr, VisitorState state, NullnessAnalysis nullnessAnalysis) { TreePath pathToExpr = new TreePath(state.getPath(), expr); return nullnessAnalysis.getNullness(pathToExpr, state.context); } | /**
* Returns the {@link Nullness} for an expression as determined by the nullness dataflow
* analysis.
*/ | Returns the <code>Nullness</code> for an expression as determined by the nullness dataflow analysis | getNullnessValue | {
"repo_name": "davidzchen/error-prone",
"path": "core/src/main/java/com/google/errorprone/util/ASTHelpers.java",
"license": "apache-2.0",
"size": 22661
} | [
"com.google.errorprone.VisitorState",
"com.google.errorprone.dataflow.nullnesspropagation.Nullness",
"com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis",
"com.sun.source.tree.ExpressionTree",
"com.sun.source.util.TreePath"
] | import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis; import com.sun.source.tree.ExpressionTree; import com.sun.source.util.TreePath; | import com.google.errorprone.*; import com.google.errorprone.dataflow.nullnesspropagation.*; import com.sun.source.tree.*; import com.sun.source.util.*; | [
"com.google.errorprone",
"com.sun.source"
] | com.google.errorprone; com.sun.source; | 121,892 |
@Override
public Iterable<Map.Entry<K, V>> entries() {
return Collections.unmodifiableSet(state.entrySet());
} | Iterable<Map.Entry<K, V>> function() { return Collections.unmodifiableSet(state.entrySet()); } | /**
* Returns all the mappings in the state in a {@link Collections#unmodifiableSet(Set)}.
*
* @return A read-only iterable view of all the key-value pairs in the state.
*/ | Returns all the mappings in the state in a <code>Collections#unmodifiableSet(Set)</code> | entries | {
"repo_name": "yew1eb/flink",
"path": "flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/state/ImmutableMapState.java",
"license": "apache-2.0",
"size": 4028
} | [
"java.util.Collections",
"java.util.Map"
] | import java.util.Collections; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,129,588 |
private double[] generateCustomFrequencies(int tone, int octave,
double[] frequencies, Set<PreciseTuning> preciseTunings) {
double[] customFrequencies = frequencies;
int toneNumber = getMidiNoteNumber(tone, octave);
double toneFrequency = frequencies[toneNumber];
int noteNumber;
double relativeFrequency;
double customCents;
double customFrequency;
for (PreciseTuning p : preciseTunings) {
noteNumber = getMidiNoteNumber(p.getNote(), p.getOctave());
relativeFrequency = frequencies[noteNumber];
customCents = getCents(toneFrequency, relativeFrequency) + p.getCents();
customFrequency = getRelativeFrequency(toneFrequency, customCents);
if (isLegitFrequency(noteNumber, customFrequency, customFrequencies)) {
customFrequencies[noteNumber] = customFrequency;
}
}
return customFrequencies;
}
| double[] function(int tone, int octave, double[] frequencies, Set<PreciseTuning> preciseTunings) { double[] customFrequencies = frequencies; int toneNumber = getMidiNoteNumber(tone, octave); double toneFrequency = frequencies[toneNumber]; int noteNumber; double relativeFrequency; double customCents; double customFrequency; for (PreciseTuning p : preciseTunings) { noteNumber = getMidiNoteNumber(p.getNote(), p.getOctave()); relativeFrequency = frequencies[noteNumber]; customCents = getCents(toneFrequency, relativeFrequency) + p.getCents(); customFrequency = getRelativeFrequency(toneFrequency, customCents); if (isLegitFrequency(noteNumber, customFrequency, customFrequencies)) { customFrequencies[noteNumber] = customFrequency; } } return customFrequencies; } | /**
* Generate special frequencies for the given custom tunings.
* @param tone Base/tuning tone/note (0 to 11).
* @param octave Base/tuning octave (-1 to 9).
* @param frequencies Original frequencies.
* @param preciseTunings User custom tunings.
* @return Custom frequencies.
*/ | Generate special frequencies for the given custom tunings | generateCustomFrequencies | {
"repo_name": "proxecto-puding/proxecto-puding",
"path": "src/gui/src/main/java/org/proxectopuding/gui/model/utils/MidiUtils.java",
"license": "gpl-3.0",
"size": 11004
} | [
"java.util.Set",
"org.proxectopuding.gui.model.entities.PreciseTuning"
] | import java.util.Set; import org.proxectopuding.gui.model.entities.PreciseTuning; | import java.util.*; import org.proxectopuding.gui.model.entities.*; | [
"java.util",
"org.proxectopuding.gui"
] | java.util; org.proxectopuding.gui; | 2,865,023 |
public static <T extends Item> List<T> fromNameList(ItemGroup context, @Nonnull String list, @Nonnull Class<T> type) {
final Jenkins jenkins = Jenkins.getInstance();
List<T> r = new ArrayList<T>();
if (jenkins == null) {
return r;
}
StringTokenizer tokens = new StringTokenizer(list,",");
while(tokens.hasMoreTokens()) {
String fullName = tokens.nextToken().trim();
if (StringUtils.isNotEmpty(fullName)) {
T item = jenkins.getItem(fullName, context, type);
if(item!=null)
r.add(item);
}
}
return r;
} | static <T extends Item> List<T> function(ItemGroup context, @Nonnull String list, @Nonnull Class<T> type) { final Jenkins jenkins = Jenkins.getInstance(); List<T> r = new ArrayList<T>(); if (jenkins == null) { return r; } StringTokenizer tokens = new StringTokenizer(list,","); while(tokens.hasMoreTokens()) { String fullName = tokens.nextToken().trim(); if (StringUtils.isNotEmpty(fullName)) { T item = jenkins.getItem(fullName, context, type); if(item!=null) r.add(item); } } return r; } | /**
* Does the opposite of {@link #toNameList(Collection)}.
*/ | Does the opposite of <code>#toNameList(Collection)</code> | fromNameList | {
"repo_name": "jpbriend/jenkins",
"path": "core/src/main/java/hudson/model/Items.java",
"license": "mit",
"size": 18312
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.StringTokenizer",
"javax.annotation.Nonnull",
"org.apache.commons.lang.StringUtils"
] | import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; | import java.util.*; import javax.annotation.*; import org.apache.commons.lang.*; | [
"java.util",
"javax.annotation",
"org.apache.commons"
] | java.util; javax.annotation; org.apache.commons; | 134,836 |
public static ObjectInputStream readDataFromDevice(Socket socket) throws IOException, ClassNotFoundException {
System.out.println("Synching information");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
// Mobile clipboard has been sent for updation.
if(!"".equals(message)) {
System.out.println("Mobile sent its clipboard " + message);
setDesktopClipBoard(message);
} else {
System.out.println("Mobile clipboard didn't change, received dummy request");
}
return ois;
}
}
| static ObjectInputStream function(Socket socket) throws IOException, ClassNotFoundException { System.out.println(STR); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String message = (String) ois.readObject(); if(!STRMobile sent its clipboard STRMobile clipboard didn't change, received dummy request"); } return ois; } } | /**
* Reads the data that was sent by the Android device
* @param socket
* @throws IOException
* @throws ClassNotFoundException
*/ | Reads the data that was sent by the Android device | readDataFromDevice | {
"repo_name": "Adeor/android-desktop-sync",
"path": "DesktopServer/src/com/swaroop/projects/JavaDesktopClipboardAccessServer.java",
"license": "apache-2.0",
"size": 5575
} | [
"java.io.IOException",
"java.io.ObjectInputStream",
"java.net.Socket"
] | import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket; | import java.io.*; import java.net.*; | [
"java.io",
"java.net"
] | java.io; java.net; | 1,243,568 |
final String spName = Utils.createRandomName("sp");
final String appName = SdkContext.randomResourceName("app", 20);
final String appUrl = "https://" + appName;
final String passwordName1 = SdkContext.randomResourceName("password", 20);
final String password1 = "P@ssw0rd";
final String passwordName2 = SdkContext.randomResourceName("password", 20);
final String password2 = "StrongP@ss!12";
final String certName1 = SdkContext.randomResourceName("cert", 20);
final String raName = SdkContext.randomUuid();
String servicePrincipalId = "";
try {
// ============================================================
// Create service principal
System.out.println("Creating an Active Directory service principal " + spName + "...");
ServicePrincipal servicePrincipal = authenticated.servicePrincipals()
.define(spName)
.withNewApplication(appUrl)
.definePasswordCredential(passwordName1)
.withPasswordValue(password1)
.attach()
.definePasswordCredential(passwordName2)
.withPasswordValue(password2)
.attach()
.defineCertificateCredential(certName1)
.withAsymmetricX509Certificate()
.withPublicKey(ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer")))
.withDuration(Duration.standardDays(1))
.attach()
.create();
System.out.println("Created service principal " + spName + ".");
Utils.print(servicePrincipal);
servicePrincipalId = servicePrincipal.id();
// ============================================================
// Create role assignment
System.out.println("Creating a Contributor role assignment " + raName + " for the service principal...");
Thread.sleep(15000);
RoleAssignment roleAssignment = authenticated.roleAssignments()
.define(raName)
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(BuiltInRole.CONTRIBUTOR)
.withSubscriptionScope(defaultSubscription)
.create();
System.out.println("Created role assignment " + raName + ".");
Utils.print(roleAssignment);
// ============================================================
// Verify the credentials are valid
System.out.println("Verifying password credential " + passwordName1 + " is valid...");
ApplicationTokenCredentials testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + passwordName1 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + passwordName1 + " is valid.");
}
System.out.println("Verifying password credential " + passwordName2 + " is valid...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + passwordName2 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + passwordName2 + " is valid.");
}
System.out.println("Verifying certificate credential " + certName1 + " is valid...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(),
authenticated.tenantId(),
ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.pfx")),
"Abc123",
environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + certName1 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + certName1 + " is valid.");
}
// ============================================================
// Revoke access of the 1st password credential
System.out.println("Revoking access for password credential " + passwordName1 + "...");
servicePrincipal.update()
.withoutCredential(passwordName1)
.apply();
SdkContext.sleep(15000);
System.out.println("Credential revoked.");
// ============================================================
// Verify the revoked password credential is no longer valid
System.out.println("Verifying password credential " + passwordName1 + " is revoked...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Failed to verify " + passwordName1 + " is revoked.");
} catch (Exception e) {
System.out.println("Verified " + passwordName1 + " is revoked.");
}
// ============================================================
// Revoke the role assignment
System.out.println("Revoking role assignment " + raName + "...");
authenticated.roleAssignments().deleteById(roleAssignment.id());
SdkContext.sleep(5000);
// ============================================================
// Verify the revoked password credential is no longer valid
System.out.println("Verifying password credential " + passwordName2 + " has no access to subscription...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription()
.resourceGroups().list();
System.out.println("Failed to verify " + passwordName2 + " has no access to subscription.");
} catch (Exception e) {
System.out.println("Verified " + passwordName2 + " has no access to subscription.");
}
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting application: " + appName);
authenticated.servicePrincipals().deleteById(servicePrincipalId);
System.out.println("Deleted application: " + appName);
}
catch (Exception e) {
System.out.println("Did not create applications in Azure. No clean up is necessary");
}
}
return false;
} | final String spName = Utils.createRandomName("sp"); final String appName = SdkContext.randomResourceName("app", 20); final String appUrl = STRpasswordSTRP@ssw0rdSTRpasswordSTRStrongP@ss!12STRcertSTRSTRCreating an Active Directory service principal STR...STR/myTest.cerSTRCreated service principal STR.STRCreating a Contributor role assignment STR for the service principal...STRCreated role assignment STR.STRVerifying password credential STR is valid...STRVerified STR is valid.STRFailed to verify STR is valid.STRVerifying password credential STR is valid...STRVerified STR is valid.STRFailed to verify STR is valid.STRVerifying certificate credential STR is valid...STR/myTest.pfxSTRAbc123STRVerified STR is valid.STRFailed to verify STR is valid.STRRevoking access for password credential STR...STRCredential revoked.STRVerifying password credential STR is revoked...STRFailed to verify STR is revoked.STRVerified STR is revoked.STRRevoking role assignment STR...STRVerifying password credential STR has no access to subscription...STRFailed to verify STR has no access to subscription.STRVerified STR has no access to subscription.STRDeleting application: STRDeleted application: STRDid not create applications in Azure. No clean up is necessary"); } } return false; } | /**
* Main function which runs the actual sample.
*
* @param authenticated instance of Authenticated
* @param defaultSubscription default subscription id
* @param environment the environment the sample is running in
* @return true if sample runs successfully
*/ | Main function which runs the actual sample | runSample | {
"repo_name": "martinsawicki/azure-sdk-for-java",
"path": "azure-samples/src/main/java/com/microsoft/azure/management/graphrbac/samples/ManageServicePrincipalCredentials.java",
"license": "mit",
"size": 10249
} | [
"com.microsoft.azure.management.Azure",
"com.microsoft.azure.management.resources.fluentcore.utils.SdkContext",
"com.microsoft.azure.management.samples.Utils"
] | import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; import com.microsoft.azure.management.samples.Utils; | import com.microsoft.azure.management.*; import com.microsoft.azure.management.resources.fluentcore.utils.*; import com.microsoft.azure.management.samples.*; | [
"com.microsoft.azure"
] | com.microsoft.azure; | 1,287,311 |
private void sendHandshakeSetConfig() throws IOException {
List<OFMessage> msglist = new ArrayList<OFMessage>(3);
// Ensure we receive the full packet via PacketIn
// FIXME: We don't set the reassembly flags.
OFSetConfig configSet = (OFSetConfig) BasicFactory.getInstance()
.getMessage(OFType.SET_CONFIG);
configSet.setMissSendLength((short) 0xffff)
.setLengthU(OFSwitchConfig.MINIMUM_LENGTH);
configSet.setXid(handshakeTransactionIds--);
msglist.add(configSet);
// Barrier
OFBarrierRequest barrier = (OFBarrierRequest) BasicFactory.getInstance()
.getMessage(OFType.BARRIER_REQUEST);
barrier.setXid(handshakeTransactionIds--);
msglist.add(barrier);
// Verify (need barrier?)
OFGetConfigRequest configReq = (OFGetConfigRequest)
BasicFactory.getInstance().getMessage(OFType.GET_CONFIG_REQUEST);
configReq.setXid(handshakeTransactionIds--);
msglist.add(configReq);
//Count Configurations Request messages
if (PerSwitchStatistics.createSwitchCounterIfNotExists(HexString.toHexString(this.featuresReply.getDatapathId()))) {
PerSwitchStatistics.getSwitches_map().get(HexString.toHexString(this.featuresReply.getDatapathId()))
.addConfigurationsRequestMessage(configReq.getLength());
}
channel.write(msglist);
} | void function() throws IOException { List<OFMessage> msglist = new ArrayList<OFMessage>(3); OFSetConfig configSet = (OFSetConfig) BasicFactory.getInstance() .getMessage(OFType.SET_CONFIG); configSet.setMissSendLength((short) 0xffff) .setLengthU(OFSwitchConfig.MINIMUM_LENGTH); configSet.setXid(handshakeTransactionIds--); msglist.add(configSet); OFBarrierRequest barrier = (OFBarrierRequest) BasicFactory.getInstance() .getMessage(OFType.BARRIER_REQUEST); barrier.setXid(handshakeTransactionIds--); msglist.add(barrier); OFGetConfigRequest configReq = (OFGetConfigRequest) BasicFactory.getInstance().getMessage(OFType.GET_CONFIG_REQUEST); configReq.setXid(handshakeTransactionIds--); msglist.add(configReq); if (PerSwitchStatistics.createSwitchCounterIfNotExists(HexString.toHexString(this.featuresReply.getDatapathId()))) { PerSwitchStatistics.getSwitches_map().get(HexString.toHexString(this.featuresReply.getDatapathId())) .addConfigurationsRequestMessage(configReq.getLength()); } channel.write(msglist); } | /**
* Send the configuration requests to tell the switch we want full
* packets
* @throws IOException
*/ | Send the configuration requests to tell the switch we want full packets | sendHandshakeSetConfig | {
"repo_name": "phisolani/floodlight",
"path": "src/main/java/net/floodlightcontroller/core/internal/OFChannelHandler.java",
"license": "apache-2.0",
"size": 81702
} | [
"java.io.IOException",
"java.util.ArrayList",
"java.util.List",
"net.floodlightcontroller.core.statistics.PerSwitchStatistics",
"org.openflow.protocol.OFBarrierRequest",
"org.openflow.protocol.OFGetConfigRequest",
"org.openflow.protocol.OFMessage",
"org.openflow.protocol.OFSetConfig",
"org.openflow.protocol.OFSwitchConfig",
"org.openflow.protocol.OFType",
"org.openflow.protocol.factory.BasicFactory",
"org.openflow.util.HexString"
] | import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.floodlightcontroller.core.statistics.PerSwitchStatistics; import org.openflow.protocol.OFBarrierRequest; import org.openflow.protocol.OFGetConfigRequest; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFSwitchConfig; import org.openflow.protocol.OFType; import org.openflow.protocol.factory.BasicFactory; import org.openflow.util.HexString; | import java.io.*; import java.util.*; import net.floodlightcontroller.core.statistics.*; import org.openflow.protocol.*; import org.openflow.protocol.factory.*; import org.openflow.util.*; | [
"java.io",
"java.util",
"net.floodlightcontroller.core",
"org.openflow.protocol",
"org.openflow.util"
] | java.io; java.util; net.floodlightcontroller.core; org.openflow.protocol; org.openflow.util; | 1,111,462 |
protected Image getImage(Plot plot, int series, int item,
double x, double y) {
// this method must be overridden if you want to display images
return null;
}
| Image function(Plot plot, int series, int item, double x, double y) { return null; } | /**
* Returns the image used to draw a single data item.
*
* @param plot the plot (can be used to obtain standard color information
* etc).
* @param series the series index.
* @param item the item index.
* @param x the x value of the item.
* @param y the y value of the item.
*
* @return The image.
*
* @see #getPlotImages()
*/ | Returns the image used to draw a single data item | getImage | {
"repo_name": "fluidware/Eastwood-Charts",
"path": "source/org/jfree/chart/renderer/xy/StandardXYItemRenderer.java",
"license": "lgpl-2.1",
"size": 41764
} | [
"java.awt.Image",
"org.jfree.chart.plot.Plot"
] | import java.awt.Image; import org.jfree.chart.plot.Plot; | import java.awt.*; import org.jfree.chart.plot.*; | [
"java.awt",
"org.jfree.chart"
] | java.awt; org.jfree.chart; | 1,725,798 |
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory} | void function(Resource configLocation) { this.configLocation = configLocation; } /** * Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory} | /**
* Set the location of the MyBatis {@code SqlSessionFactory} config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*/ | Set the location of the MyBatis SqlSessionFactory config file. A typical value is "WEB-INF/mybatis-configuration.xml" | setConfigLocation | {
"repo_name": "lanyonm/mybatis-spring",
"path": "src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java",
"license": "apache-2.0",
"size": 17727
} | [
"org.apache.ibatis.session.SqlSessionFactory",
"org.springframework.core.io.Resource"
] | import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.core.io.Resource; | import org.apache.ibatis.session.*; import org.springframework.core.io.*; | [
"org.apache.ibatis",
"org.springframework.core"
] | org.apache.ibatis; org.springframework.core; | 2,736,149 |
void getLogicalToVisualRunsMap()
{
if (isGoodLogicalToVisualRunsMap) {
return;
}
int count = countRuns();
if ((logicalToVisualRunsMap == null) ||
(logicalToVisualRunsMap.length < count)) {
logicalToVisualRunsMap = new int[count];
}
int i;
long[] keys = new long[count];
for (i = 0; i < count; i++) {
keys[i] = ((long)(runs[i].start)<<32) + i;
}
Arrays.sort(keys);
for (i = 0; i < count; i++) {
logicalToVisualRunsMap[i] = (int)(keys[i] & 0x00000000FFFFFFFF);
}
keys = null;
isGoodLogicalToVisualRunsMap = true;
} | void getLogicalToVisualRunsMap() { if (isGoodLogicalToVisualRunsMap) { return; } int count = countRuns(); if ((logicalToVisualRunsMap == null) (logicalToVisualRunsMap.length < count)) { logicalToVisualRunsMap = new int[count]; } int i; long[] keys = new long[count]; for (i = 0; i < count; i++) { keys[i] = ((long)(runs[i].start)<<32) + i; } Arrays.sort(keys); for (i = 0; i < count; i++) { logicalToVisualRunsMap[i] = (int)(keys[i] & 0x00000000FFFFFFFF); } keys = null; isGoodLogicalToVisualRunsMap = true; } | /**
* Compute the logical to visual run mapping
*/ | Compute the logical to visual run mapping | getLogicalToVisualRunsMap | {
"repo_name": "UweTrottmann/QuickDic-Dictionary",
"path": "jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/text/Bidi.java",
"license": "apache-2.0",
"size": 216165
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 396,513 |
public void setOnChartGestureListener(OnChartGestureListener l) {
this.mGestureListener = l;
} | void function(OnChartGestureListener l) { this.mGestureListener = l; } | /**
* Sets a gesture-listener for the chart for custom callbacks when executing
* gestures on the chart surface.
*
* @param l
*/ | Sets a gesture-listener for the chart for custom callbacks when executing gestures on the chart surface | setOnChartGestureListener | {
"repo_name": "MPieter/Notification-Analyser",
"path": "NotificationAnalyser/MPChartLib/src/com/github/mikephil/charting/charts/Chart.java",
"license": "mit",
"size": 71102
} | [
"com.github.mikephil.charting.interfaces.OnChartGestureListener"
] | import com.github.mikephil.charting.interfaces.OnChartGestureListener; | import com.github.mikephil.charting.interfaces.*; | [
"com.github.mikephil"
] | com.github.mikephil; | 1,274,543 |
@Override
public PathEntity getPathToEntityLiving(Entity par1Entity){
return getPathEntityToEntity(pathfindingEntity, par1Entity, getPathSearchRange(), false, false, true, false);
} | PathEntity function(Entity par1Entity){ return getPathEntityToEntity(pathfindingEntity, par1Entity, getPathSearchRange(), false, false, true, false); } | /**
* Returns the path to the given EntityLiving
*/ | Returns the path to the given EntityLiving | getPathToEntityLiving | {
"repo_name": "wormzjl/PneumaticCraft",
"path": "src/pneumaticCraft/common/ai/EntityPathNavigateDrone.java",
"license": "gpl-3.0",
"size": 8280
} | [
"net.minecraft.entity.Entity",
"net.minecraft.pathfinding.PathEntity"
] | import net.minecraft.entity.Entity; import net.minecraft.pathfinding.PathEntity; | import net.minecraft.entity.*; import net.minecraft.pathfinding.*; | [
"net.minecraft.entity",
"net.minecraft.pathfinding"
] | net.minecraft.entity; net.minecraft.pathfinding; | 1,847,783 |
void getAllBreakpoints(@NotNull String id, @NotNull AsyncRequestCallback<String> callback); | void getAllBreakpoints(@NotNull String id, @NotNull AsyncRequestCallback<String> callback); | /**
* Returns list of breakpoints.
*
* @param id
* @param callback
*/ | Returns list of breakpoints | getAllBreakpoints | {
"repo_name": "dhuebner/che",
"path": "plugins/plugin-java/che-plugin-java-ext-debugger-java-client/src/main/java/org/eclipse/che/ide/ext/java/jdi/client/debug/DebuggerServiceClient.java",
"license": "epl-1.0",
"size": 4312
} | [
"javax.validation.constraints.NotNull",
"org.eclipse.che.ide.rest.AsyncRequestCallback"
] | import javax.validation.constraints.NotNull; import org.eclipse.che.ide.rest.AsyncRequestCallback; | import javax.validation.constraints.*; import org.eclipse.che.ide.rest.*; | [
"javax.validation",
"org.eclipse.che"
] | javax.validation; org.eclipse.che; | 87,426 |
protected boolean PrimaryExpr() throws javax.xml.transform.TransformerException
{
boolean matchFound;
int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
if ((m_tokenChar == '\'') || (m_tokenChar == '"'))
{
appendOp(2, OpCodes.OP_LITERAL);
Literal();
m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
matchFound = true;
}
else if (m_tokenChar == '$')
{
nextToken(); // consume '$'
appendOp(2, OpCodes.OP_VARIABLE);
QName();
m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
matchFound = true;
}
else if (m_tokenChar == '(')
{
nextToken();
appendOp(2, OpCodes.OP_GROUP);
Expr();
consumeExpected(')');
m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
matchFound = true;
}
else if ((null != m_token) && ((('.' == m_tokenChar) && (m_token.length() > 1) && Character.isDigit(
m_token.charAt(1))) || Character.isDigit(m_tokenChar)))
{
appendOp(2, OpCodes.OP_NUMBERLIT);
Number();
m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
matchFound = true;
}
else if (lookahead('(', 1) || (lookahead(':', 1) && lookahead('(', 3)))
{
matchFound = FunctionCall();
}
else
{
matchFound = false;
}
return matchFound;
} | boolean function() throws javax.xml.transform.TransformerException { boolean matchFound; int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH); if ((m_tokenChar == '\'') (m_tokenChar == '"')) { appendOp(2, OpCodes.OP_LITERAL); Literal(); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); matchFound = true; } else if (m_tokenChar == '$') { nextToken(); appendOp(2, OpCodes.OP_VARIABLE); QName(); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); matchFound = true; } else if (m_tokenChar == '(') { nextToken(); appendOp(2, OpCodes.OP_GROUP); Expr(); consumeExpected(')'); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); matchFound = true; } else if ((null != m_token) && ((('.' == m_tokenChar) && (m_token.length() > 1) && Character.isDigit( m_token.charAt(1))) Character.isDigit(m_tokenChar))) { appendOp(2, OpCodes.OP_NUMBERLIT); Number(); m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos); matchFound = true; } else if (lookahead('(', 1) (lookahead(':', 1) && lookahead('(', 3))) { matchFound = FunctionCall(); } else { matchFound = false; } return matchFound; } | /**
*
* PrimaryExpr ::= VariableReference
* | '(' Expr ')'
* | Literal
* | Number
* | FunctionCall
*
* @return true if this method successfully matched a PrimaryExpr
*
* @throws javax.xml.transform.TransformerException
*
*/ | PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall | PrimaryExpr | {
"repo_name": "rokn/Count_Words_2015",
"path": "testing/openjdk2/jaxp/src/com/sun/org/apache/xpath/internal/compiler/XPathParser.java",
"license": "mit",
"size": 63899
} | [
"javax.xml.transform.TransformerException"
] | import javax.xml.transform.TransformerException; | import javax.xml.transform.*; | [
"javax.xml"
] | javax.xml; | 1,544,356 |
EAttribute getNodeDef_Name();
| EAttribute getNodeDef_Name(); | /**
* Returns the meta object for the attribute '{@link com.openMap1.mapper.NodeDef#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see com.openMap1.mapper.NodeDef#getName()
* @see #getNodeDef()
* @generated
*/ | Returns the meta object for the attribute '<code>com.openMap1.mapper.NodeDef#getName Name</code>'. | getNodeDef_Name | {
"repo_name": "openmapsoftware/mappingtools",
"path": "openmap-mapper-lib/src/main/java/com/openMap1/mapper/MapperPackage.java",
"license": "epl-1.0",
"size": 172715
} | [
"org.eclipse.emf.ecore.EAttribute"
] | import org.eclipse.emf.ecore.EAttribute; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,184,770 |
public static DBMeta findDBMeta(Class<?> entityType) {
DBMeta dbmeta = byEntityType(entityType);
if (dbmeta == null) {
String msg = "The DB meta was not found by the entity type: key=" + entityType;
throw new DBMetaNotFoundException(msg);
}
return dbmeta;
} | static DBMeta function(Class<?> entityType) { DBMeta dbmeta = byEntityType(entityType); if (dbmeta == null) { String msg = STR + entityType; throw new DBMetaNotFoundException(msg); } return dbmeta; } | /**
* Find DB meta by entity type.
* @param entityType The entity type of table, which should implement the {@link Entity} interface. (NotNull)
* @return The instance of DB meta. (NotNull)
* @throws org.dbflute.exception.DBMetaNotFoundException When the DB meta is not found.
*/ | Find DB meta by entity type | findDBMeta | {
"repo_name": "dbflute-test/dbflute-test-dbms-mysql",
"path": "src/main/java/org/docksidestage/mysql/dbflute/resola/allcommon/ResolaDBMetaInstanceHandler.java",
"license": "apache-2.0",
"size": 13031
} | [
"org.dbflute.dbmeta.DBMeta",
"org.dbflute.exception.DBMetaNotFoundException"
] | import org.dbflute.dbmeta.DBMeta; import org.dbflute.exception.DBMetaNotFoundException; | import org.dbflute.dbmeta.*; import org.dbflute.exception.*; | [
"org.dbflute.dbmeta",
"org.dbflute.exception"
] | org.dbflute.dbmeta; org.dbflute.exception; | 2,350,189 |
protected void addError(BaseServiceResponse response, String key,
Object[] inserts)
{
Precondition.assertNotNull("response", response);
response.addError(key, inserts);
}
| void function(BaseServiceResponse response, String key, Object[] inserts) { Precondition.assertNotNull(STR, response); response.addError(key, inserts); } | /**
* Adds an error message with a given key to a given response
* @param response The response to add the message to.
* @param key The key of the message.
* @param inserts The inserts of the message.
*/ | Adds an error message with a given key to a given response | addError | {
"repo_name": "VHAINNOVATIONS/AVS",
"path": "ll-foundation/src/main/java/gov/va/med/lom/foundation/service/AbstractBaseService.java",
"license": "apache-2.0",
"size": 13148
} | [
"gov.va.med.lom.foundation.service.response.BaseServiceResponse",
"gov.va.med.lom.foundation.util.Precondition"
] | import gov.va.med.lom.foundation.service.response.BaseServiceResponse; import gov.va.med.lom.foundation.util.Precondition; | import gov.va.med.lom.foundation.service.response.*; import gov.va.med.lom.foundation.util.*; | [
"gov.va.med"
] | gov.va.med; | 2,178,422 |
@Override
public void remove(Declarator element) {
throw new ChameleonProgrammerException("Trying to remove an element from a lazy class body.");
}
private boolean _initializedElements = false; | void function(Declarator element) { throw new ChameleonProgrammerException(STR); } private boolean _initializedElements = false; | /**
* Trying to remove something from a lazy class body will result in an exception.
*
* @throws ChameleonProgrammerException Always
*/ | Trying to remove something from a lazy class body will result in an exception | remove | {
"repo_name": "markovandooren/chameleon",
"path": "src/org/aikodi/chameleon/oo/type/LazyClassBody.java",
"license": "mit",
"size": 9032
} | [
"org.aikodi.chameleon.core.declaration.Declarator",
"org.aikodi.chameleon.exception.ChameleonProgrammerException"
] | import org.aikodi.chameleon.core.declaration.Declarator; import org.aikodi.chameleon.exception.ChameleonProgrammerException; | import org.aikodi.chameleon.core.declaration.*; import org.aikodi.chameleon.exception.*; | [
"org.aikodi.chameleon"
] | org.aikodi.chameleon; | 2,445,770 |
@Override
public String getText(Object object) {
String label = ((Metadata)object).getKey();
return label == null || label.length() == 0 ?
getString("_UI_Metadata_type") :
getString("_UI_Metadata_type") + " " + label;
}
| String function(Object object) { String label = ((Metadata)object).getKey(); return label == null label.length() == 0 ? getString(STR) : getString(STR) + " " + label; } | /**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This returns the label text for the adapted class. | getText | {
"repo_name": "lbroudoux/eip-designer",
"path": "plugins/com.github.lbroudoux.dsl.eip.edit/src/com/github/lbroudoux/dsl/eip/provider/MetadataItemProvider.java",
"license": "apache-2.0",
"size": 5947
} | [
"com.github.lbroudoux.dsl.eip.Metadata"
] | import com.github.lbroudoux.dsl.eip.Metadata; | import com.github.lbroudoux.dsl.eip.*; | [
"com.github.lbroudoux"
] | com.github.lbroudoux; | 2,638,409 |
public void setZoom(double zoomNew) {
if (!isZoomable() || (zoomNew <= 0.0) ||
!MathUtils.isCalculatable(zoomNew)) {
return;
}
double zoomOld = getZoom();
zoomNew = MathUtils.limit(zoomNew, getZoomMin(), getZoomMax());
if (zoomOld == zoomNew) {
return;
}
for (String axisName : getAxes()) {
NavigationInfo info = getInfo(axisName);
if (info == null) {
continue;
}
info.setZoom(zoomNew);
}
NavigationEvent<Double> event =
new NavigationEvent<Double>(this, zoomOld, zoomNew);
fireZoomChanged(event);
refresh();
} | void function(double zoomNew) { if (!isZoomable() (zoomNew <= 0.0) !MathUtils.isCalculatable(zoomNew)) { return; } double zoomOld = getZoom(); zoomNew = MathUtils.limit(zoomNew, getZoomMin(), getZoomMax()); if (zoomOld == zoomNew) { return; } for (String axisName : getAxes()) { NavigationInfo info = getInfo(axisName); if (info == null) { continue; } info.setZoom(zoomNew); } NavigationEvent<Double> event = new NavigationEvent<Double>(this, zoomOld, zoomNew); fireZoomChanged(event); refresh(); } | /**
* Sets the zoom level of the associated object to the specified value.
* @param zoomNew New zoom level.
*/ | Sets the zoom level of the associated object to the specified value | setZoom | {
"repo_name": "charles-cooper/idylfin",
"path": "src/de/erichseifert/gral/plots/PlotNavigator.java",
"license": "apache-2.0",
"size": 13880
} | [
"de.erichseifert.gral.navigation.NavigationEvent",
"de.erichseifert.gral.util.MathUtils"
] | import de.erichseifert.gral.navigation.NavigationEvent; import de.erichseifert.gral.util.MathUtils; | import de.erichseifert.gral.navigation.*; import de.erichseifert.gral.util.*; | [
"de.erichseifert.gral"
] | de.erichseifert.gral; | 2,412,079 |
Job performBackup(long delay, long interval, boolean block, int generations);
| Job performBackup(long delay, long interval, boolean block, int generations); | /**
* Creates a back-up of the database if a back-up is due or is forced
*
* @param delay
* - delay in msec before back-up job is started
* @param interval
* - interval between backups in msec, -1 to force immediate backup
* @param block
* - true if method should wait for job finishing
* @param generations
* - true maximum number of backup generations to keep
* @return - scheduled backup job
*/ | Creates a back-up of the database if a back-up is due or is forced | performBackup | {
"repo_name": "bdaum/zoraPD",
"path": "com.bdaum.zoom.core/src/com/bdaum/zoom/core/db/IDbManager.java",
"license": "gpl-2.0",
"size": 21435
} | [
"org.eclipse.core.runtime.jobs.Job"
] | import org.eclipse.core.runtime.jobs.Job; | import org.eclipse.core.runtime.jobs.*; | [
"org.eclipse.core"
] | org.eclipse.core; | 425,812 |
public IntegrityCheckResult findResultForIntegrityCheckById(IntegrityCheck integrityCheck,int id); | IntegrityCheckResult function(IntegrityCheck integrityCheck,int id); | /**
* Get the integrity check result associate with integrity check and the result id
* @param integrityCheck integrity check of the result
* @param id result id
* @return will return integrity check associated with given integrity check and result id
* @throws DAOException
*/ | Get the integrity check result associate with integrity check and the result id | findResultForIntegrityCheckById | {
"repo_name": "openmrs/openmrs-module-dataintegrityworkflow",
"path": "api/src/main/java/org/openmrs/module/dataintegrityworkflow/DataIntegrityWorkflowService.java",
"license": "mpl-2.0",
"size": 13605
} | [
"org.openmrs.module.dataintegrity.IntegrityCheck",
"org.openmrs.module.dataintegrity.IntegrityCheckResult"
] | import org.openmrs.module.dataintegrity.IntegrityCheck; import org.openmrs.module.dataintegrity.IntegrityCheckResult; | import org.openmrs.module.dataintegrity.*; | [
"org.openmrs.module"
] | org.openmrs.module; | 1,785,304 |
EReference getPrecedence_PostOR(); | EReference getPrecedence_PostOR(); | /**
* Returns the meta object for the containment reference '{@link lqn.Precedence#getPostOR <em>Post OR</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Post OR</em>'.
* @see lqn.Precedence#getPostOR()
* @see #getPrecedence()
* @generated
*/ | Returns the meta object for the containment reference '<code>lqn.Precedence#getPostOR Post OR</code>'. | getPrecedence_PostOR | {
"repo_name": "aciancone/klapersuite",
"path": "klapersuite.metamodel.lqn/src/lqn/LqnPackage.java",
"license": "epl-1.0",
"size": 116938
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,131,698 |
public BigInteger getN() {
return n;
}
private final BigInteger g; | BigInteger function() { return n; } private final BigInteger g; | /**
* Getter for a modulus of an instance of the Paillier encryption. It is
* composite number and is equal to <math>p*q</math>, where p, q are secret
* informations.
*
* @return n A modulus of this encryption.
*/ | Getter for a modulus of an instance of the Paillier encryption. It is composite number and is equal to p*q, where p, q are secret informations | getN | {
"repo_name": "tell/cryptojava",
"path": "src/main/java/com/github/tell/cryptography/paillier/key/PaillierPublicKey.java",
"license": "mit",
"size": 4602
} | [
"java.math.BigInteger"
] | import java.math.BigInteger; | import java.math.*; | [
"java.math"
] | java.math; | 2,242,507 |
@Test()
public void testMalformedNameForm()
throws Exception
{
final Entry schemaEntry = minimalSchemaEntry.duplicate();
schemaEntry.addAttribute(Schema.ATTR_NAME_FORM, "malformed");
final File schemaFile = createTempFile(schemaEntry.toLDIF());
final SchemaValidator schemaValidator = new SchemaValidator();
final List<String> errorMessages = new ArrayList<>(5);
final Schema schema =
schemaValidator.validateSchema(schemaFile, null, errorMessages);
assertNotNull(schema);
assertNotNull(schema.getAttributeType("dc"));
assertFalse(errorMessages.isEmpty());
} | @Test() void function() throws Exception { final Entry schemaEntry = minimalSchemaEntry.duplicate(); schemaEntry.addAttribute(Schema.ATTR_NAME_FORM, STR); final File schemaFile = createTempFile(schemaEntry.toLDIF()); final SchemaValidator schemaValidator = new SchemaValidator(); final List<String> errorMessages = new ArrayList<>(5); final Schema schema = schemaValidator.validateSchema(schemaFile, null, errorMessages); assertNotNull(schema); assertNotNull(schema.getAttributeType("dc")); assertFalse(errorMessages.isEmpty()); } | /**
* Tests the behavior for a schema entry that a malformed name form
* definition.
*
* @throws Exception If an unexpected problem occurs.
*/ | Tests the behavior for a schema entry that a malformed name form definition | testMalformedNameForm | {
"repo_name": "UnboundID/ldapsdk",
"path": "tests/unit/src/com/unboundid/ldap/sdk/schema/SchemaValidatorTestCase.java",
"license": "gpl-2.0",
"size": 262381
} | [
"com.unboundid.ldap.sdk.Entry",
"java.io.File",
"java.util.ArrayList",
"java.util.List",
"org.testng.annotations.Test"
] | import com.unboundid.ldap.sdk.Entry; import java.io.File; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; | import com.unboundid.ldap.sdk.*; import java.io.*; import java.util.*; import org.testng.annotations.*; | [
"com.unboundid.ldap",
"java.io",
"java.util",
"org.testng.annotations"
] | com.unboundid.ldap; java.io; java.util; org.testng.annotations; | 932,330 |
public static String listToString(ArrayList<String> colList, String cmd) {
if ( colList==null ) return " * ";
if (colList.indexOf("los") >= 0 ) // los is null is the current version
colList.remove("los");
String str = new String("");
for (int i=0; i<colList.size(); i++) {
if ( i>0 ) str += ", ";
if (cmd == null )
str += colList.get(i);
else
str += ( cmd + "(" + colList.get(i) + ")" );
}
return str;
}
| static String function(ArrayList<String> colList, String cmd) { if ( colList==null ) return STR; if (colList.indexOf("los") >= 0 ) colList.remove("los"); String str = new String(STR, STR(STR)" ); } return str; } | /**
* Convert list to a command usable in a select query for report
* @param colList
* @return String
*/ | Convert list to a command usable in a select query for report | listToString | {
"repo_name": "relteq/beats",
"path": "src/main/java/edu/berkeley/path/beats/processor/AggregateData.java",
"license": "bsd-2-clause",
"size": 23574
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 723,162 |
public void onEvent(DownloadEvent event) {
setVisibilityForDownloadProgressView(true);
} | void function(DownloadEvent event) { setVisibilityForDownloadProgressView(true); } | /**
* callback for EventBus
* https://github.com/greenrobot/EventBus
*/ | callback for EventBus HREF | onEvent | {
"repo_name": "Rawneed/edx-app-android",
"path": "VideoLocker/src/main/java/org/edx/mobile/view/CourseBaseActivity.java",
"license": "apache-2.0",
"size": 12168
} | [
"org.edx.mobile.event.DownloadEvent"
] | import org.edx.mobile.event.DownloadEvent; | import org.edx.mobile.event.*; | [
"org.edx.mobile"
] | org.edx.mobile; | 2,426,154 |
public int getMeasureAsInt()
{
ByteBuffer buffer = ByteBuffer.wrap(measure);
return buffer.getInt();
} | int function() { ByteBuffer buffer = ByteBuffer.wrap(measure); return buffer.getInt(); } | /**
* Returns the measure value as an integer.
*
* @return
*/ | Returns the measure value as an integer | getMeasureAsInt | {
"repo_name": "Gr33nOpo55um/EnOcean",
"path": "src/it/polito/elite/enocean/enj/eep/eep26/D2/D201/D201ActuatorMeasurementResponse.java",
"license": "apache-2.0",
"size": 2710
} | [
"java.nio.ByteBuffer"
] | import java.nio.ByteBuffer; | import java.nio.*; | [
"java.nio"
] | java.nio; | 883,944 |
protected boolean hasDuplicateEntry(List<String> docNumbers){
boolean isDuplicate = false;
WorkflowDocument workflowDocument = null;
for (String docNumber : docNumbers) {
try{
workflowDocument = workflowDocumentService.loadWorkflowDocument(docNumber, GlobalVariables.getUserSession().getPerson());
}catch(WorkflowException we){
throw new RuntimeException(we);
}
//if the doc number exists, and is in final status, consider this a dupe and return
if(workflowDocument.isFinal()){
isDuplicate = true;
break;
}
}
return isDuplicate;
}
| boolean function(List<String> docNumbers){ boolean isDuplicate = false; WorkflowDocument workflowDocument = null; for (String docNumber : docNumbers) { try{ workflowDocument = workflowDocumentService.loadWorkflowDocument(docNumber, GlobalVariables.getUserSession().getPerson()); }catch(WorkflowException we){ throw new RuntimeException(we); } if(workflowDocument.isFinal()){ isDuplicate = true; break; } } return isDuplicate; } | /**
* Looks at a list of doc numbers, but only considers an entry duplicate
* if the document is in a Final status.
*
* @param docNumbers
* @return
*/ | Looks at a list of doc numbers, but only considers an entry duplicate if the document is in a Final status | hasDuplicateEntry | {
"repo_name": "Ariah-Group/Finance",
"path": "af_webapp/src/main/java/org/kuali/kfs/module/purap/document/service/impl/ReceivingServiceImpl.java",
"license": "apache-2.0",
"size": 45711
} | [
"java.util.List",
"org.kuali.rice.kew.api.WorkflowDocument",
"org.kuali.rice.kew.api.exception.WorkflowException",
"org.kuali.rice.krad.util.GlobalVariables"
] | import java.util.List; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.krad.util.GlobalVariables; | import java.util.*; import org.kuali.rice.kew.api.*; import org.kuali.rice.kew.api.exception.*; import org.kuali.rice.krad.util.*; | [
"java.util",
"org.kuali.rice"
] | java.util; org.kuali.rice; | 2,610,545 |
@Test
public void forbidsUselessParentheses()
throws Exception {
final String file = "UselessParentheses.java";
new PMDAssert(
file, Matchers.is(false),
Matchers.containsString("Useless parentheses")
).validate();
} | void function() throws Exception { final String file = STR; new PMDAssert( file, Matchers.is(false), Matchers.containsString(STR) ).validate(); } | /**
* PMDValidator forbid useless parentheses.
* @throws Exception If something wrong happens inside.
*/ | PMDValidator forbid useless parentheses | forbidsUselessParentheses | {
"repo_name": "vkuchyn/qulice",
"path": "qulice-pmd/src/test/java/com/qulice/pmd/PMDValidatorTest.java",
"license": "bsd-3-clause",
"size": 19126
} | [
"org.hamcrest.Matchers"
] | import org.hamcrest.Matchers; | import org.hamcrest.*; | [
"org.hamcrest"
] | org.hamcrest; | 474,561 |
public Builder requiresConfigurationFragmentsBySkylarkModuleName(
Collection<String> configurationFragmentNames) {
configurationFragmentPolicy
.requiresConfigurationFragmentsBySkylarkModuleName(configurationFragmentNames);
return this;
} | Builder function( Collection<String> configurationFragmentNames) { configurationFragmentPolicy .requiresConfigurationFragmentsBySkylarkModuleName(configurationFragmentNames); return this; } | /**
* Declares the configuration fragments that are required by this rule for the target
* configuration.
*
* <p>In contrast to {@link #requiresConfigurationFragments(Class...)}, this method takes the
* Skylark module names of fragments instead of their classes.
*/ | Declares the configuration fragments that are required by this rule for the target configuration. In contrast to <code>#requiresConfigurationFragments(Class...)</code>, this method takes the Skylark module names of fragments instead of their classes | requiresConfigurationFragmentsBySkylarkModuleName | {
"repo_name": "kchodorow/bazel-1",
"path": "src/main/java/com/google/devtools/build/lib/packages/RuleClass.java",
"license": "apache-2.0",
"size": 76983
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 207,504 |
IIdType doUpdateResource(IBaseResource theResource); | IIdType doUpdateResource(IBaseResource theResource); | /**
* Users of this API must implement this method
*/ | Users of this API must implement this method | doUpdateResource | {
"repo_name": "aemay2/hapi-fhir",
"path": "hapi-fhir-test-utilities/src/main/java/ca/uhn/fhir/test/utilities/ITestDataBuilder.java",
"license": "apache-2.0",
"size": 9371
} | [
"org.hl7.fhir.instance.model.api.IBaseResource",
"org.hl7.fhir.instance.model.api.IIdType"
] | import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; | import org.hl7.fhir.instance.model.api.*; | [
"org.hl7.fhir"
] | org.hl7.fhir; | 285,007 |
private void initList() {
lstScenarios.setCellRenderer(new DefaultListCellRenderer() { | void function() { lstScenarios.setCellRenderer(new DefaultListCellRenderer() { | /**
* DOCUMENT ME!
*/ | DOCUMENT ME | initList | {
"repo_name": "cismet/cids-custom-sudplan",
"path": "src/main/java/de/cismet/cids/custom/sudplan/hydrology/DoSimulationVisualPanelSelectScenario.java",
"license": "lgpl-3.0",
"size": 12475
} | [
"javax.swing.DefaultListCellRenderer"
] | import javax.swing.DefaultListCellRenderer; | import javax.swing.*; | [
"javax.swing"
] | javax.swing; | 2,238,472 |
IBasicExpression createMergeExpression (String name, String namespace, Collection expressionsToMerge)
throws BadQueryException; | IBasicExpression createMergeExpression (String name, String namespace, Collection expressionsToMerge) throws BadQueryException; | /**
* Creates a MergeExpression for the given element (AND, OR). The given children
* are the expressions to merge.
*
* @param name the name of the Element describing the merge expression.
* @param namespace the namespace of the Element describing the merge expression.
* @param expressionsToMerge the expressions to merge.
*
* @return an IBasicExpression
*
* @throws BadQueryException
*/ | Creates a MergeExpression for the given element (AND, OR). The given children are the expressions to merge | createMergeExpression | {
"repo_name": "integrated/jakarta-slide-server",
"path": "maven/jakarta-slide-kernel/src/main/java/org/apache/slide/search/basic/IBasicExpressionFactory.java",
"license": "apache-2.0",
"size": 3349
} | [
"java.util.Collection",
"org.apache.slide.search.BadQueryException"
] | import java.util.Collection; import org.apache.slide.search.BadQueryException; | import java.util.*; import org.apache.slide.search.*; | [
"java.util",
"org.apache.slide"
] | java.util; org.apache.slide; | 138,382 |
//#ifdef JAVA6
public void setSQLXML(int parameterIndex,
SQLXML xmlObject) throws SQLException {
throw Util.notSupported();
}
//#endif JAVA6
// --------------------------- Added: Mustang Build 86 ------------------------- | void function(int parameterIndex, SQLXML xmlObject) throws SQLException { throw Util.notSupported(); } | /**
* Sets the designated parameter to the given <code>java.sql.SQLXML</code> object.
* The driver converts this to an
* SQL <code>XML</code> value when it sends it to the database.
* <p>
*
* @param parameterIndex index of the first parameter is 1, the second is 2, ...
* @param xmlObject a <code>SQLXML</code> object that maps an SQL <code>XML</code> value
* @throws SQLException if a database access error occurs,
* this method is called on a closed <code>PreparedStatement</code>
* or the <code>java.xml.transform.Result</code>,
* <code>Writer</code> or <code>OutputStream</code> has not been closed for
* the <code>SQLXML</code> object
* @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method
*
* @since JDK 1.6, HSQLDB 1.9.0
*/ | Sets the designated parameter to the given <code>java.sql.SQLXML</code> object. The driver converts this to an SQL <code>XML</code> value when it sends it to the database. | setSQLXML | {
"repo_name": "ifcharming/original2.0",
"path": "src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCPreparedStatement.java",
"license": "gpl-3.0",
"size": 175518
} | [
"java.sql.SQLException"
] | import java.sql.SQLException; | import java.sql.*; | [
"java.sql"
] | java.sql; | 1,961,755 |
@RequestMapping(value = "/timeSlotTypes",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TimeSlotType> update(@Valid @RequestBody TimeSlotType timeSlotType) throws URISyntaxException {
log.debug("REST request to update TimeSlotType : {}", timeSlotType);
if (timeSlotType.getId() == null) {
return create(timeSlotType);
}
TimeSlotType result;
try {
result = doSave(timeSlotType);
} catch (BadRequestException e) {
return ResponseEntity.badRequest().header("Failure", e.getMessage()).body(null);
}
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("timeSlotType", timeSlotType.getId().toString()))
.body(result);
}
| @RequestMapping(value = STR, method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<TimeSlotType> function(@Valid @RequestBody TimeSlotType timeSlotType) throws URISyntaxException { log.debug(STR, timeSlotType); if (timeSlotType.getId() == null) { return create(timeSlotType); } TimeSlotType result; try { result = doSave(timeSlotType); } catch (BadRequestException e) { return ResponseEntity.badRequest().header(STR, e.getMessage()).body(null); } return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(STR, timeSlotType.getId().toString())) .body(result); } | /**
* PUT /timeSlotTypes -> Updates an existing timeSlotType.
*/ | PUT /timeSlotTypes -> Updates an existing timeSlotType | update | {
"repo_name": "lgangloff/crossfit-2.0",
"path": "src/main/java/org/crossfit/app/web/rest/api/TimeSlotTypeResource.java",
"license": "mit",
"size": 6018
} | [
"java.net.URISyntaxException",
"javax.validation.Valid",
"org.crossfit.app.domain.TimeSlotType",
"org.crossfit.app.web.exception.BadRequestException",
"org.crossfit.app.web.rest.util.HeaderUtil",
"org.springframework.http.MediaType",
"org.springframework.http.ResponseEntity",
"org.springframework.web.bind.annotation.RequestBody",
"org.springframework.web.bind.annotation.RequestMapping",
"org.springframework.web.bind.annotation.RequestMethod"
] | import java.net.URISyntaxException; import javax.validation.Valid; import org.crossfit.app.domain.TimeSlotType; import org.crossfit.app.web.exception.BadRequestException; import org.crossfit.app.web.rest.util.HeaderUtil; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; | import java.net.*; import javax.validation.*; import org.crossfit.app.domain.*; import org.crossfit.app.web.exception.*; import org.crossfit.app.web.rest.util.*; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; | [
"java.net",
"javax.validation",
"org.crossfit.app",
"org.springframework.http",
"org.springframework.web"
] | java.net; javax.validation; org.crossfit.app; org.springframework.http; org.springframework.web; | 1,850,778 |
public Date getCreated() {
return _created;
}
| Date function() { return _created; } | /**
* Returns the entry created date (Atom 0.3 only)
* <p>
* @return the entry created date, <b>null</b> if none.
*/ | Returns the entry created date (Atom 0.3 only) | getCreated | {
"repo_name": "OpenNTF/collaborationtoday",
"path": "DOTSFeedMonster/org.openntf.rome/org.openntf.rome/src/com/sun/syndication/feed/atom/Entry.java",
"license": "apache-2.0",
"size": 14309
} | [
"java.util.Date"
] | import java.util.Date; | import java.util.*; | [
"java.util"
] | java.util; | 65,503 |
public PageBlobClearPagesHeaders setDateProperty(OffsetDateTime dateProperty) {
if (dateProperty == null) {
this.dateProperty = null;
} else {
this.dateProperty = new DateTimeRfc1123(dateProperty);
}
return this;
} | PageBlobClearPagesHeaders function(OffsetDateTime dateProperty) { if (dateProperty == null) { this.dateProperty = null; } else { this.dateProperty = new DateTimeRfc1123(dateProperty); } return this; } | /**
* Set the dateProperty property: UTC date/time value generated by the
* service that indicates the time at which the response was initiated.
*
* @param dateProperty the dateProperty value to set.
* @return the PageBlobClearPagesHeaders object itself.
*/ | Set the dateProperty property: UTC date/time value generated by the service that indicates the time at which the response was initiated | setDateProperty | {
"repo_name": "navalev/azure-sdk-for-java",
"path": "sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/implementation/models/PageBlobClearPagesHeaders.java",
"license": "mit",
"size": 13736
} | [
"com.azure.core.util.DateTimeRfc1123",
"java.time.OffsetDateTime"
] | import com.azure.core.util.DateTimeRfc1123; import java.time.OffsetDateTime; | import com.azure.core.util.*; import java.time.*; | [
"com.azure.core",
"java.time"
] | com.azure.core; java.time; | 826,605 |
static boolean restoreBackupIncremental(Database database,
String dataFileName, String backupFileName) {
try {
FileAccess fileAccess = database.logger.getFileAccess();
if (fileAccess.isStreamElement(backupFileName)) {
RAShadowFile.restoreFile(database, backupFileName,
dataFileName);
deleteFile(database, backupFileName);
return true;
}
return false;
} catch (Throwable e) {
database.logger.logSevereEvent(
"DataFileCache.restoreBackupIncremental", e);
throw Error.error(ErrorCode.FILE_IO_ERROR, e);
}
} | static boolean restoreBackupIncremental(Database database, String dataFileName, String backupFileName) { try { FileAccess fileAccess = database.logger.getFileAccess(); if (fileAccess.isStreamElement(backupFileName)) { RAShadowFile.restoreFile(database, backupFileName, dataFileName); deleteFile(database, backupFileName); return true; } return false; } catch (Throwable e) { database.logger.logSevereEvent( STR, e); throw Error.error(ErrorCode.FILE_IO_ERROR, e); } } | /**
* Restores in from an incremental backup
*/ | Restores in from an incremental backup | restoreBackupIncremental | {
"repo_name": "Julien35/dev-courses",
"path": "tutoriel-spring-mvc/lib/hsqldb/src/org/hsqldb/persist/DataFileCache.java",
"license": "mit",
"size": 47274
} | [
"org.hsqldb.Database",
"org.hsqldb.error.Error",
"org.hsqldb.error.ErrorCode",
"org.hsqldb.lib.FileAccess"
] | import org.hsqldb.Database; import org.hsqldb.error.Error; import org.hsqldb.error.ErrorCode; import org.hsqldb.lib.FileAccess; | import org.hsqldb.*; import org.hsqldb.error.*; import org.hsqldb.lib.*; | [
"org.hsqldb",
"org.hsqldb.error",
"org.hsqldb.lib"
] | org.hsqldb; org.hsqldb.error; org.hsqldb.lib; | 770,080 |
public void testSingleValueWithOffsetMinDocCount() throws Exception {
prepareIndex(date("2014-03-11T00:00:00+00:00"), 12, 1, 0);
prepareIndex(date("2014-03-14T00:00:00+00:00"), 12, 1, 13);
SearchResponse response = client().prepareSearch("idx2")
.setQuery(matchAllQuery())
.addAggregation(dateHistogram("date_histo")
.field("date")
.offset("6h")
.minDocCount(0)
.format(DATE_FORMAT)
.dateHistogramInterval(DateHistogramInterval.DAY))
.execute().actionGet();
assertThat(response.getHits().getTotalHits(), equalTo(24L));
Histogram histo = response.getAggregations().get("date_histo");
List<? extends Histogram.Bucket> buckets = histo.getBuckets();
assertThat(buckets.size(), equalTo(5));
checkBucketFor(buckets.get(0), new DateTime(2014, 3, 10, 6, 0, DateTimeZone.UTC), 6L);
checkBucketFor(buckets.get(1), new DateTime(2014, 3, 11, 6, 0, DateTimeZone.UTC), 6L);
checkBucketFor(buckets.get(2), new DateTime(2014, 3, 12, 6, 0, DateTimeZone.UTC), 0L);
checkBucketFor(buckets.get(3), new DateTime(2014, 3, 13, 6, 0, DateTimeZone.UTC), 6L);
checkBucketFor(buckets.get(4), new DateTime(2014, 3, 14, 6, 0, DateTimeZone.UTC), 6L);
} | void function() throws Exception { prepareIndex(date(STR), 12, 1, 0); prepareIndex(date(STR), 12, 1, 13); SearchResponse response = client().prepareSearch("idx2") .setQuery(matchAllQuery()) .addAggregation(dateHistogram(STR) .field("date") .offset("6h") .minDocCount(0) .format(DATE_FORMAT) .dateHistogramInterval(DateHistogramInterval.DAY)) .execute().actionGet(); assertThat(response.getHits().getTotalHits(), equalTo(24L)); Histogram histo = response.getAggregations().get(STR); List<? extends Histogram.Bucket> buckets = histo.getBuckets(); assertThat(buckets.size(), equalTo(5)); checkBucketFor(buckets.get(0), new DateTime(2014, 3, 10, 6, 0, DateTimeZone.UTC), 6L); checkBucketFor(buckets.get(1), new DateTime(2014, 3, 11, 6, 0, DateTimeZone.UTC), 6L); checkBucketFor(buckets.get(2), new DateTime(2014, 3, 12, 6, 0, DateTimeZone.UTC), 0L); checkBucketFor(buckets.get(3), new DateTime(2014, 3, 13, 6, 0, DateTimeZone.UTC), 6L); checkBucketFor(buckets.get(4), new DateTime(2014, 3, 14, 6, 0, DateTimeZone.UTC), 6L); } | /**
* Set offset so day buckets start at 6am. Index first 12 hours for two days, with one day gap.
*/ | Set offset so day buckets start at 6am. Index first 12 hours for two days, with one day gap | testSingleValueWithOffsetMinDocCount | {
"repo_name": "strahanjen/strahanjen.github.io",
"path": "elasticsearch-master/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DateHistogramOffsetIT.java",
"license": "bsd-3-clause",
"size": 7784
} | [
"java.util.List",
"org.elasticsearch.action.search.SearchResponse",
"org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval",
"org.elasticsearch.search.aggregations.bucket.histogram.Histogram",
"org.hamcrest.Matchers",
"org.joda.time.DateTime",
"org.joda.time.DateTimeZone"
] | import java.util.List; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.hamcrest.Matchers; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; | import java.util.*; import org.elasticsearch.action.search.*; import org.elasticsearch.search.aggregations.bucket.histogram.*; import org.hamcrest.*; import org.joda.time.*; | [
"java.util",
"org.elasticsearch.action",
"org.elasticsearch.search",
"org.hamcrest",
"org.joda.time"
] | java.util; org.elasticsearch.action; org.elasticsearch.search; org.hamcrest; org.joda.time; | 2,286,496 |
public Set<String> getGraphLabels() {
return graphMetaData.keySet();
} | Set<String> function() { return graphMetaData.keySet(); } | /**
* Returns the graph labels available in the meta data.
*
* @return graph labels
*/ | Returns the graph labels available in the meta data | getGraphLabels | {
"repo_name": "galpha/gradoop",
"path": "gradoop-common/src/main/java/org/gradoop/common/model/impl/metadata/MetaData.java",
"license": "apache-2.0",
"size": 7905
} | [
"java.util.Set"
] | import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 1,977,403 |
private Map<StatementPattern, Map<StatementSource, List<String>>> addAllCombinations(
Map<StatementPattern, Map<StatementSource, List<String>>> newStmtToLstAuthorities, List<String> allNewURIs)
{
Map<StatementPattern, Map<StatementSource, List<String>>> hm = new HashMap<StatementPattern, Map<StatementSource, List<String>>>();
TrieNode tn = Trie.constructTrie(allNewURIs, 100);
for(StatementPattern stmt:newStmtToLstAuthorities.keySet())
{
Map<StatementSource, List<String>> newStmtSourceToLstAuthorities = new HashMap<StatementSource, List<String>>();
Map<StatementSource, List<String>> stmtSourceToLstAuthorities = newStmtToLstAuthorities.get(stmt);
for(StatementSource src:stmtSourceToLstAuthorities.keySet())
{
List<String> srcURISet = stmtSourceToLstAuthorities.get(src);
List<String> newSrcURISet = new ArrayList<String> ();
for(String uri:srcURISet)
{
newSrcURISet = getUnion(newSrcURISet, Trie.getAllCombinations(uri, tn));
}
newStmtSourceToLstAuthorities.put(src, newSrcURISet);
}
hm.put(stmt, newStmtSourceToLstAuthorities);
}
return hm;
}
| Map<StatementPattern, Map<StatementSource, List<String>>> function( Map<StatementPattern, Map<StatementSource, List<String>>> newStmtToLstAuthorities, List<String> allNewURIs) { Map<StatementPattern, Map<StatementSource, List<String>>> hm = new HashMap<StatementPattern, Map<StatementSource, List<String>>>(); TrieNode tn = Trie.constructTrie(allNewURIs, 100); for(StatementPattern stmt:newStmtToLstAuthorities.keySet()) { Map<StatementSource, List<String>> newStmtSourceToLstAuthorities = new HashMap<StatementSource, List<String>>(); Map<StatementSource, List<String>> stmtSourceToLstAuthorities = newStmtToLstAuthorities.get(stmt); for(StatementSource src:stmtSourceToLstAuthorities.keySet()) { List<String> srcURISet = stmtSourceToLstAuthorities.get(src); List<String> newSrcURISet = new ArrayList<String> (); for(String uri:srcURISet) { newSrcURISet = getUnion(newSrcURISet, Trie.getAllCombinations(uri, tn)); } newStmtSourceToLstAuthorities.put(src, newSrcURISet); } hm.put(stmt, newStmtSourceToLstAuthorities); } return hm; } | /**
* Add all possible combinations to sub-prefixes. Sub-prefixes are like most common automata's
* @param newStmtToLstAuthorities Statement Patter to list of authorities map
* @param allNewURIs Set of prefixes which needs to be checked for adding all possibilities
* @return Hash map of statement pattern to sources after adding combinations
*/ | Add all possible combinations to sub-prefixes. Sub-prefixes are like most common automata's | addAllCombinations | {
"repo_name": "apotocki/fex",
"path": "src/main/java/org/aksw/simba/quetsal/core/TBSSSourceSelection.java",
"license": "agpl-3.0",
"size": 49133
} | [
"com.fluidops.fedx.algebra.StatementSource",
"java.util.ArrayList",
"java.util.HashMap",
"java.util.List",
"java.util.Map",
"org.aksw.simba.quetsal.datastructues.Trie",
"org.aksw.simba.quetsal.datastructues.TrieNode",
"org.openrdf.query.algebra.StatementPattern"
] | import com.fluidops.fedx.algebra.StatementSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.aksw.simba.quetsal.datastructues.Trie; import org.aksw.simba.quetsal.datastructues.TrieNode; import org.openrdf.query.algebra.StatementPattern; | import com.fluidops.fedx.algebra.*; import java.util.*; import org.aksw.simba.quetsal.datastructues.*; import org.openrdf.query.algebra.*; | [
"com.fluidops.fedx",
"java.util",
"org.aksw.simba",
"org.openrdf.query"
] | com.fluidops.fedx; java.util; org.aksw.simba; org.openrdf.query; | 1,079,727 |
public static List<Phrase> toPhrases(Tree node, SemanticGraph graph, String text) {
ArrayList<Phrase> phrases = new ArrayList<Phrase>();
for (Tree child : node.children())
if (child.isPrePreTerminal() || child.isPreTerminal())
phrases.add(toPhrase(child, graph, text));
else if (child.isPhrasal())
for (Phrase p : toPhrases(child, graph, text))
phrases.add(p);
return phrases;
} | static List<Phrase> function(Tree node, SemanticGraph graph, String text) { ArrayList<Phrase> phrases = new ArrayList<Phrase>(); for (Tree child : node.children()) if (child.isPrePreTerminal() child.isPreTerminal()) phrases.add(toPhrase(child, graph, text)); else if (child.isPhrasal()) for (Phrase p : toPhrases(child, graph, text)) phrases.add(p); return phrases; } | /**
* Transform a parse tree node into a list of Phrase instances
*
* @param node
* @param graph
* @param text
* @return
*/ | Transform a parse tree node into a list of Phrase instances | toPhrases | {
"repo_name": "hakchul77/irnlp_toolkit",
"path": "src/main/java/kr/jihee/irnlp_toolkit/nlp/StanfordNlpWrapper.java",
"license": "gpl-2.0",
"size": 18360
} | [
"edu.stanford.nlp.semgraph.SemanticGraph",
"edu.stanford.nlp.trees.Tree",
"java.util.ArrayList",
"java.util.List"
] | import edu.stanford.nlp.semgraph.SemanticGraph; import edu.stanford.nlp.trees.Tree; import java.util.ArrayList; import java.util.List; | import edu.stanford.nlp.semgraph.*; import edu.stanford.nlp.trees.*; import java.util.*; | [
"edu.stanford.nlp",
"java.util"
] | edu.stanford.nlp; java.util; | 2,584,183 |
if ((args.length == 1) && (args[0].equalsIgnoreCase("kick"))) {
UUID id = SGApi.getPartyManager().getPlayers().get(sender.getName());
if (id != null) {
Party party = SGApi.getPartyManager().getParties().get(id);
if (party.getLeader().equalsIgnoreCase(sender.getName())) {
for (String members : party.getMembers()) {
if ((members != null) && (members.equalsIgnoreCase(args[0]))) {
party.removeMember(args[0]);
SGApi.getPartyManager().getPlayers().remove(args[0]);
sender.sendMessage(org.bukkit.ChatColor.YELLOW + args[0] + I18N.getLocaleString("KICKED_FROM_PARTY"));
Player p = Bukkit.getServer().getPlayer(args[0]);
if (p != null) {
p.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString("KICKED_FROM_PARTY_2"));
}
if (party.hasNoMembers()) {
PartyManager.endParty(sender.getName(), id);
}
for (String member : party.getMembers()) {
if (member != null) {
Player play = Bukkit.getServer().getPlayer(member);
if (play != null) {
play.sendMessage(org.bukkit.ChatColor.YELLOW + args[0] + I18N.getLocaleString("KICKED_FROM_PARTY"));
}
}
}
return;
}
}
sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString("PLAYER") + args[0] + I18N.getLocaleString("NOT_IN_YOUR_PARTY"));
} else {
sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString("LEADER_TO_KICK"));
}
} else {
sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString("NO_PARTY_2"));
}
}
} | if ((args.length == 1) && (args[0].equalsIgnoreCase("kick"))) { UUID id = SGApi.getPartyManager().getPlayers().get(sender.getName()); if (id != null) { Party party = SGApi.getPartyManager().getParties().get(id); if (party.getLeader().equalsIgnoreCase(sender.getName())) { for (String members : party.getMembers()) { if ((members != null) && (members.equalsIgnoreCase(args[0]))) { party.removeMember(args[0]); SGApi.getPartyManager().getPlayers().remove(args[0]); sender.sendMessage(org.bukkit.ChatColor.YELLOW + args[0] + I18N.getLocaleString(STR)); Player p = Bukkit.getServer().getPlayer(args[0]); if (p != null) { p.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString(STR)); } if (party.hasNoMembers()) { PartyManager.endParty(sender.getName(), id); } for (String member : party.getMembers()) { if (member != null) { Player play = Bukkit.getServer().getPlayer(member); if (play != null) { play.sendMessage(org.bukkit.ChatColor.YELLOW + args[0] + I18N.getLocaleString(STR)); } } } return; } } sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString(STR) + args[0] + I18N.getLocaleString(STR)); } else { sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString(STR)); } } else { sender.sendMessage(org.bukkit.ChatColor.YELLOW + I18N.getLocaleString(STR)); } } } | /**
* Kicks a player out of the party if you are the party leader
*
* @param sender The player executing the command
*/ | Kicks a player out of the party if you are the party leader | execute | {
"repo_name": "SurvivalGamesDevTeam/TheSurvivalGames",
"path": "src/main/java/com/communitysurvivalgames/thesurvivalgames/command/subcommands/party/KickCommand.java",
"license": "unlicense",
"size": 3111
} | [
"com.communitysurvivalgames.thesurvivalgames.managers.PartyManager",
"com.communitysurvivalgames.thesurvivalgames.managers.SGApi",
"com.communitysurvivalgames.thesurvivalgames.objects.Party",
"org.bukkit.Bukkit",
"org.bukkit.entity.Player"
] | import com.communitysurvivalgames.thesurvivalgames.managers.PartyManager; import com.communitysurvivalgames.thesurvivalgames.managers.SGApi; import com.communitysurvivalgames.thesurvivalgames.objects.Party; import org.bukkit.Bukkit; import org.bukkit.entity.Player; | import com.communitysurvivalgames.thesurvivalgames.managers.*; import com.communitysurvivalgames.thesurvivalgames.objects.*; import org.bukkit.*; import org.bukkit.entity.*; | [
"com.communitysurvivalgames.thesurvivalgames",
"org.bukkit",
"org.bukkit.entity"
] | com.communitysurvivalgames.thesurvivalgames; org.bukkit; org.bukkit.entity; | 1,734,403 |
void onRenderers(TrackRenderer[] renderers, BandwidthMeter bandwidthMeter) {
for (int i = 0; i < RENDERER_COUNT; i++) {
if (renderers[i] == null) {
// Convert a null renderer to a dummy renderer.
renderers[i] = new DummyTrackRenderer();
}
}
// Complete preparation.
this.videoRenderer = renderers[TYPE_VIDEO];
this.codecCounters = videoRenderer instanceof MediaCodecTrackRenderer
? ((MediaCodecTrackRenderer) videoRenderer).codecCounters
: renderers[TYPE_AUDIO] instanceof MediaCodecTrackRenderer
? ((MediaCodecTrackRenderer) renderers[TYPE_AUDIO]).codecCounters : null;
this.bandwidthMeter = bandwidthMeter;
pushSurface(false);
player.prepare(renderers);
rendererBuildingState = RENDERER_BUILDING_STATE_BUILT;
} | void onRenderers(TrackRenderer[] renderers, BandwidthMeter bandwidthMeter) { for (int i = 0; i < RENDERER_COUNT; i++) { if (renderers[i] == null) { renderers[i] = new DummyTrackRenderer(); } } this.videoRenderer = renderers[TYPE_VIDEO]; this.codecCounters = videoRenderer instanceof MediaCodecTrackRenderer ? ((MediaCodecTrackRenderer) videoRenderer).codecCounters : renderers[TYPE_AUDIO] instanceof MediaCodecTrackRenderer ? ((MediaCodecTrackRenderer) renderers[TYPE_AUDIO]).codecCounters : null; this.bandwidthMeter = bandwidthMeter; pushSurface(false); player.prepare(renderers); rendererBuildingState = RENDERER_BUILDING_STATE_BUILT; } | /**
* Invoked with the results from a {@link RendererBuilder}.
*
* @param renderers Renderers indexed by {@link VideoPlayer} TYPE_* constants. An
* individual element may be null if there do not exist tracks of the
* corresponding type.
* @param bandwidthMeter Provides an estimate of the currently available bandwidth. May be
* null.
*/ | Invoked with the results from a <code>RendererBuilder</code> | onRenderers | {
"repo_name": "cartland/androidtv-Leanback",
"path": "app/src/main/java/com/example/android/tvleanback/player/VideoPlayer.java",
"license": "apache-2.0",
"size": 21890
} | [
"com.google.android.exoplayer.DummyTrackRenderer",
"com.google.android.exoplayer.MediaCodecTrackRenderer",
"com.google.android.exoplayer.TrackRenderer",
"com.google.android.exoplayer.upstream.BandwidthMeter"
] | import com.google.android.exoplayer.DummyTrackRenderer; import com.google.android.exoplayer.MediaCodecTrackRenderer; import com.google.android.exoplayer.TrackRenderer; import com.google.android.exoplayer.upstream.BandwidthMeter; | import com.google.android.exoplayer.*; import com.google.android.exoplayer.upstream.*; | [
"com.google.android"
] | com.google.android; | 1,527,462 |
protected void refreshGridLayer() {
if (jConfig != null) {
boolean visible = jConfig.getPropertyBoolean(RulersGridPreferencePage.P_PAGE_RULERGRID_SHOWGRID, true);
GridLayer grid = ((APageFigure) getFigure()).getGrid();
grid.setOrigin((Point) getViewer().getProperty(SnapToGrid.PROPERTY_GRID_ORIGIN));
int x = jConfig.getPropertyInteger(RulersGridPreferencePage.P_PAGE_RULERGRID_GRIDSPACEX, 10);
int y = jConfig.getPropertyInteger(RulersGridPreferencePage.P_PAGE_RULERGRID_GRIDSPACEY, 10);
grid.setSpacing(new Dimension(x, y));
grid.setVisible(visible);
getViewer().setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(x, y));
String mcolor = jConfig.getProperty(RulersGridPreferencePage.P_PAGE_GRID_COLOR,
RulersGridPreferencePage.DEFAULT_GRIDCOLOR);
Color fg = SWTResourceManager.getColor(StringConverter.asRGB(mcolor));
grid.setForegroundColor(fg);
}
} | void function() { if (jConfig != null) { boolean visible = jConfig.getPropertyBoolean(RulersGridPreferencePage.P_PAGE_RULERGRID_SHOWGRID, true); GridLayer grid = ((APageFigure) getFigure()).getGrid(); grid.setOrigin((Point) getViewer().getProperty(SnapToGrid.PROPERTY_GRID_ORIGIN)); int x = jConfig.getPropertyInteger(RulersGridPreferencePage.P_PAGE_RULERGRID_GRIDSPACEX, 10); int y = jConfig.getPropertyInteger(RulersGridPreferencePage.P_PAGE_RULERGRID_GRIDSPACEY, 10); grid.setSpacing(new Dimension(x, y)); grid.setVisible(visible); getViewer().setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(x, y)); String mcolor = jConfig.getProperty(RulersGridPreferencePage.P_PAGE_GRID_COLOR, RulersGridPreferencePage.DEFAULT_GRIDCOLOR); Color fg = SWTResourceManager.getColor(StringConverter.asRGB(mcolor)); grid.setForegroundColor(fg); } } | /**
* Updates the {@link GridLayer grid} based on properties set on the {@link #getViewer() graphical viewer}:
* {@link SnapToGrid#PROPERTY_GRID_VISIBLE}, {@link SnapToGrid#PROPERTY_GRID_SPACING}, and
* {@link SnapToGrid#PROPERTY_GRID_ORIGIN}.
* <p>
* This method is invoked initially when the GridLayer is created, and when any of the above-mentioned properties are
* changed on the viewer.
*/ | Updates the <code>GridLayer grid</code> based on properties set on the <code>#getViewer() graphical viewer</code>: <code>SnapToGrid#PROPERTY_GRID_VISIBLE</code>, <code>SnapToGrid#PROPERTY_GRID_SPACING</code>, and <code>SnapToGrid#PROPERTY_GRID_ORIGIN</code>. This method is invoked initially when the GridLayer is created, and when any of the above-mentioned properties are changed on the viewer | refreshGridLayer | {
"repo_name": "OpenSoftwareSolutions/PDFReporter-Studio",
"path": "com.jaspersoft.studio/src/com/jaspersoft/studio/editor/gef/parts/PageEditPart.java",
"license": "lgpl-3.0",
"size": 13596
} | [
"com.jaspersoft.studio.editor.gef.figures.APageFigure",
"com.jaspersoft.studio.editor.gef.figures.layers.GridLayer",
"com.jaspersoft.studio.preferences.RulersGridPreferencePage",
"org.eclipse.draw2d.geometry.Dimension",
"org.eclipse.draw2d.geometry.Point",
"org.eclipse.gef.SnapToGrid",
"org.eclipse.jface.resource.StringConverter",
"org.eclipse.swt.graphics.Color",
"org.eclipse.wb.swt.SWTResourceManager"
] | import com.jaspersoft.studio.editor.gef.figures.APageFigure; import com.jaspersoft.studio.editor.gef.figures.layers.GridLayer; import com.jaspersoft.studio.preferences.RulersGridPreferencePage; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.gef.SnapToGrid; import org.eclipse.jface.resource.StringConverter; import org.eclipse.swt.graphics.Color; import org.eclipse.wb.swt.SWTResourceManager; | import com.jaspersoft.studio.editor.gef.figures.*; import com.jaspersoft.studio.editor.gef.figures.layers.*; import com.jaspersoft.studio.preferences.*; import org.eclipse.draw2d.geometry.*; import org.eclipse.gef.*; import org.eclipse.jface.resource.*; import org.eclipse.swt.graphics.*; import org.eclipse.wb.swt.*; | [
"com.jaspersoft.studio",
"org.eclipse.draw2d",
"org.eclipse.gef",
"org.eclipse.jface",
"org.eclipse.swt",
"org.eclipse.wb"
] | com.jaspersoft.studio; org.eclipse.draw2d; org.eclipse.gef; org.eclipse.jface; org.eclipse.swt; org.eclipse.wb; | 2,525,567 |
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
headers.set(CLIENT_ID, apiKey);
return headers;
} | HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); headers.set(CLIENT_ID, apiKey); return headers; } | /**
* Creates http headers object based, which contains given api-key
* @param apiKey the api-key to enrich the headers with
* @return the created headers containing the api-key
*/ | Creates http headers object based, which contains given api-key | createHeaders | {
"repo_name": "rufer7/swisscom-sms-api-client",
"path": "src/main/java/be/rufer/swisscom/sms/api/factory/HeaderFactory.java",
"license": "apache-2.0",
"size": 1440
} | [
"org.springframework.http.HttpHeaders",
"org.springframework.http.MediaType"
] | import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; | import org.springframework.http.*; | [
"org.springframework.http"
] | org.springframework.http; | 1,927,604 |
public static int frequency(Iterator<?> iterator, @Nullable Object element) {
return size(filter(iterator, equalTo(element)));
} | static int function(Iterator<?> iterator, @Nullable Object element) { return size(filter(iterator, equalTo(element))); } | /**
* Returns the number of elements in the specified iterator that equal the
* specified object. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @see Collections#frequency
*/ | Returns the number of elements in the specified iterator that equal the specified object. The iterator will be left exhausted: its hasNext() method will return false | frequency | {
"repo_name": "tianweidut/guava-study",
"path": "guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java",
"license": "apache-2.0",
"size": 44344
} | [
"com.google.common.base.Predicates",
"java.util.Iterator",
"javax.annotation.Nullable"
] | import com.google.common.base.Predicates; import java.util.Iterator; import javax.annotation.Nullable; | import com.google.common.base.*; import java.util.*; import javax.annotation.*; | [
"com.google.common",
"java.util",
"javax.annotation"
] | com.google.common; java.util; javax.annotation; | 354,533 |
boolean exists(ID id)
throws ForbiddenUserException, FailedRequestException; | boolean exists(ID id) throws ForbiddenUserException, FailedRequestException; | /** True if a document exists in the database with the specified id
* @param id the unique identifier of the pojo (the value of the field annotated with
* {@literal @}{@link Id Id})
* @return true if a document exists in the database with the specified id
*/ | True if a document exists in the database with the specified id | exists | {
"repo_name": "marklogic/java-client-api",
"path": "marklogic-client-api/src/main/java/com/marklogic/client/pojo/PojoRepository.java",
"license": "apache-2.0",
"size": 25907
} | [
"com.marklogic.client.FailedRequestException",
"com.marklogic.client.ForbiddenUserException"
] | import com.marklogic.client.FailedRequestException; import com.marklogic.client.ForbiddenUserException; | import com.marklogic.client.*; | [
"com.marklogic.client"
] | com.marklogic.client; | 774,503 |
Object browseSelected(String queueName, String messageSelector, BrowserCallback action) throws JmsException; | Object browseSelected(String queueName, String messageSelector, BrowserCallback action) throws JmsException; | /**
* Browse selected messages in a JMS queue. The callback gives access to the JMS
* Session and QueueBrowser in order to browse the queue and react to the contents.
* @param queueName the name of the queue to browse
* (to be resolved to an actual destination by a DestinationResolver)
* @param messageSelector the JMS message selector expression (or <code>null</code> if none).
* See the JMS specification for a detailed definition of selector expressions.
* @param action callback object that exposes the session/browser pair
* @return the result object from working with the session
* @throws JmsException checked JMSException converted to unchecked
*/ | Browse selected messages in a JMS queue. The callback gives access to the JMS Session and QueueBrowser in order to browse the queue and react to the contents | browseSelected | {
"repo_name": "cbeams-archive/spring-framework-2.5.x",
"path": "src/org/springframework/jms/core/JmsOperations.java",
"license": "apache-2.0",
"size": 21601
} | [
"org.springframework.jms.JmsException"
] | import org.springframework.jms.JmsException; | import org.springframework.jms.*; | [
"org.springframework.jms"
] | org.springframework.jms; | 2,208,120 |
protected void onMessage(WebSocketRequestHandler handler, TextMessage message)
{
} | void function(WebSocketRequestHandler handler, TextMessage message) { } | /**
* A callback method called when there is a text message sent by the client
*
* @param handler
* The request handler that can be used to send messages back to the client
* @param message
* The text message sent by the client
*/ | A callback method called when there is a text message sent by the client | onMessage | {
"repo_name": "mafulafunk/wicket",
"path": "wicket-native-websocket/wicket-native-websocket-core/src/main/java/org/apache/wicket/protocol/ws/api/WebSocketBehavior.java",
"license": "apache-2.0",
"size": 5109
} | [
"org.apache.wicket.protocol.ws.api.message.TextMessage"
] | import org.apache.wicket.protocol.ws.api.message.TextMessage; | import org.apache.wicket.protocol.ws.api.message.*; | [
"org.apache.wicket"
] | org.apache.wicket; | 493,030 |
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException(
"I/O error parsing XML document for application context [" + getDisplayName() + "]", ex);
}
} | final void function() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException( STR + getDisplayName() + "]", ex); } } | /**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/ | This implementation performs an actual refresh of this context's underlying bean factory, shutting down the previous bean factory (if any) and initializing a fresh bean factory for the next phase of the context's lifecycle | refreshBeanFactory | {
"repo_name": "mattxia/spring-2.5-analysis",
"path": "src/org/springframework/context/support/AbstractRefreshableApplicationContext.java",
"license": "apache-2.0",
"size": 7525
} | [
"java.io.IOException",
"org.springframework.beans.BeansException",
"org.springframework.beans.factory.support.DefaultListableBeanFactory",
"org.springframework.context.ApplicationContextException"
] | import java.io.IOException; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContextException; | import java.io.*; import org.springframework.beans.*; import org.springframework.beans.factory.support.*; import org.springframework.context.*; | [
"java.io",
"org.springframework.beans",
"org.springframework.context"
] | java.io; org.springframework.beans; org.springframework.context; | 1,191,916 |
public void respondWithHtml(HttpStatus status, String body) throws IOException {
beginResponse(status);
sendHeader("Content-Length", String.valueOf(body.length()));
sendHeader("Content-Type", "text/html");
endHeader();
writeClientBody(body);
endResponse();
}
| void function(HttpStatus status, String body) throws IOException { beginResponse(status); sendHeader(STR, String.valueOf(body.length())); sendHeader(STR, STR); endHeader(); writeClientBody(body); endResponse(); } | /**
* Responds to client with some html text
*/ | Responds to client with some html text | respondWithHtml | {
"repo_name": "oxguy3/AwesomeProxy",
"path": "src/RequestWorker.java",
"license": "mit",
"size": 24573
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 821,564 |
private void dfs(Digraph G, int v)
{
this.onCheck[v] = true;
this.marked[v] = true;
for (int w: G.adj(v))
{
if (!this.marked[w])
{
edgeTo[w] = v;
depth[w] = depth[v] + 1;
dfs(G, w);
}
else if (this.onCheck[w])
{
this.cycleRoots.insert(new CycleHead(
v, w, depth[v] - depth[w]));
}
}
this.onCheck[v] = false;
} | void function(Digraph G, int v) { this.onCheck[v] = true; this.marked[v] = true; for (int w: G.adj(v)) { if (!this.marked[w]) { edgeTo[w] = v; depth[w] = depth[v] + 1; dfs(G, w); } else if (this.onCheck[w]) { this.cycleRoots.insert(new CycleHead( v, w, depth[v] - depth[w])); } } this.onCheck[v] = false; } | /**
* Find all possible cycle
* @param G Digraph
* @param v Vertex
*/ | Find all possible cycle | dfs | {
"repo_name": "Bladefidz/algorithm",
"path": "coursera/Algorithms/directed-graph/ShortestDirectedCycle.java",
"license": "unlicense",
"size": 3189
} | [
"edu.princeton.cs.algs4.Digraph"
] | import edu.princeton.cs.algs4.Digraph; | import edu.princeton.cs.algs4.*; | [
"edu.princeton.cs"
] | edu.princeton.cs; | 155,226 |
public AcsChatThreadEventBaseProperties setCreateTime(OffsetDateTime createTime) {
this.createTime = createTime;
return this;
} | AcsChatThreadEventBaseProperties function(OffsetDateTime createTime) { this.createTime = createTime; return this; } | /**
* Set the createTime property: The original creation time of the thread.
*
* @param createTime the createTime value to set.
* @return the AcsChatThreadEventBaseProperties object itself.
*/ | Set the createTime property: The original creation time of the thread | setCreateTime | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventBaseProperties.java",
"license": "mit",
"size": 2545
} | [
"java.time.OffsetDateTime"
] | import java.time.OffsetDateTime; | import java.time.*; | [
"java.time"
] | java.time; | 2,886,861 |
public T secureXML(String secureTag, Map<String, String> namespaces, boolean secureTagContents, String recipientKeyAlias,
String xmlCipherAlgorithm, String keyCipherAlgorithm, KeyStoreParameters keyOrTrustStoreParameters, String keyPassword) {
XMLSecurityDataFormat xsdf = new XMLSecurityDataFormat(secureTag, namespaces, secureTagContents, recipientKeyAlias, xmlCipherAlgorithm,
keyCipherAlgorithm, keyOrTrustStoreParameters, keyPassword);
return dataFormat(xsdf);
} | T function(String secureTag, Map<String, String> namespaces, boolean secureTagContents, String recipientKeyAlias, String xmlCipherAlgorithm, String keyCipherAlgorithm, KeyStoreParameters keyOrTrustStoreParameters, String keyPassword) { XMLSecurityDataFormat xsdf = new XMLSecurityDataFormat(secureTag, namespaces, secureTagContents, recipientKeyAlias, xmlCipherAlgorithm, keyCipherAlgorithm, keyOrTrustStoreParameters, keyPassword); return dataFormat(xsdf); } | /**
* Uses the XML Security data format
*/ | Uses the XML Security data format | secureXML | {
"repo_name": "rmarting/camel",
"path": "camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java",
"license": "apache-2.0",
"size": 42614
} | [
"java.util.Map",
"org.apache.camel.model.dataformat.XMLSecurityDataFormat",
"org.apache.camel.util.jsse.KeyStoreParameters"
] | import java.util.Map; import org.apache.camel.model.dataformat.XMLSecurityDataFormat; import org.apache.camel.util.jsse.KeyStoreParameters; | import java.util.*; import org.apache.camel.model.dataformat.*; import org.apache.camel.util.jsse.*; | [
"java.util",
"org.apache.camel"
] | java.util; org.apache.camel; | 2,066,903 |
@Override
public void execute() throws BuildException
{
checkParameters();
reportFilesMap = new HashMap<String, String>();
AntClassLoader classLoader = null;
if (classpath != null)
{
jasperReportsContext.setProperty(JRCompiler.COMPILER_CLASSPATH, String.valueOf(classpath));//FIXMECONTEXT is this needed? what about class loader below/
ClassLoader parentClassLoader = getClass().getClassLoader();
classLoader = new AntClassLoader(parentClassLoader, getProject(), classpath, true);
classLoader.setThreadContextLoader();
}
try
{
scanSrc();
decompile();
}
finally
{
if (classLoader != null)
{
classLoader.resetThreadContextLoader();
}
}
}
| void function() throws BuildException { checkParameters(); reportFilesMap = new HashMap<String, String>(); AntClassLoader classLoader = null; if (classpath != null) { jasperReportsContext.setProperty(JRCompiler.COMPILER_CLASSPATH, String.valueOf(classpath)); ClassLoader parentClassLoader = getClass().getClassLoader(); classLoader = new AntClassLoader(parentClassLoader, getProject(), classpath, true); classLoader.setThreadContextLoader(); } try { scanSrc(); decompile(); } finally { if (classLoader != null) { classLoader.resetThreadContextLoader(); } } } | /**
* Executes the task.
*/ | Executes the task | execute | {
"repo_name": "MHTaleb/Encologim",
"path": "lib/JasperReport/src/net/sf/jasperreports/ant/JRAntDecompileTask.java",
"license": "gpl-3.0",
"size": 8264
} | [
"java.util.HashMap",
"net.sf.jasperreports.engine.design.JRCompiler",
"org.apache.tools.ant.AntClassLoader",
"org.apache.tools.ant.BuildException"
] | import java.util.HashMap; import net.sf.jasperreports.engine.design.JRCompiler; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; | import java.util.*; import net.sf.jasperreports.engine.design.*; import org.apache.tools.ant.*; | [
"java.util",
"net.sf.jasperreports",
"org.apache.tools"
] | java.util; net.sf.jasperreports; org.apache.tools; | 2,743,065 |
public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject, JSONObject restrictions,Record thisr)
throws ExistException, UnimplementedException, UnderlyingStorageException {
updateJSON( root, creds, cache, filePath, jsonObject, restrictions, thisr, thisr.getServicesURL()+"/");
} | void function(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject, JSONObject restrictions,Record thisr) throws ExistException, UnimplementedException, UnderlyingStorageException { updateJSON( root, creds, cache, filePath, jsonObject, restrictions, thisr, thisr.getServicesURL()+"/"); } | /**
* guess service url based on record type and call the function with more parameters
* @param root
* @param creds
* @param cache
* @param filePath
* @param jsonObject
* @param thisr
* @throws ExistException
* @throws UnimplementedException
* @throws UnderlyingStorageException
*/ | guess service url based on record type and call the function with more parameters | updateJSON | {
"repo_name": "cherryhill/collectionspace-application",
"path": "cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/GenericStorage.java",
"license": "apache-2.0",
"size": 93300
} | [
"org.collectionspace.chain.csp.schema.Record",
"org.collectionspace.csp.api.core.CSPRequestCache",
"org.collectionspace.csp.api.core.CSPRequestCredentials",
"org.collectionspace.csp.api.persistence.ExistException",
"org.collectionspace.csp.api.persistence.UnderlyingStorageException",
"org.collectionspace.csp.api.persistence.UnimplementedException",
"org.collectionspace.csp.helper.persistence.ContextualisedStorage",
"org.json.JSONObject"
] | import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.csp.api.core.CSPRequestCache; import org.collectionspace.csp.api.core.CSPRequestCredentials; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.helper.persistence.ContextualisedStorage; import org.json.JSONObject; | import org.collectionspace.chain.csp.schema.*; import org.collectionspace.csp.api.core.*; import org.collectionspace.csp.api.persistence.*; import org.collectionspace.csp.helper.persistence.*; import org.json.*; | [
"org.collectionspace.chain",
"org.collectionspace.csp",
"org.json"
] | org.collectionspace.chain; org.collectionspace.csp; org.json; | 1,472,958 |
private void dci_closed(boolean firstTime, List<Integer> closedset, BitSet bitset,
List<Integer> postset, List<Integer> preset, BitMatrix matrix, BitMatrix originalMatrix) throws IOException {
//L2: For all i in postset
for(Integer i : postset){
// L4 Calculate the tidset of newgen
// where newgen is "closedset" U {i}
BitSet newgenTIDs;
// if the first time
if(firstTime){
// it is the tidset of it
newgenTIDs = matrix.getBitSetOf(i);
}else{
// otherwise we intersect the tidset of closedset and the
// tidset of i
newgenTIDs = (BitSet)bitset.clone();
newgenTIDs.and(matrix.getBitSetOf(i));
}
// if newgen has a support no less than minsup
if(newgenTIDs.cardinality() >= minSuppRelative){
// L3: newgen = closedset U {i}
// Create the itemset for newgen
List<Integer> newgen = new ArrayList<Integer>(closedset.size()+1);
newgen.addAll(closedset);
newgen.add(i);
// L5: if newgen is not a duplicate
if(is_dup(newgenTIDs, preset, matrix) == false){
// L6: ClosedsetNew = newGen
List<Integer> closedsetNew = new ArrayList<Integer>();
closedsetNew.addAll(newgen);
// calculate tidset
BitSet closedsetNewTIDs = null;
// if first time
if(firstTime){
// the new tidset of closed set is the tidset of i
closedsetNewTIDs = (BitSet)matrix.getBitSetOf(i).clone();
}else{
// otherwise, we add the tidset of newgen
closedsetNewTIDs = (BitSet)newgenTIDs.clone();
}
// L7 : PostsetNew = emptyset
List<Integer> postsetNew = new ArrayList<Integer>();
// L8 for each j in Postset such that i _ j :
for(Integer j : postset){
// if i is smaller than j according to the total order on items
if(smallerAccordingToTotalOrder(i, j, originalMatrix)){
// L9
// if the tidset of j contains the tidset of newgen
if(isAllContainedIn(newgenTIDs, matrix.getBitSetOf(j))){
closedsetNew.add(j);
// recalculate TIDS of closedsetNEW by intersection
closedsetNewTIDs.and(matrix.getBitSetOf(j));
}else{
// otherwise add j to the new postset
postsetNew.add(j);
}
}
}
// L15 : write out closedsetNew and its support
int support = closedsetNewTIDs.cardinality();
writeOut(closedsetNew, support);
// L16: recursive call
// FIXED: we have to make a copy of preset before the recursive call
List<Integer> presetNew = new ArrayList<Integer>(preset);
if(firstTime){
// THIS IS THE "Dataset projection" optimization described in the TKDE paper.
BitMatrix projectedMatrix = projectMatrix(matrix, closedsetNewTIDs, support);
BitSet replacement = new BitSet(support);
replacement.set(0, support, true);
dci_closed(false, closedsetNew, replacement, postsetNew, presetNew, projectedMatrix, matrix);
}else{
dci_closed(false, closedsetNew, closedsetNewTIDs, postsetNew, presetNew, matrix, originalMatrix);
}
// L17 : Preset = Preset U {i}
preset.add(i);
}
}
}
} | void function(boolean firstTime, List<Integer> closedset, BitSet bitset, List<Integer> postset, List<Integer> preset, BitMatrix matrix, BitMatrix originalMatrix) throws IOException { for(Integer i : postset){ BitSet newgenTIDs; if(firstTime){ newgenTIDs = matrix.getBitSetOf(i); }else{ newgenTIDs = (BitSet)bitset.clone(); newgenTIDs.and(matrix.getBitSetOf(i)); } if(newgenTIDs.cardinality() >= minSuppRelative){ List<Integer> newgen = new ArrayList<Integer>(closedset.size()+1); newgen.addAll(closedset); newgen.add(i); if(is_dup(newgenTIDs, preset, matrix) == false){ List<Integer> closedsetNew = new ArrayList<Integer>(); closedsetNew.addAll(newgen); BitSet closedsetNewTIDs = null; if(firstTime){ closedsetNewTIDs = (BitSet)matrix.getBitSetOf(i).clone(); }else{ closedsetNewTIDs = (BitSet)newgenTIDs.clone(); } List<Integer> postsetNew = new ArrayList<Integer>(); for(Integer j : postset){ if(smallerAccordingToTotalOrder(i, j, originalMatrix)){ if(isAllContainedIn(newgenTIDs, matrix.getBitSetOf(j))){ closedsetNew.add(j); closedsetNewTIDs.and(matrix.getBitSetOf(j)); }else{ postsetNew.add(j); } } } int support = closedsetNewTIDs.cardinality(); writeOut(closedsetNew, support); List<Integer> presetNew = new ArrayList<Integer>(preset); if(firstTime){ BitMatrix projectedMatrix = projectMatrix(matrix, closedsetNewTIDs, support); BitSet replacement = new BitSet(support); replacement.set(0, support, true); dci_closed(false, closedsetNew, replacement, postsetNew, presetNew, projectedMatrix, matrix); }else{ dci_closed(false, closedsetNew, closedsetNewTIDs, postsetNew, presetNew, matrix, originalMatrix); } preset.add(i); } } } } | /**
* The method "DCI_CLOSED" as described in the paper.
* @param firstime true if this method is called for the first time
* @param closedset the closed set (see paper).
* @param bitset the tids set of the closed set
* @param postset the postset (see paper for full details)
* @param preset the preset (see paper)
* @param matrix the modified matrix
* @param originalMatrix the original bitmatrix
* @exception IOException if error writing the output file
*/ | The method "DCI_CLOSED" as described in the paper | dci_closed | {
"repo_name": "dragonzhou/humor",
"path": "src/ca/pfv/spmf/algorithms/frequentpatterns/dci_closed_optimized/AlgoDCI_Closed_Optimized.java",
"license": "apache-2.0",
"size": 15426
} | [
"java.io.IOException",
"java.util.ArrayList",
"java.util.BitSet",
"java.util.List"
] | import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.List; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 314,487 |
@Override
public Integer save(ILabelBean labelBean, boolean copy, Integer personID, Locale locale) {
return PriorityBL.save(labelBean, locale);
}
| Integer function(ILabelBean labelBean, boolean copy, Integer personID, Locale locale) { return PriorityBL.save(labelBean, locale); } | /**
* Saves a new/modified list entry
* If sortOrder is not set it will be set to be the next available sortOrder
* @param labelBean
* @param copy
* @param personID
* @param locale
* @return
*/ | Saves a new/modified list entry If sortOrder is not set it will be set to be the next available sortOrder | save | {
"repo_name": "trackplus/Genji",
"path": "src/main/java/com/aurel/track/admin/customize/lists/systemOption/PriorityConfigBL.java",
"license": "gpl-3.0",
"size": 8885
} | [
"com.aurel.track.beans.ILabelBean",
"java.util.Locale"
] | import com.aurel.track.beans.ILabelBean; import java.util.Locale; | import com.aurel.track.beans.*; import java.util.*; | [
"com.aurel.track",
"java.util"
] | com.aurel.track; java.util; | 724,527 |
public void rewrite(Server server) throws IOException {
StringBuffer page = new StringBuffer();
Matcher matcher = linkPattern.matcher(stream.toString());
while (matcher.find()) {
String link = matcher.group(6).replaceAll("\\$", "\\\\\\$");
if (link.length() == 0) {
link = "/";
}
String rewritten = null;
if (matcher.group(4) != null) {
rewritten = handleExternalLink(matcher, link);
} else if (link.startsWith("/")) {
rewritten = handleLocalLink(server, matcher, link);
}
if (rewritten != null) {
if (log.isDebugEnabled()) {
log.debug("Found link " + link + " >> " + rewritten);
}
matcher.appendReplacement(page, rewritten);
}
}
matcher.appendTail(page);
originalStream.print(page.toString());
}
| void function(Server server) throws IOException { StringBuffer page = new StringBuffer(); Matcher matcher = linkPattern.matcher(stream.toString()); while (matcher.find()) { String link = matcher.group(6).replaceAll("\\$", STR); if (link.length() == 0) { link = "/"; } String rewritten = null; if (matcher.group(4) != null) { rewritten = handleExternalLink(matcher, link); } else if (link.startsWith("/")) { rewritten = handleLocalLink(server, matcher, link); } if (rewritten != null) { if (log.isDebugEnabled()) { log.debug(STR + link + STR + rewritten); } matcher.appendReplacement(page, rewritten); } } matcher.appendTail(page); originalStream.print(page.toString()); } | /**
* Processes the stream looking for links, all links
* found are rewritten. After this the stream is written
* to the response.
*
* @param server The server that we are using for this request.
* @throws IOException Is thrown when there is a problem with the streams
*/ | Processes the stream looking for links, all links found are rewritten. After this the stream is written to the response | rewrite | {
"repo_name": "tfr42/j2ep",
"path": "src/main/java/net/sf/j2ep/UrlRewritingOutputStream.java",
"license": "apache-2.0",
"size": 7210
} | [
"java.io.IOException",
"java.util.regex.Matcher",
"net.sf.j2ep.model.Server"
] | import java.io.IOException; import java.util.regex.Matcher; import net.sf.j2ep.model.Server; | import java.io.*; import java.util.regex.*; import net.sf.j2ep.model.*; | [
"java.io",
"java.util",
"net.sf.j2ep"
] | java.io; java.util; net.sf.j2ep; | 2,035,753 |
@After
public void tearDown( ) throws Exception {
logger.debug( TestConstants.setUpMethodLoggerMsg );
} | void function( ) throws Exception { logger.debug( TestConstants.setUpMethodLoggerMsg ); } | /**
* Tear down.
*
* @throws Exception the exception
*/ | Tear down | tearDown | {
"repo_name": "arkoghosh11/bloom-test",
"path": "bloom-dao/src/test/java/com/mana/innovative/dao/common/WhenUpdateAnAddressThenTestAddressDAOUpdateMethods.java",
"license": "apache-2.0",
"size": 1803
} | [
"com.mana.innovative.constants.TestConstants"
] | import com.mana.innovative.constants.TestConstants; | import com.mana.innovative.constants.*; | [
"com.mana.innovative"
] | com.mana.innovative; | 1,221,626 |
static public ArrayList<MetaHuApp> parseList( String strJson ) throws JSONException
{
JSONObject joList = new JSONObject( strJson );
JSONArray jaList = joList.getJSONArray( "appList" );
ArrayList<MetaHuApp> metas = new ArrayList<MetaHuApp>( jaList.length() );
for( int i = 0; i < jaList.length(); i++ )
{
JSONObject jo = jaList.getJSONObject( i );
MetaHuApp meta = new MetaHuApp( jo );
metas.add( meta );
}
return metas;
} | static ArrayList<MetaHuApp> function( String strJson ) throws JSONException { JSONObject joList = new JSONObject( strJson ); JSONArray jaList = joList.getJSONArray( STR ); ArrayList<MetaHuApp> metas = new ArrayList<MetaHuApp>( jaList.length() ); for( int i = 0; i < jaList.length(); i++ ) { JSONObject jo = jaList.getJSONObject( i ); MetaHuApp meta = new MetaHuApp( jo ); metas.add( meta ); } return metas; } | /**
* Parse a list of objects.
* @param strJson : string that contains a list of objects in JSON format.
* @return List of objects.
* @throws JSONException if the content is not in a valid JSON format.
*/ | Parse a list of objects | parseList | {
"repo_name": "yangjun2/android",
"path": "androidhap/InfinitiInTouch/src/com/airbiquity/hap/MetaHuApp.java",
"license": "unlicense",
"size": 3354
} | [
"java.util.ArrayList",
"org.json.JSONArray",
"org.json.JSONException",
"org.json.JSONObject"
] | import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; | import java.util.*; import org.json.*; | [
"java.util",
"org.json"
] | java.util; org.json; | 2,909,973 |
public static int nextToUppercase(SurfaceFormOccurrence surfaceFormOccurrence) {
if(nonSentenceInitialUppercase(surfaceFormOccurrence) == 0)
return 0;
String leftNeighbourToken = null;
try {
leftNeighbourToken = ((TaggedText) surfaceFormOccurrence.context()).taggedTokenProvider()
.getLeftNeighbourToken(surfaceFormOccurrence).getToken();
} catch (ItemNotFoundException ignored) {
}
String rightNeighbourToken = null;
try {
rightNeighbourToken = ((TaggedText) surfaceFormOccurrence.context()).taggedTokenProvider()
.getRightNeighbourToken(surfaceFormOccurrence).getToken();
} catch (ItemNotFoundException ignored) {
}
if (rightNeighbourToken != null && Character.isUpperCase(rightNeighbourToken.charAt(0))) {
return 1;
}else if(leftNeighbourToken != null && Character.isUpperCase(leftNeighbourToken.charAt(0))) {
return 1;
} else {
return 0;
}
} | static int function(SurfaceFormOccurrence surfaceFormOccurrence) { if(nonSentenceInitialUppercase(surfaceFormOccurrence) == 0) return 0; String leftNeighbourToken = null; try { leftNeighbourToken = ((TaggedText) surfaceFormOccurrence.context()).taggedTokenProvider() .getLeftNeighbourToken(surfaceFormOccurrence).getToken(); } catch (ItemNotFoundException ignored) { } String rightNeighbourToken = null; try { rightNeighbourToken = ((TaggedText) surfaceFormOccurrence.context()).taggedTokenProvider() .getRightNeighbourToken(surfaceFormOccurrence).getToken(); } catch (ItemNotFoundException ignored) { } if (rightNeighbourToken != null && Character.isUpperCase(rightNeighbourToken.charAt(0))) { return 1; }else if(leftNeighbourToken != null && Character.isUpperCase(leftNeighbourToken.charAt(0))) { return 1; } else { return 0; } } | /**
* Surface form occurs next to an uppercase word
*
* @param surfaceFormOccurrence the surface form in context
* @return does surface form occur next to uppercase word?
*/ | Surface form occurs next to an uppercase word | nextToUppercase | {
"repo_name": "Skunnyk/dbpedia-spotlight-model",
"path": "core/src/main/java/org/dbpedia/spotlight/spot/cooccurrence/features/CandidateFeatures.java",
"license": "apache-2.0",
"size": 10436
} | [
"org.dbpedia.spotlight.exceptions.ItemNotFoundException",
"org.dbpedia.spotlight.model.SurfaceFormOccurrence",
"org.dbpedia.spotlight.model.TaggedText"
] | import org.dbpedia.spotlight.exceptions.ItemNotFoundException; import org.dbpedia.spotlight.model.SurfaceFormOccurrence; import org.dbpedia.spotlight.model.TaggedText; | import org.dbpedia.spotlight.exceptions.*; import org.dbpedia.spotlight.model.*; | [
"org.dbpedia.spotlight"
] | org.dbpedia.spotlight; | 2,440,434 |
private ExtendedBlock updateBlockForPipeline(
Set<StripedDataStreamer> healthyStreamers) throws IOException {
final LocatedBlock updated = dfsClient.namenode.updateBlockForPipeline(
currentBlockGroup, dfsClient.clientName);
final long newGS = updated.getBlock().getGenerationStamp();
ExtendedBlock newBlock = new ExtendedBlock(currentBlockGroup);
newBlock.setGenerationStamp(newGS);
final LocatedBlock[] updatedBlks = StripedBlockUtil.parseStripedBlockGroup(
(LocatedStripedBlock) updated, cellSize, numDataBlocks,
numAllBlocks - numDataBlocks);
for (int i = 0; i < numAllBlocks; i++) {
StripedDataStreamer si = getStripedDataStreamer(i);
if (healthyStreamers.contains(si)) {
final LocatedBlock lb = new LocatedBlock(new ExtendedBlock(newBlock),
null, null, null, -1, updated.isCorrupt(), null);
lb.setBlockToken(updatedBlks[i].getBlockToken());
coordinator.getNewBlocks().offer(i, lb);
}
}
return newBlock;
} | ExtendedBlock function( Set<StripedDataStreamer> healthyStreamers) throws IOException { final LocatedBlock updated = dfsClient.namenode.updateBlockForPipeline( currentBlockGroup, dfsClient.clientName); final long newGS = updated.getBlock().getGenerationStamp(); ExtendedBlock newBlock = new ExtendedBlock(currentBlockGroup); newBlock.setGenerationStamp(newGS); final LocatedBlock[] updatedBlks = StripedBlockUtil.parseStripedBlockGroup( (LocatedStripedBlock) updated, cellSize, numDataBlocks, numAllBlocks - numDataBlocks); for (int i = 0; i < numAllBlocks; i++) { StripedDataStreamer si = getStripedDataStreamer(i); if (healthyStreamers.contains(si)) { final LocatedBlock lb = new LocatedBlock(new ExtendedBlock(newBlock), null, null, null, -1, updated.isCorrupt(), null); lb.setBlockToken(updatedBlks[i].getBlockToken()); coordinator.getNewBlocks().offer(i, lb); } } return newBlock; } | /**
* Call {@link ClientProtocol#updateBlockForPipeline} and assign updated block
* to healthy streamers.
* @param healthyStreamers The healthy data streamers. These streamers join
* the failure handling.
*/ | Call <code>ClientProtocol#updateBlockForPipeline</code> and assign updated block to healthy streamers | updateBlockForPipeline | {
"repo_name": "aliyun-beta/aliyun-oss-hadoop-fs",
"path": "hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java",
"license": "apache-2.0",
"size": 35838
} | [
"java.io.IOException",
"java.util.Set",
"org.apache.hadoop.hdfs.protocol.ExtendedBlock",
"org.apache.hadoop.hdfs.protocol.LocatedBlock",
"org.apache.hadoop.hdfs.protocol.LocatedStripedBlock",
"org.apache.hadoop.hdfs.util.StripedBlockUtil"
] | import java.io.IOException; import java.util.Set; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedStripedBlock; import org.apache.hadoop.hdfs.util.StripedBlockUtil; | import java.io.*; import java.util.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.util.*; | [
"java.io",
"java.util",
"org.apache.hadoop"
] | java.io; java.util; org.apache.hadoop; | 2,641,699 |
public boolean initialize( URL url )
{
initialized( SET, false );
cleanup();
if( url == null )
{
errorMessage( "url null in method 'initialize'" );
cleanup();
return false;
}
try
{
myAudioInputStream = AudioSystem.getAudioInputStream(
new BufferedInputStream( url.openStream() ) );
}
catch( UnsupportedAudioFileException uafe )
{
errorMessage( "Unsupported audio format in method 'initialize'" );
printStackTrace( uafe );
return false;
}
catch( IOException ioe )
{
errorMessage( "Error setting up audio input stream in method " +
"'initialize'" );
printStackTrace( ioe );
return false;
}
endOfStream( SET, false );
initialized( SET, true );
return true;
} | boolean function( URL url ) { initialized( SET, false ); cleanup(); if( url == null ) { errorMessage( STR ); cleanup(); return false; } try { myAudioInputStream = AudioSystem.getAudioInputStream( new BufferedInputStream( url.openStream() ) ); } catch( UnsupportedAudioFileException uafe ) { errorMessage( STR ); printStackTrace( uafe ); return false; } catch( IOException ioe ) { errorMessage( STR + STR ); printStackTrace( ioe ); return false; } endOfStream( SET, false ); initialized( SET, true ); return true; } | /**
* Prepares an audio stream to read from. If another stream is already opened,
* it will be closed and a new audio stream opened in its place.
* @param url URL to an audio file to stream from.
* @return False if an error occurred or if end of stream was reached.
*/ | Prepares an audio stream to read from. If another stream is already opened, it will be closed and a new audio stream opened in its place | initialize | {
"repo_name": "yuripourre/etyllica",
"path": "src/main/java/sound/paulscode/codecs/CodecWav.java",
"license": "lgpl-3.0",
"size": 17420
} | [
"java.io.BufferedInputStream",
"java.io.IOException",
"javax.sound.sampled.AudioSystem",
"javax.sound.sampled.UnsupportedAudioFileException"
] | import java.io.BufferedInputStream; import java.io.IOException; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; | import java.io.*; import javax.sound.sampled.*; | [
"java.io",
"javax.sound"
] | java.io; javax.sound; | 1,532,756 |
public Map<String, List<FRRoom>> getAutoComplete() {
return listRoom;
} | Map<String, List<FRRoom>> function() { return listRoom; } | /**
* Return the rooms autocompleted, mapped by buildings.
*
* @return the rooms autocompleted, mapped by buildings.
*/ | Return the rooms autocompleted, mapped by buildings | getAutoComplete | {
"repo_name": "ValentinMinder/pocketcampus",
"path": "plugin/freeroom/android/src/main/java/org/pocketcampus/plugin/freeroom/android/FreeRoomModel.java",
"license": "bsd-3-clause",
"size": 49308
} | [
"java.util.List",
"java.util.Map",
"org.pocketcampus.plugin.freeroom.shared.FRRoom"
] | import java.util.List; import java.util.Map; import org.pocketcampus.plugin.freeroom.shared.FRRoom; | import java.util.*; import org.pocketcampus.plugin.freeroom.shared.*; | [
"java.util",
"org.pocketcampus.plugin"
] | java.util; org.pocketcampus.plugin; | 269,152 |
public void disapproveSalaryExpenseDocument(SalaryExpenseTransferDocument document) throws Exception; | void function(SalaryExpenseTransferDocument document) throws Exception; | /**
* Disapproves the salary expense document due to effort validation errors.
*
* @param document - document to cancel
*/ | Disapproves the salary expense document due to effort validation errors | disapproveSalaryExpenseDocument | {
"repo_name": "quikkian-ua-devops/will-financials",
"path": "kfs-ld/src/main/java/org/kuali/kfs/module/ld/document/service/SalaryTransferPeriodValidationService.java",
"license": "agpl-3.0",
"size": 1767
} | [
"org.kuali.kfs.module.ld.document.SalaryExpenseTransferDocument"
] | import org.kuali.kfs.module.ld.document.SalaryExpenseTransferDocument; | import org.kuali.kfs.module.ld.document.*; | [
"org.kuali.kfs"
] | org.kuali.kfs; | 1,540,638 |
@Override
@RabbitListener(
bindings =
@QueueBinding(
value =
@Queue(
value = RabbitConfiguration.QUEUE_NAME_MANAGER_REGISTER,
durable = "true",
autoDelete = "true"),
exchange =
@Exchange(
value = RabbitConfiguration.EXCHANGE_NAME_OPENBATON,
ignoreDeclarationExceptions = "true",
type = RabbitConfiguration.EXCHANGE_TYPE_OPENBATON,
durable = RabbitConfiguration.EXCHANGE_DURABLE_OPENBATON),
key = RabbitConfiguration.QUEUE_NAME_MANAGER_REGISTER))
public String enableManager(String message) {
try {
// deserialize message
JsonObject body = gson.fromJson(message, JsonObject.class);
if (!body.has("action")) {
log.error("Could not process Json message. The 'action' property is missing.");
return null;
}
JsonElement vnfmManagerEndpoint = body.get("vnfmManagerEndpoint");
switch (body.get("action").getAsString().toLowerCase()) {
case "register":
{
// register plugin or vnfm
if (!body.has("type")) {
log.error("Could not process Json message. The 'type' property is missing.");
return null;
}
String username = body.get("type").getAsString();
String password = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(16);
ManagerCredentials managerCredentials =
managerCredentialsRepository.findFirstByRabbitUsername(username);
VnfmManagerEndpoint endpoint = null;
boolean isManager = vnfmManagerEndpoint != null;
if (managerCredentials != null) {
log.warn("Manager already registered.");
return gson.toJson(managerCredentials);
} else {
managerCredentials = new ManagerCredentials();
if (isManager) {
if (vnfmManagerEndpoint.isJsonPrimitive()) {
endpoint =
gson.fromJson(vnfmManagerEndpoint.getAsString(), VnfmManagerEndpoint.class);
} else {
endpoint = gson.fromJson(vnfmManagerEndpoint, VnfmManagerEndpoint.class);
}
}
}
String type =
isManager
? vnfmManagerEndpoint.getAsJsonObject().get("endpoint").getAsString()
: username;
String configurePermissions =
"^amq\\.gen.*|amq\\.default$|(" + type + ")|(nfvo." + type + ".actions)";
String writePermissions =
"^amq\\.gen.*|amq\\.default$|("
+ type
+ ")|(vnfm.nfvo.actions)|(vnfm.nfvo.actions.reply)|(nfvo."
+ type
+ ".actions)|(openbaton-exchange)";
String readPermissions =
"^amq\\.gen.*|amq\\.default$|(nfvo."
+ type
+ ".actions)|("
+ type
+ ")|(openbaton-exchange)";
createRabbitMqUser(
rabbitUsername,
rabbitPassword,
brokerIp,
managementPort,
username,
password,
vhost);
try {
setRabbitMqUserPermissions(
rabbitUsername,
rabbitPassword,
brokerIp,
managementPort,
username,
vhost,
configurePermissions,
writePermissions,
readPermissions);
} catch (Exception e) {
// remove the created RabbitMQ user again since the whole registration process failed
removeRabbitMqUserQuietly(
rabbitUsername, rabbitPassword, brokerIp, managementPort, username);
throw e;
}
managerCredentials.setRabbitUsername(username);
managerCredentials.setRabbitPassword(password);
managerCredentials = managerCredentialsRepository.save(managerCredentials);
if (endpoint != null) vnfmManagerEndpointRepository.save(endpoint);
log.info(
String.format(
"Registered a new manager: %s.", managerCredentials.getRabbitUsername()));
if (!isManager) {
this.refreshVims(username);
}
return gson.toJson(managerCredentials);
}
case "unregister":
case "deregister":
{
if (!body.has("username")) {
log.error("Could not process Json message. The 'username' property is missing.");
return null;
}
if (!body.has("password")) {
log.error("Could not process Json message. The 'password' property is missing.");
return null;
}
String username = body.get("username").getAsString();
ManagerCredentials managerCredentials =
managerCredentialsRepository.findFirstByRabbitUsername(username);
if (managerCredentials == null) {
log.error("Did not find manager with name " + body.get("username"));
return null;
}
if (body.get("password").getAsString().equals(managerCredentials.getRabbitPassword())) {
managerCredentialsRepository.delete(managerCredentials);
// if message comes from a vnfm, remove the endpoint
if (body.has("vnfmManagerEndpoint"))
vnfmRegister.unregister(
gson.fromJson(vnfmManagerEndpoint, VnfmManagerEndpoint.class));
removeRabbitMqUserQuietly(
rabbitUsername, rabbitPassword, brokerIp, managementPort, username);
} else {
log.warn(
"Some manager tried to unregister with a wrong password! or maybe i have an inconsistent DB...most probably... ;( ");
}
return null;
}
default:
return null;
}
} catch (Exception e) {
log.error("Exception while enabling manager or plugin.", e);
return null;
}
} | @RabbitListener( bindings = @QueueBinding( value = @Queue( value = RabbitConfiguration.QUEUE_NAME_MANAGER_REGISTER, durable = "true", autoDelete = "true"), exchange = @Exchange( value = RabbitConfiguration.EXCHANGE_NAME_OPENBATON, ignoreDeclarationExceptions = "true", type = RabbitConfiguration.EXCHANGE_TYPE_OPENBATON, durable = RabbitConfiguration.EXCHANGE_DURABLE_OPENBATON), key = RabbitConfiguration.QUEUE_NAME_MANAGER_REGISTER)) String function(String message) { try { JsonObject body = gson.fromJson(message, JsonObject.class); if (!body.has(STR)) { log.error(STR); return null; } JsonElement vnfmManagerEndpoint = body.get(STR); switch (body.get(STR).getAsString().toLowerCase()) { case STR: { if (!body.has("type")) { log.error(STR); return null; } String username = body.get("type").getAsString(); String password = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(16); ManagerCredentials managerCredentials = managerCredentialsRepository.findFirstByRabbitUsername(username); VnfmManagerEndpoint endpoint = null; boolean isManager = vnfmManagerEndpoint != null; if (managerCredentials != null) { log.warn(STR); return gson.toJson(managerCredentials); } else { managerCredentials = new ManagerCredentials(); if (isManager) { if (vnfmManagerEndpoint.isJsonPrimitive()) { endpoint = gson.fromJson(vnfmManagerEndpoint.getAsString(), VnfmManagerEndpoint.class); } else { endpoint = gson.fromJson(vnfmManagerEndpoint, VnfmManagerEndpoint.class); } } } String type = isManager ? vnfmManagerEndpoint.getAsJsonObject().get(STR).getAsString() : username; String configurePermissions = STR + type + STR + type + STR; String writePermissions = STR + type + STR + type + STR; String readPermissions = STR + type + STR + type + STR; createRabbitMqUser( rabbitUsername, rabbitPassword, brokerIp, managementPort, username, password, vhost); try { setRabbitMqUserPermissions( rabbitUsername, rabbitPassword, brokerIp, managementPort, username, vhost, configurePermissions, writePermissions, readPermissions); } catch (Exception e) { removeRabbitMqUserQuietly( rabbitUsername, rabbitPassword, brokerIp, managementPort, username); throw e; } managerCredentials.setRabbitUsername(username); managerCredentials.setRabbitPassword(password); managerCredentials = managerCredentialsRepository.save(managerCredentials); if (endpoint != null) vnfmManagerEndpointRepository.save(endpoint); log.info( String.format( STR, managerCredentials.getRabbitUsername())); if (!isManager) { this.refreshVims(username); } return gson.toJson(managerCredentials); } case STR: case STR: { if (!body.has(STR)) { log.error(STR); return null; } if (!body.has(STR)) { log.error(STR); return null; } String username = body.get(STR).getAsString(); ManagerCredentials managerCredentials = managerCredentialsRepository.findFirstByRabbitUsername(username); if (managerCredentials == null) { log.error(STR + body.get(STR)); return null; } if (body.get(STR).getAsString().equals(managerCredentials.getRabbitPassword())) { managerCredentialsRepository.delete(managerCredentials); if (body.has(STR)) vnfmRegister.unregister( gson.fromJson(vnfmManagerEndpoint, VnfmManagerEndpoint.class)); removeRabbitMqUserQuietly( rabbitUsername, rabbitPassword, brokerIp, managementPort, username); } else { log.warn( STR); } return null; } default: return null; } } catch (Exception e) { log.error(STR, e); return null; } } | /**
* Handles the registration requests of VNFMs and returns a ManagerCredential object from which
* the VNFMs can get the rabbitmq username and password.
*
* @param message
* @return
* @throws IOException
*/ | Handles the registration requests of VNFMs and returns a ManagerCredential object from which the VNFMs can get the rabbitmq username and password | enableManager | {
"repo_name": "openbaton/NFVO",
"path": "core/core-impl/src/main/java/org/openbaton/nfvo/core/api/ComponentManager.java",
"license": "apache-2.0",
"size": 18234
} | [
"com.google.gson.JsonElement",
"com.google.gson.JsonObject",
"org.openbaton.catalogue.nfvo.ManagerCredentials",
"org.openbaton.catalogue.nfvo.VnfmManagerEndpoint",
"org.openbaton.nfvo.common.configuration.RabbitConfiguration",
"org.openbaton.nfvo.common.utils.rabbit.RabbitManager",
"org.springframework.amqp.rabbit.annotation.Exchange",
"org.springframework.amqp.rabbit.annotation.Queue",
"org.springframework.amqp.rabbit.annotation.QueueBinding",
"org.springframework.amqp.rabbit.annotation.RabbitListener"
] | import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.openbaton.catalogue.nfvo.ManagerCredentials; import org.openbaton.catalogue.nfvo.VnfmManagerEndpoint; import org.openbaton.nfvo.common.configuration.RabbitConfiguration; import org.openbaton.nfvo.common.utils.rabbit.RabbitManager; import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; | import com.google.gson.*; import org.openbaton.catalogue.nfvo.*; import org.openbaton.nfvo.common.configuration.*; import org.openbaton.nfvo.common.utils.rabbit.*; import org.springframework.amqp.rabbit.annotation.*; | [
"com.google.gson",
"org.openbaton.catalogue",
"org.openbaton.nfvo",
"org.springframework.amqp"
] | com.google.gson; org.openbaton.catalogue; org.openbaton.nfvo; org.springframework.amqp; | 377,478 |
List<TaskEvent> getTaskEvents(long taskId, QueryFilter filter); | List<TaskEvent> getTaskEvents(long taskId, QueryFilter filter); | /**
* Gets a list of task events for given task
* @param taskId
* @param filter
* @return
*/ | Gets a list of task events for given task | getTaskEvents | {
"repo_name": "lukenjmcd/jbpm",
"path": "jbpm-services/jbpm-services-api/src/main/java/org/jbpm/services/api/RuntimeDataService.java",
"license": "apache-2.0",
"size": 23582
} | [
"java.util.List",
"org.kie.internal.query.QueryFilter",
"org.kie.internal.task.api.model.TaskEvent"
] | import java.util.List; import org.kie.internal.query.QueryFilter; import org.kie.internal.task.api.model.TaskEvent; | import java.util.*; import org.kie.internal.query.*; import org.kie.internal.task.api.model.*; | [
"java.util",
"org.kie.internal"
] | java.util; org.kie.internal; | 2,485,898 |
public DatasetListStatistics getStatistics(){
return stats;
}
| DatasetListStatistics function(){ return stats; } | /**
* Obtiene el objeto con las estadisticas
* @return MultiFileStatistics
*/ | Obtiene el objeto con las estadisticas | getStatistics | {
"repo_name": "iCarto/siga",
"path": "libRaster/src/org/gvsig/raster/dataset/MultiRasterDataset.java",
"license": "gpl-3.0",
"size": 49227
} | [
"org.gvsig.raster.dataset.properties.DatasetListStatistics"
] | import org.gvsig.raster.dataset.properties.DatasetListStatistics; | import org.gvsig.raster.dataset.properties.*; | [
"org.gvsig.raster"
] | org.gvsig.raster; | 2,878,788 |
public long getLastModified(HttpServletRequest request, Object handler) {
return -1;
}
| long function(HttpServletRequest request, Object handler) { return -1; } | /**
* This implementation always returns -1, as last-modified checks are not supported.
*/ | This implementation always returns -1, as last-modified checks are not supported | getLastModified | {
"repo_name": "codeApeFromChina/resource",
"path": "frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/web/servlet/mvc/throwaway/ThrowawayControllerHandlerAdapter.java",
"license": "unlicense",
"size": 4849
} | [
"javax.servlet.http.HttpServletRequest"
] | import javax.servlet.http.HttpServletRequest; | import javax.servlet.http.*; | [
"javax.servlet"
] | javax.servlet; | 1,965,674 |
@SuppressWarnings("unchecked")
private void assertClosedIndex(final String index, final boolean checkRoutingTable) throws IOException {
final Map<String, ?> state = entityAsMap(client().performRequest(new Request("GET", "/_cluster/state")));
final Map<String, ?> metadata = (Map<String, Object>) XContentMapValues.extractValue("metadata.indices." + index, state);
assertThat(metadata, notNullValue());
assertThat(metadata.get("state"), equalTo("close"));
final Map<String, ?> blocks = (Map<String, Object>) XContentMapValues.extractValue("blocks.indices." + index, state);
assertThat(blocks, notNullValue());
assertThat(blocks.containsKey(String.valueOf(MetadataIndexStateService.INDEX_CLOSED_BLOCK_ID)), is(true));
final Map<String, ?> settings = (Map<String, Object>) XContentMapValues.extractValue("settings", metadata);
assertThat(settings, notNullValue());
final int numberOfShards = Integer.parseInt((String) XContentMapValues.extractValue("index.number_of_shards", settings));
final int numberOfReplicas = Integer.parseInt((String) XContentMapValues.extractValue("index.number_of_replicas", settings));
final Map<String, ?> routingTable = (Map<String, Object>) XContentMapValues.extractValue("routing_table.indices." + index, state);
if (checkRoutingTable) {
assertThat(routingTable, notNullValue());
assertThat(Booleans.parseBoolean((String) XContentMapValues.extractValue("index.verified_before_close", settings)), is(true));
for (int i = 0; i < numberOfShards; i++) {
final Collection<Map<String, ?>> shards =
(Collection<Map<String, ?>>) XContentMapValues.extractValue("shards." + i, routingTable);
assertThat(shards, notNullValue());
assertThat(shards.size(), equalTo(numberOfReplicas + 1));
for (Map<String, ?> shard : shards) {
assertThat(XContentMapValues.extractValue("shard", shard), equalTo(i));
assertThat((String) XContentMapValues.extractValue("state", shard),
oneOf("STARTED", "RELOCATING", "RELOCATED"));
assertThat(XContentMapValues.extractValue("index", shard), equalTo(index));
}
}
} else {
assertThat(routingTable, nullValue());
assertThat(XContentMapValues.extractValue("index.verified_before_close", settings), nullValue());
}
} | @SuppressWarnings(STR) void function(final String index, final boolean checkRoutingTable) throws IOException { final Map<String, ?> state = entityAsMap(client().performRequest(new Request("GET", STR))); final Map<String, ?> metadata = (Map<String, Object>) XContentMapValues.extractValue(STR + index, state); assertThat(metadata, notNullValue()); assertThat(metadata.get("state"), equalTo("close")); final Map<String, ?> blocks = (Map<String, Object>) XContentMapValues.extractValue(STR + index, state); assertThat(blocks, notNullValue()); assertThat(blocks.containsKey(String.valueOf(MetadataIndexStateService.INDEX_CLOSED_BLOCK_ID)), is(true)); final Map<String, ?> settings = (Map<String, Object>) XContentMapValues.extractValue(STR, metadata); assertThat(settings, notNullValue()); final int numberOfShards = Integer.parseInt((String) XContentMapValues.extractValue(STR, settings)); final int numberOfReplicas = Integer.parseInt((String) XContentMapValues.extractValue(STR, settings)); final Map<String, ?> routingTable = (Map<String, Object>) XContentMapValues.extractValue(STR + index, state); if (checkRoutingTable) { assertThat(routingTable, notNullValue()); assertThat(Booleans.parseBoolean((String) XContentMapValues.extractValue(STR, settings)), is(true)); for (int i = 0; i < numberOfShards; i++) { final Collection<Map<String, ?>> shards = (Collection<Map<String, ?>>) XContentMapValues.extractValue(STR + i, routingTable); assertThat(shards, notNullValue()); assertThat(shards.size(), equalTo(numberOfReplicas + 1)); for (Map<String, ?> shard : shards) { assertThat(XContentMapValues.extractValue("shard", shard), equalTo(i)); assertThat((String) XContentMapValues.extractValue("state", shard), oneOf(STR, STR, STR)); assertThat(XContentMapValues.extractValue("index", shard), equalTo(index)); } } } else { assertThat(routingTable, nullValue()); assertThat(XContentMapValues.extractValue(STR, settings), nullValue()); } } | /**
* Asserts that an index is closed in the cluster state. If `checkRoutingTable` is true, it also asserts
* that the index has started shards.
*/ | Asserts that an index is closed in the cluster state. If `checkRoutingTable` is true, it also asserts that the index has started shards | assertClosedIndex | {
"repo_name": "gingerwizard/elasticsearch",
"path": "qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/RecoveryIT.java",
"license": "apache-2.0",
"size": 39567
} | [
"java.io.IOException",
"java.util.Collection",
"java.util.Map",
"org.elasticsearch.client.Request",
"org.elasticsearch.cluster.metadata.MetadataIndexStateService",
"org.elasticsearch.common.Booleans",
"org.elasticsearch.common.xcontent.support.XContentMapValues",
"org.hamcrest.Matchers"
] | import java.io.IOException; import java.util.Collection; import java.util.Map; import org.elasticsearch.client.Request; import org.elasticsearch.cluster.metadata.MetadataIndexStateService; import org.elasticsearch.common.Booleans; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.hamcrest.Matchers; | import java.io.*; import java.util.*; import org.elasticsearch.client.*; import org.elasticsearch.cluster.metadata.*; import org.elasticsearch.common.*; import org.elasticsearch.common.xcontent.support.*; import org.hamcrest.*; | [
"java.io",
"java.util",
"org.elasticsearch.client",
"org.elasticsearch.cluster",
"org.elasticsearch.common",
"org.hamcrest"
] | java.io; java.util; org.elasticsearch.client; org.elasticsearch.cluster; org.elasticsearch.common; org.hamcrest; | 2,260,094 |
private String buildXMLResultString(List<RequestData> lst){
String output=null;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("report");
doc.appendChild(rootElement);
// report elements
lst.stream().forEach( d -> {
Element request = doc.createElement("request");
rootElement.appendChild(request);
Element id = doc.createElement("id");
id.setTextContent(d.id);
request.appendChild(id);
Element flag = doc.createElement("flag");
flag.setTextContent(d.flag.toString());
request.appendChild(flag);
});
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
output = writer.getBuffer().toString().replaceAll("\n|\r", "");
} catch (ParserConfigurationException | TransformerException pce) {
pce.printStackTrace(System.err);
}
return output;
} | String function(List<RequestData> lst){ String output=null; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(STR); doc.appendChild(rootElement); lst.stream().forEach( d -> { Element request = doc.createElement(STR); rootElement.appendChild(request); Element id = doc.createElement("id"); id.setTextContent(d.id); request.appendChild(id); Element flag = doc.createElement("flag"); flag.setTextContent(d.flag.toString()); request.appendChild(flag); }); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); output = writer.getBuffer().toString().replaceAll(STR, ""); } catch (ParserConfigurationException TransformerException pce) { pce.printStackTrace(System.err); } return output; } | /**
* Formats a request results as an XML String.
* @param lst The list of results to be formatted as XML.
* @return The XML String.
*/ | Formats a request results as an XML String | buildXMLResultString | {
"repo_name": "jcarm010/Link",
"path": "src/link/Request.java",
"license": "apache-2.0",
"size": 9182
} | [
"java.io.StringWriter",
"java.util.List",
"javax.xml.parsers.DocumentBuilder",
"javax.xml.parsers.DocumentBuilderFactory",
"javax.xml.parsers.ParserConfigurationException",
"javax.xml.transform.OutputKeys",
"javax.xml.transform.Transformer",
"javax.xml.transform.TransformerException",
"javax.xml.transform.TransformerFactory",
"javax.xml.transform.dom.DOMSource",
"javax.xml.transform.stream.StreamResult",
"org.w3c.dom.Document",
"org.w3c.dom.Element"
] | import java.io.StringWriter; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; | import java.io.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; | [
"java.io",
"java.util",
"javax.xml",
"org.w3c.dom"
] | java.io; java.util; javax.xml; org.w3c.dom; | 322,905 |
private static List<Class<?>> convertArgumentClassesToPrimitives( List<Class<?>> arguments ) {
List<Class<?>> result = new ArrayList<Class<?>>(arguments.size());
for (Class<?> clazz : arguments) {
if ( clazz == Boolean.class ) clazz = Boolean.TYPE;
else if ( clazz == Character.class ) clazz = Character.TYPE;
else if ( clazz == Byte.class ) clazz = Byte.TYPE;
else if ( clazz == Short.class ) clazz = Short.TYPE;
else if ( clazz == Integer.class ) clazz = Integer.TYPE;
else if ( clazz == Long.class ) clazz = Long.TYPE;
else if ( clazz == Float.class ) clazz = Float.TYPE;
else if ( clazz == Double.class ) clazz = Double.TYPE;
else if ( clazz == Void.class ) clazz = Void.TYPE;
result.add( clazz );
}
return result;
} | static List<Class<?>> function( List<Class<?>> arguments ) { List<Class<?>> result = new ArrayList<Class<?>>(arguments.size()); for (Class<?> clazz : arguments) { if ( clazz == Boolean.class ) clazz = Boolean.TYPE; else if ( clazz == Character.class ) clazz = Character.TYPE; else if ( clazz == Byte.class ) clazz = Byte.TYPE; else if ( clazz == Short.class ) clazz = Short.TYPE; else if ( clazz == Integer.class ) clazz = Integer.TYPE; else if ( clazz == Long.class ) clazz = Long.TYPE; else if ( clazz == Float.class ) clazz = Float.TYPE; else if ( clazz == Double.class ) clazz = Double.TYPE; else if ( clazz == Void.class ) clazz = Void.TYPE; result.add( clazz ); } return result; } | /**
* Convert any argument classes to primitives.
* @param arguments the list of argument classes.
* @return the list of Class instances in which any classes that could be represented
* by primitives (e.g., Boolean) were replaced with the primitive classes (e.g., Boolean.TYPE).
*/ | Convert any argument classes to primitives | convertArgumentClassesToPrimitives | {
"repo_name": "jagazee/teiid-8.7",
"path": "common-core/src/main/java/org/teiid/core/util/ReflectionHelper.java",
"license": "lgpl-2.1",
"size": 15296
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,002,738 |
public Collection<Callsite> getAllCallsites() {
return callsitesByNode.values();
} | Collection<Callsite> function() { return callsitesByNode.values(); } | /**
* Returns a collection of all callsites in the call graph.
*/ | Returns a collection of all callsites in the call graph | getAllCallsites | {
"repo_name": "110035/kissy",
"path": "tools/module-compiler/src/com/google/javascript/jscomp/CallGraph.java",
"license": "mit",
"size": 26034
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 1,125,438 |
public PropertyDescriptor[] getPropertyDescriptors()
{
MWC.Utilities.Errors.Trace
.trace("Possible problem collating properties for:" + getName() + " (" + getData().getClass() + ")", false);
return super.getPropertyDescriptors();
} | PropertyDescriptor[] function() { MWC.Utilities.Errors.Trace .trace(STR + getName() + STR + getData().getClass() + ")", false); return super.getPropertyDescriptors(); } | /**
* Deny knowledge of properties. You can override this if you wish to
* provide explicit property info.
*/ | Deny knowledge of properties. You can override this if you wish to provide explicit property info | getPropertyDescriptors | {
"repo_name": "theanuradha/debrief",
"path": "org.mwc.cmap.legacy/src/MWC/GUI/Editable.java",
"license": "epl-1.0",
"size": 37860
} | [
"java.beans.PropertyDescriptor"
] | import java.beans.PropertyDescriptor; | import java.beans.*; | [
"java.beans"
] | java.beans; | 2,897,747 |
public alluxio.grpc.GetFileInfoPResponse getFileInfo(alluxio.grpc.GetFileInfoPRequest request) {
return blockingUnaryCall(
getChannel(), getGetFileInfoMethod(), getCallOptions(), request);
} | alluxio.grpc.GetFileInfoPResponse function(alluxio.grpc.GetFileInfoPRequest request) { return blockingUnaryCall( getChannel(), getGetFileInfoMethod(), getCallOptions(), request); } | /**
* <pre>
* Returns the file information for a file or directory identified by the given file id.
* </pre>
*/ | <code> Returns the file information for a file or directory identified by the given file id. </code> | getFileInfo | {
"repo_name": "madanadit/alluxio",
"path": "core/transport/src/main/java/alluxio/grpc/FileSystemMasterWorkerServiceGrpc.java",
"license": "apache-2.0",
"size": 25155
} | [
"io.grpc.stub.ClientCalls"
] | import io.grpc.stub.ClientCalls; | import io.grpc.stub.*; | [
"io.grpc.stub"
] | io.grpc.stub; | 769,356 |
@SuppressWarnings("unchecked")
private void handleMap(String documentId, JsonObjectDescriptorHelper objectDescriptorHelper, DocumentNode node,
String attributeName, Object attributeValue, int index) {
String type = buildNodeLabel(attributeName, (Map<String, Object>) attributeValue, objectDescriptorHelper);
DocumentNode childNode = transform(documentId, type, (Map<String, Object>) attributeValue, objectDescriptorHelper, index);
childNode.setParentPropertyName(attributeName);
node.addOutgoingRelation(childNode);
} | @SuppressWarnings(STR) void function(String documentId, JsonObjectDescriptorHelper objectDescriptorHelper, DocumentNode node, String attributeName, Object attributeValue, int index) { String type = buildNodeLabel(attributeName, (Map<String, Object>) attributeValue, objectDescriptorHelper); DocumentNode childNode = transform(documentId, type, (Map<String, Object>) attributeValue, objectDescriptorHelper, index); childNode.setParentPropertyName(attributeName); node.addOutgoingRelation(childNode); } | /**
* The method handleMap.
*
* @param documentId
* the document ID
* @param objectDescriptorHelper
* the descriptor helper
* @param node
* the current node
* @param attributeName
* the attribute name
* @param attributeValue
* the attribute value
* @param index the index
*/ | The method handleMap | handleMap | {
"repo_name": "larusba/neo4j-json-loader",
"path": "src/main/java/it/larusba/integration/neo4j/jsonloader/transformer/DomainDrivenJsonTransformer.java",
"license": "apache-2.0",
"size": 8862
} | [
"it.larusba.integration.neo4j.jsonloader.bean.DocumentNode",
"it.larusba.integration.neo4j.jsonloader.util.JsonObjectDescriptorHelper",
"java.util.Map"
] | import it.larusba.integration.neo4j.jsonloader.bean.DocumentNode; import it.larusba.integration.neo4j.jsonloader.util.JsonObjectDescriptorHelper; import java.util.Map; | import it.larusba.integration.neo4j.jsonloader.bean.*; import it.larusba.integration.neo4j.jsonloader.util.*; import java.util.*; | [
"it.larusba.integration",
"java.util"
] | it.larusba.integration; java.util; | 1,595,364 |
public GetEnrollmentOptions type(List<EnrollmentType> enrollmentTypes) {
addEnumList("type[]", enrollmentTypes);
return this;
} | GetEnrollmentOptions function(List<EnrollmentType> enrollmentTypes) { addEnumList(STR, enrollmentTypes); return this; } | /**
* Specify enrollment types to filter the returned list by (student, teacher, TA, designer, observer)
* This option is ignored if a role is specified.
* @param enrollmentTypes All the enrollment types you want to retrieve
* @return This object to allow adding more options
*/ | Specify enrollment types to filter the returned list by (student, teacher, TA, designer, observer) This option is ignored if a role is specified | type | {
"repo_name": "kstateome/canvas-api",
"path": "src/main/java/edu/ksu/canvas/requestOptions/GetEnrollmentOptions.java",
"license": "lgpl-3.0",
"size": 6064
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,655,639 |
public VirtualNetworkGatewayConnectionType connectionType() {
return this.innerProperties() == null ? null : this.innerProperties().connectionType();
} | VirtualNetworkGatewayConnectionType function() { return this.innerProperties() == null ? null : this.innerProperties().connectionType(); } | /**
* Get the connectionType property: Gateway connection type.
*
* @return the connectionType value.
*/ | Get the connectionType property: Gateway connection type | connectionType | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/VirtualNetworkGatewayConnectionListEntityInner.java",
"license": "mit",
"size": 20243
} | [
"com.azure.resourcemanager.network.models.VirtualNetworkGatewayConnectionType"
] | import com.azure.resourcemanager.network.models.VirtualNetworkGatewayConnectionType; | import com.azure.resourcemanager.network.models.*; | [
"com.azure.resourcemanager"
] | com.azure.resourcemanager; | 630,491 |
public ServiceFuture<ProbeInner> getAsync(String resourceGroupName, String loadBalancerName, String probeName, final ServiceCallback<ProbeInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, loadBalancerName, probeName), serviceCallback);
} | ServiceFuture<ProbeInner> function(String resourceGroupName, String loadBalancerName, String probeName, final ServiceCallback<ProbeInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, loadBalancerName, probeName), serviceCallback); } | /**
* Gets load balancer probe.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param probeName The name of the probe.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/ | Gets load balancer probe | getAsync | {
"repo_name": "navalev/azure-sdk-for-java",
"path": "sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/implementation/LoadBalancerProbesInner.java",
"license": "mit",
"size": 20824
} | [
"com.microsoft.rest.ServiceCallback",
"com.microsoft.rest.ServiceFuture"
] | import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
] | com.microsoft.rest; | 4,236 |
public static AbstractFileSystem createFileSystem(URI uri, Configuration conf)
throws UnsupportedFileSystemException {
final String fsImplConf = String.format("fs.AbstractFileSystem.%s.impl",
uri.getScheme());
Class<?> clazz = conf.getClass(fsImplConf, null);
if (clazz == null) {
throw new UnsupportedFileSystemException(String.format(
"%s=null: %s: %s",
fsImplConf, NO_ABSTRACT_FS_ERROR, uri.getScheme()));
}
return (AbstractFileSystem) newInstance(clazz, uri, conf);
} | static AbstractFileSystem function(URI uri, Configuration conf) throws UnsupportedFileSystemException { final String fsImplConf = String.format(STR, uri.getScheme()); Class<?> clazz = conf.getClass(fsImplConf, null); if (clazz == null) { throw new UnsupportedFileSystemException(String.format( STR, fsImplConf, NO_ABSTRACT_FS_ERROR, uri.getScheme())); } return (AbstractFileSystem) newInstance(clazz, uri, conf); } | /**
* Create a file system instance for the specified uri using the conf. The
* conf is used to find the class name that implements the file system. The
* conf is also passed to the file system for its configuration.
*
* @param uri URI of the file system
* @param conf Configuration for the file system
*
* @return Returns the file system for the given URI
*
* @throws UnsupportedFileSystemException file system for <code>uri</code> is
* not found
*/ | Create a file system instance for the specified uri using the conf. The conf is used to find the class name that implements the file system. The conf is also passed to the file system for its configuration | createFileSystem | {
"repo_name": "plusplusjiajia/hadoop",
"path": "hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/AbstractFileSystem.java",
"license": "apache-2.0",
"size": 50364
} | [
"org.apache.hadoop.conf.Configuration"
] | import org.apache.hadoop.conf.Configuration; | import org.apache.hadoop.conf.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 1,720,968 |
public static <E> Iterator<E> concat(Iterator<? extends Iterator<? extends E>> iterators)
{
return new ConcatIterator<E>(iterators);
} | static <E> Iterator<E> function(Iterator<? extends Iterator<? extends E>> iterators) { return new ConcatIterator<E>(iterators); } | /**
* Concatenates all the given {@code Iterator}s into a single one. The
* source {@code Iterator}s aren't polled until necessary. The returned
* {@code Iterator} supports {@link Iterator#remove()} when the
* corresponding input {@code Iterator} supports it.
*
* @param <E> the type of the returned {@code Iterator}'s elements.
* @param iterators the {@code Iterator}s to concatenate.
*
* @return the concatenated {@code Iterator}.
*
* @throws NullPointerException if {@code iterators} is {@code null} or
* if it contains a {@code null} reference.
*/ | Concatenates all the given Iterators into a single one. The source Iterators aren't polled until necessary. The returned Iterator supports <code>Iterator#remove()</code> when the corresponding input Iterator supports it | concat | {
"repo_name": "kocakosm/pitaya",
"path": "src/org/kocakosm/pitaya/collection/Iterators.java",
"license": "lgpl-3.0",
"size": 12880
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 2,040,194 |
public Future<List<generated.classic.reactive.dataobject.tables.pojos.Something>> findManyBySomejsonobject(Collection<JsonObject> values, int limit) {
return findManyByCondition(Something.SOMETHING.SOMEJSONOBJECT.in(values),limit);
} | Future<List<generated.classic.reactive.dataobject.tables.pojos.Something>> function(Collection<JsonObject> values, int limit) { return findManyByCondition(Something.SOMETHING.SOMEJSONOBJECT.in(values),limit); } | /**
* Find records that have <code>someJsonObject IN (values)</code>
* asynchronously limited by the given limit
*/ | Find records that have <code>someJsonObject IN (values)</code> asynchronously limited by the given limit | findManyBySomejsonobject | {
"repo_name": "jklingsporn/vertx-jooq",
"path": "vertx-jooq-generate/src/test/java/generated/classic/reactive/dataobject/tables/daos/SomethingDao.java",
"license": "mit",
"size": 15579
} | [
"io.vertx.core.Future",
"io.vertx.core.json.JsonObject",
"java.util.Collection",
"java.util.List"
] | import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import java.util.Collection; import java.util.List; | import io.vertx.core.*; import io.vertx.core.json.*; import java.util.*; | [
"io.vertx.core",
"java.util"
] | io.vertx.core; java.util; | 1,164,563 |
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
String view = getFormView();
if (Context.isAuthenticated()) {
EncounterType encounterType = (EncounterType) obj;
EncounterService es = Context.getEncounterService();
if (request.getParameter("save") != null) {
es.saveEncounterType(encounterType);
view = getSuccessView();
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.saved");
}
// if the user is retiring out the EncounterType
else if (request.getParameter("retire") != null) {
String retireReason = request.getParameter("retireReason");
if (encounterType.getEncounterTypeId() != null && !(StringUtils.hasText(retireReason))) {
errors.reject("retireReason", "general.retiredReason.empty");
return showForm(request, response, errors);
}
es.retireEncounterType(encounterType, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.retiredSuccessfully");
view = getSuccessView();
}
// if the user is unretiring the EncounterType
else if (request.getParameter("unretire") != null) {
es.unretireEncounterType(encounterType);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.unretiredSuccessfully");
view = getSuccessView();
}
// if the user is purging the encounterType
else if (request.getParameter("purge") != null) {
try {
es.purgeEncounterType(encounterType);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.purgedSuccessfully");
view = getSuccessView();
}
catch (DataIntegrityViolationException e) {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
view = "encounterType.form?encounterTypeId=" + encounterType.getEncounterTypeId();
}
catch (APIException e) {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.general: " + e.getLocalizedMessage());
view = "encounterType.form?encounterTypeId=" + encounterType.getEncounterTypeId();
}
}
}
return new ModelAndView(new RedirectView(view));
}
| ModelAndView function(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (Context.isAuthenticated()) { EncounterType encounterType = (EncounterType) obj; EncounterService es = Context.getEncounterService(); if (request.getParameter("save") != null) { es.saveEncounterType(encounterType); view = getSuccessView(); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, STR); } else if (request.getParameter(STR) != null) { String retireReason = request.getParameter(STR); if (encounterType.getEncounterTypeId() != null && !(StringUtils.hasText(retireReason))) { errors.reject(STR, STR); return showForm(request, response, errors); } es.retireEncounterType(encounterType, retireReason); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, STR); view = getSuccessView(); } else if (request.getParameter(STR) != null) { es.unretireEncounterType(encounterType); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, STR); view = getSuccessView(); } else if (request.getParameter("purge") != null) { try { es.purgeEncounterType(encounterType); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, STR); view = getSuccessView(); } catch (DataIntegrityViolationException e) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, STR); view = STR + encounterType.getEncounterTypeId(); } catch (APIException e) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, STR + e.getLocalizedMessage()); view = STR + encounterType.getEncounterTypeId(); } } } return new ModelAndView(new RedirectView(view)); } | /**
* The onSubmit function receives the form/command object that was modified by the input form
* and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, java.lang.Object,
* org.springframework.validation.BindException)
*/ | The onSubmit function receives the form/command object that was modified by the input form and saves it to the db | onSubmit | {
"repo_name": "Bhamni/openmrs-core",
"path": "web/src/main/java/org/openmrs/web/controller/encounter/EncounterTypeFormController.java",
"license": "mpl-2.0",
"size": 6872
} | [
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpServletResponse",
"javax.servlet.http.HttpSession",
"org.openmrs.EncounterType",
"org.openmrs.api.APIException",
"org.openmrs.api.EncounterService",
"org.openmrs.api.context.Context",
"org.openmrs.web.WebConstants",
"org.springframework.dao.DataIntegrityViolationException",
"org.springframework.util.StringUtils",
"org.springframework.validation.BindException",
"org.springframework.web.servlet.ModelAndView",
"org.springframework.web.servlet.view.RedirectView"
] | import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.openmrs.EncounterType; import org.openmrs.api.APIException; import org.openmrs.api.EncounterService; import org.openmrs.api.context.Context; import org.openmrs.web.WebConstants; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.util.StringUtils; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; | import javax.servlet.http.*; import org.openmrs.*; import org.openmrs.api.*; import org.openmrs.api.context.*; import org.openmrs.web.*; import org.springframework.dao.*; import org.springframework.util.*; import org.springframework.validation.*; import org.springframework.web.servlet.*; import org.springframework.web.servlet.view.*; | [
"javax.servlet",
"org.openmrs",
"org.openmrs.api",
"org.openmrs.web",
"org.springframework.dao",
"org.springframework.util",
"org.springframework.validation",
"org.springframework.web"
] | javax.servlet; org.openmrs; org.openmrs.api; org.openmrs.web; org.springframework.dao; org.springframework.util; org.springframework.validation; org.springframework.web; | 722,443 |
public void createWorkerSession(org.tensorflow.distruntime.CreateWorkerSessionRequest request,
io.grpc.stub.StreamObserver<org.tensorflow.distruntime.CreateWorkerSessionResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_CREATE_WORKER_SESSION, responseObserver);
} | void function(org.tensorflow.distruntime.CreateWorkerSessionRequest request, io.grpc.stub.StreamObserver<org.tensorflow.distruntime.CreateWorkerSessionResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_CREATE_WORKER_SESSION, responseObserver); } | /**
* <pre>
* See worker.proto for details.
* </pre>
*/ | <code> See worker.proto for details. </code> | createWorkerSession | {
"repo_name": "nubbel/swift-tensorflow",
"path": "JavaGenerated/org/tensorflow/distruntime/WorkerServiceGrpc.java",
"license": "mit",
"size": 35911
} | [
"io.grpc.stub.ServerCalls"
] | import io.grpc.stub.ServerCalls; | import io.grpc.stub.*; | [
"io.grpc.stub"
] | io.grpc.stub; | 287,783 |
@Operation(desc = "Retry all messages on a DLQ to their respective original queues", impact = MBeanOperationInfo.ACTION)
int retryMessages() throws Exception; | @Operation(desc = STR, impact = MBeanOperationInfo.ACTION) int retryMessages() throws Exception; | /**
* Retries all messages on a DLQ to their respective original queues.
* This is appropriate on dead messages on Dead letter queues only.
*
* @return the number of retried messages.
* @throws Exception
*/ | Retries all messages on a DLQ to their respective original queues. This is appropriate on dead messages on Dead letter queues only | retryMessages | {
"repo_name": "d0k1/activemq-artemis",
"path": "artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/QueueControl.java",
"license": "apache-2.0",
"size": 22193
} | [
"javax.management.MBeanOperationInfo"
] | import javax.management.MBeanOperationInfo; | import javax.management.*; | [
"javax.management"
] | javax.management; | 2,848,357 |
public SessionManagementConfigurer<H> invalidSessionStrategy(
InvalidSessionStrategy invalidSessionStrategy) {
Assert.notNull(invalidSessionStrategy, "invalidSessionStrategy");
this.invalidSessionStrategy = invalidSessionStrategy;
return this;
} | SessionManagementConfigurer<H> function( InvalidSessionStrategy invalidSessionStrategy) { Assert.notNull(invalidSessionStrategy, STR); this.invalidSessionStrategy = invalidSessionStrategy; return this; } | /**
* Setting this attribute will inject the provided invalidSessionStrategy into the
* {@link SessionManagementFilter}. When an invalid session ID is submitted, the
* strategy will be invoked, redirecting to the configured URL.
* @param invalidSessionStrategy the strategy to use when an invalid session ID is
* submitted.
* @return the {@link SessionManagementConfigurer} for further customization
*/ | Setting this attribute will inject the provided invalidSessionStrategy into the <code>SessionManagementFilter</code>. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL | invalidSessionStrategy | {
"repo_name": "kazuki43zoo/spring-security",
"path": "config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java",
"license": "apache-2.0",
"size": 26911
} | [
"org.springframework.security.web.session.InvalidSessionStrategy",
"org.springframework.util.Assert"
] | import org.springframework.security.web.session.InvalidSessionStrategy; import org.springframework.util.Assert; | import org.springframework.security.web.session.*; import org.springframework.util.*; | [
"org.springframework.security",
"org.springframework.util"
] | org.springframework.security; org.springframework.util; | 205,229 |
EAttribute getBlockElement_ScriptType(); | EAttribute getBlockElement_ScriptType(); | /**
* Returns the meta object for the attribute '{@link org.roboid.studio.contentscomposer.BlockElement#getScriptType <em>Script Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Script Type</em>'.
* @see org.roboid.studio.contentscomposer.BlockElement#getScriptType()
* @see #getBlockElement()
* @generated
*/ | Returns the meta object for the attribute '<code>org.roboid.studio.contentscomposer.BlockElement#getScriptType Script Type</code>'. | getBlockElement_ScriptType | {
"repo_name": "roboidstudio/embedded",
"path": "org.roboid.studio.contentscomposer.model/src/org/roboid/studio/contentscomposer/ContentsComposerPackage.java",
"license": "lgpl-2.1",
"size": 131603
} | [
"org.eclipse.emf.ecore.EAttribute"
] | import org.eclipse.emf.ecore.EAttribute; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 74,399 |
public Calendar getCreateTime() {
return createTime;
} | Calendar function() { return createTime; } | /**
* Get the value of createTime.
*
* @return the value of createTime.
*/ | Get the value of createTime | getCreateTime | {
"repo_name": "AurionProject/Aurion",
"path": "Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/entity/CertPolicy.java",
"license": "bsd-3-clause",
"size": 5022
} | [
"java.util.Calendar"
] | import java.util.Calendar; | import java.util.*; | [
"java.util"
] | java.util; | 922,797 |
@Test
public void testServerTime() throws Exception {
Assert.assertNotNull(iConfig.getServerTime());
} | void function() throws Exception { Assert.assertNotNull(iConfig.getServerTime()); } | /**
* Tests the <code>getServerTime</code> method. Access the method as a non
* administrator.
*
* @throws Exception
* Thrown if an error occurred.
*/ | Tests the <code>getServerTime</code> method. Access the method as a non administrator | testServerTime | {
"repo_name": "simleo/openmicroscopy",
"path": "components/tools/OmeroJava/test/integration/ConfigurationServiceTest.java",
"license": "gpl-2.0",
"size": 11475
} | [
"org.testng.Assert"
] | import org.testng.Assert; | import org.testng.*; | [
"org.testng"
] | org.testng; | 2,276,836 |
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
Log.d(TAG, "cancelWork - cancelled work for Image No" + bitmapWorkerTask.posOfImage);
}
}
} | static void function(ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { bitmapWorkerTask.cancel(true); if (BuildConfig.DEBUG) { Log.d(TAG, STR + bitmapWorkerTask.posOfImage); } } } | /**
* Cancels any pending work attached to the provided ImageView.
* @param imageView
*/ | Cancels any pending work attached to the provided ImageView | cancelWork | {
"repo_name": "hahnjas/DumbDisplayDriver",
"path": "Application/src/main/java/se/kth/prodreal/dumbdevices/dumbdisplayhelper/util/ImageWorkerLocal.java",
"license": "apache-2.0",
"size": 17551
} | [
"android.widget.ImageView",
"se.kth.prodreal.dumbdevices.dumbdisplayhelper.BuildConfig",
"se.kth.prodreal.dumbdevices.dumbdisplayhelper.Logger"
] | import android.widget.ImageView; import se.kth.prodreal.dumbdevices.dumbdisplayhelper.BuildConfig; import se.kth.prodreal.dumbdevices.dumbdisplayhelper.Logger; | import android.widget.*; import se.kth.prodreal.dumbdevices.dumbdisplayhelper.*; | [
"android.widget",
"se.kth.prodreal"
] | android.widget; se.kth.prodreal; | 188,784 |
public synchronized void setBase(File jmxBase) {
if (jmxBase == null) {
throw new IllegalArgumentException("jmxBase must not be null");
}
checkForOpenFiles();
base = jmxBase;
log.info("Set new base='"+base+"'");
} | synchronized void function(File jmxBase) { if (jmxBase == null) { throw new IllegalArgumentException(STR); } checkForOpenFiles(); base = jmxBase; log.info(STR+base+"'"); } | /**
* Sets the current base directory for relative file names.
*
* @param jmxBase the path of the script file base directory, cannot be null
* @throws IllegalStateException if files are still open
* @throws IllegalArgumentException if {@code basepath} is null
*/ | Sets the current base directory for relative file names | setBase | {
"repo_name": "DoctorQ/jmeter",
"path": "src/core/org/apache/jmeter/services/FileServer.java",
"license": "apache-2.0",
"size": 22886
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 2,718,779 |
private void onChunkOperationComplete(GetChunk chunk) {
if (chunk.getChunkException() != null) {
// if operation callback was already called, then this exception will have to be notified as part of the
// read callback.
setOperationException(chunk.getChunkException());
}
if (chunk == firstChunk) {
if (operationCallbackInvoked.compareAndSet(false, true)) {
Exception e = getOperationException();
if (options.getChunkIdsOnly) {
// If this is an operation just to get the chunk ids, then these ids will be returned as part of the
// result callback and no more chunks will be fetched, so mark the operation as complete to let the
// GetManager remove this operation.
operationCompleted = true;
List<StoreKey> chunkIds = e == null && compositeBlobInfo != null ? compositeBlobInfo.getKeys() : null;
operationResult = new GetBlobResultInternal(null, chunkIds);
} else {
// Complete the operation from the caller's perspective, so that the caller can start reading from the
// channel if there is no exception. The operation will not be marked as complete internally as subsequent
// chunk retrievals and channel writes will need to happen and for that, this operation needs the GetManager to
// poll it periodically. If any exception is encountered while processing subsequent chunks, those will be
// notified during the channel read.
long timeElapsed = time.milliseconds() - submissionTimeMs;
routerMetrics.getBlobOperationLatencyMs.update(timeElapsed);
if (e == null) {
blobDataChannel = new BlobDataReadableStreamChannel();
operationResult = new GetBlobResultInternal(new GetBlobResult(blobInfo, blobDataChannel), null);
} else {
blobDataChannel = null;
operationResult = null;
routerMetrics.onGetBlobError(e, options);
}
}
NonBlockingRouter.completeOperation(null, getOperationCallback, operationResult, e);
}
}
chunk.postCompletionCleanup();
if (blobDataChannel != null) {
blobDataChannel.maybeWriteToChannel();
}
} | void function(GetChunk chunk) { if (chunk.getChunkException() != null) { setOperationException(chunk.getChunkException()); } if (chunk == firstChunk) { if (operationCallbackInvoked.compareAndSet(false, true)) { Exception e = getOperationException(); if (options.getChunkIdsOnly) { operationCompleted = true; List<StoreKey> chunkIds = e == null && compositeBlobInfo != null ? compositeBlobInfo.getKeys() : null; operationResult = new GetBlobResultInternal(null, chunkIds); } else { long timeElapsed = time.milliseconds() - submissionTimeMs; routerMetrics.getBlobOperationLatencyMs.update(timeElapsed); if (e == null) { blobDataChannel = new BlobDataReadableStreamChannel(); operationResult = new GetBlobResultInternal(new GetBlobResult(blobInfo, blobDataChannel), null); } else { blobDataChannel = null; operationResult = null; routerMetrics.onGetBlobError(e, options); } } NonBlockingRouter.completeOperation(null, getOperationCallback, operationResult, e); } } chunk.postCompletionCleanup(); if (blobDataChannel != null) { blobDataChannel.maybeWriteToChannel(); } } | /**
* Do all that needs to be done (cleanup, notification, etc.) on chunk completion and mark the state of the chunk
* appropriately.
* @param chunk the chunk that has completed.
*/ | Do all that needs to be done (cleanup, notification, etc.) on chunk completion and mark the state of the chunk appropriately | onChunkOperationComplete | {
"repo_name": "nsivabalan/ambry",
"path": "ambry-router/src/main/java/com.github.ambry.router/GetBlobOperation.java",
"license": "apache-2.0",
"size": 45897
} | [
"com.github.ambry.store.StoreKey",
"java.util.List"
] | import com.github.ambry.store.StoreKey; import java.util.List; | import com.github.ambry.store.*; import java.util.*; | [
"com.github.ambry",
"java.util"
] | com.github.ambry; java.util; | 2,458,616 |
protected String getDebitCreditOption(Map fieldValues) {
// truncate the non-property filed
String debitCreditOption = (String) fieldValues.get(Constant.DEBIT_CREDIT_OPTION);
fieldValues.remove(Constant.DEBIT_CREDIT_OPTION);
return debitCreditOption;
} | String function(Map fieldValues) { String debitCreditOption = (String) fieldValues.get(Constant.DEBIT_CREDIT_OPTION); fieldValues.remove(Constant.DEBIT_CREDIT_OPTION); return debitCreditOption; } | /**
* This method tests if the user selects to see the Debit/Credit entries
*
* @param fieldValues the map containing the search fields and values
* @return the value of pending entry option
*/ | This method tests if the user selects to see the Debit/Credit entries | getDebitCreditOption | {
"repo_name": "quikkian-ua-devops/will-financials",
"path": "kfs-core/src/main/java/org/kuali/kfs/gl/businessobject/lookup/AbstractGeneralLedgerLookupableHelperServiceImpl.java",
"license": "agpl-3.0",
"size": 14155
} | [
"java.util.Map",
"org.kuali.kfs.gl.Constant"
] | import java.util.Map; import org.kuali.kfs.gl.Constant; | import java.util.*; import org.kuali.kfs.gl.*; | [
"java.util",
"org.kuali.kfs"
] | java.util; org.kuali.kfs; | 2,867,300 |
public static Object noBlank(Object... items) {
if (items.length < 2)
throw new DbProException("noBlank method need at least 2 args");
for (int i = 0; i <= items.length - 1; i++)
if (StrUtils.isBlankObject(items[i]))
return "";
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= items.length - 1; i++)
sb.append(items[i]);
return new Object[] {items[0], par(sb.toString())};
}
| static Object function(Object... items) { if (items.length < 2) throw new DbProException(STR); for (int i = 0; i <= items.length - 1; i++) if (StrUtils.isBlankObject(items[i])) return ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i <= items.length - 1; i++) sb.append(items[i]); return new Object[] {items[0], par(sb.toString())}; } | /**
* If no any param is null, then add all items in SQL<br/>
* Example: query("select * from a where 1=1",noNull("and name like
* ?","%",name,"%"));
*/ | If no any param is null, then add all items in SQL Example: query("select * from a where 1=1",noNull("and name like ?","%",name,"%")) | noBlank | {
"repo_name": "drinkjava2/jSQLBox",
"path": "core/src/main/java/com/github/drinkjava2/jdbpro/JDBC.java",
"license": "apache-2.0",
"size": 9878
} | [
"com.github.drinkjava2.jdialects.StrUtils"
] | import com.github.drinkjava2.jdialects.StrUtils; | import com.github.drinkjava2.jdialects.*; | [
"com.github.drinkjava2"
] | com.github.drinkjava2; | 253,110 |
public void setRegionCoverageAngle(int id, float angleInRadians) {
if (mRegionCoverageAngles == null) {
mRegionCoverageAngles = new float[REGION_CENTERS.length];
for (int i = 0; i < REGION_CENTERS.length; ++i) {
mRegionCoverageAngles[i] = REGION_COVERAGE_ANGLE_IN_RADIANS;
}
}
if (angleInRadians < mRegionCoverageAngles[id]) {
Log.e("SkyRegionMap", "Reducing coverage angle of region " + id +
" from " + mRegionCoverageAngles[id] + " to " + angleInRadians);
}
mRegionCoverageAngles[id] = angleInRadians;
} | void function(int id, float angleInRadians) { if (mRegionCoverageAngles == null) { mRegionCoverageAngles = new float[REGION_CENTERS.length]; for (int i = 0; i < REGION_CENTERS.length; ++i) { mRegionCoverageAngles[i] = REGION_COVERAGE_ANGLE_IN_RADIANS; } } if (angleInRadians < mRegionCoverageAngles[id]) { Log.e(STR, STR + id + STR + mRegionCoverageAngles[id] + STR + angleInRadians); } mRegionCoverageAngles[id] = angleInRadians; } | /**
* Sets the coverage angle for a sky region. Needed for non-point
* objects (see the javadoc for this class).
* @param id
* @param angleInRadians
*/ | Sets the coverage angle for a sky region. Needed for non-point objects (see the javadoc for this class) | setRegionCoverageAngle | {
"repo_name": "jaydeetay/stardroid",
"path": "app/src/main/java/com/google/android/stardroid/renderer/util/SkyRegionMap.java",
"license": "apache-2.0",
"size": 21835
} | [
"android.util.Log"
] | import android.util.Log; | import android.util.*; | [
"android.util"
] | android.util; | 2,148,349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.