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
|
---|---|---|---|---|---|---|---|---|---|---|---|
@Test
public void testLong2Int() {
try {
Message message = senderSession.createMessage();
message.setLongProperty("prop", 127L);
message.getIntProperty("prop");
Assert.fail("sec. 3.5.4 The unmarked cases [of Table 0-4] should raise a JMS MessageFormatException.\n");
} catch (MessageFormatException e) {
} catch (JMSException e) {
fail(e);
}
} | void function() { try { Message message = senderSession.createMessage(); message.setLongProperty("prop", 127L); message.getIntProperty("prop"); Assert.fail(STR); } catch (MessageFormatException e) { } catch (JMSException e) { fail(e); } } | /**
* if a property is set as a <code>long</code>,
* to get is as an <code>int</code> throws a <code>javax.jms.MessageFormatException</code>.
*/ | if a property is set as a <code>long</code>, to get is as an <code>int</code> throws a <code>javax.jms.MessageFormatException</code> | testLong2Int | {
"repo_name": "cshannon/activemq-artemis",
"path": "tests/joram-tests/src/test/java/org/objectweb/jtests/jms/conform/message/properties/MessagePropertyConversionTest.java",
"license": "apache-2.0",
"size": 43771
} | [
"javax.jms.JMSException",
"javax.jms.Message",
"javax.jms.MessageFormatException",
"org.junit.Assert"
] | import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageFormatException; import org.junit.Assert; | import javax.jms.*; import org.junit.*; | [
"javax.jms",
"org.junit"
] | javax.jms; org.junit; | 11,438 |
protected void unregisterConfigProvider(ConfigProvider configProvider) {
ServiceReferenceHolder.getInstance().setConfigProvider(null);
} | void function(ConfigProvider configProvider) { ServiceReferenceHolder.getInstance().setConfigProvider(null); } | /**
* This is the unbind method for the above reference that gets called for ConfigProvider instance un-registrations.
*
* @param configProvider the ConfigProvider service that get unregistered.
*/ | This is the unbind method for the above reference that gets called for ConfigProvider instance un-registrations | unregisterConfigProvider | {
"repo_name": "dewmini/carbon-apimgt",
"path": "components/apimgt/org.wso2.carbon.apimgt.rest.api.authenticator/src/main/java/org/wso2/carbon/apimgt/rest/api/authenticator/internal/ConfigurationActivator.java",
"license": "apache-2.0",
"size": 2444
} | [
"org.wso2.carbon.kernel.configprovider.ConfigProvider"
] | import org.wso2.carbon.kernel.configprovider.ConfigProvider; | import org.wso2.carbon.kernel.configprovider.*; | [
"org.wso2.carbon"
] | org.wso2.carbon; | 947,981 |
public HttpResponse removeRatingFromAPI(String apiName, String version, String provider)
throws APIManagerIntegrationTestException {
try {
checkAuthentication();
return HTTPSClientUtils.doGet(
backendURL + "store/site/blocks/api/api-info/ajax/api-info.jag?" +
"action=removeRating&name=" + apiName + "&version=" + version +
"&provider=" + provider, requestHeaders);
} catch (Exception e) {
throw new APIManagerIntegrationTestException("Unable to remove rating of API - " + apiName
+ ". Error: " + e.getMessage(), e);
}
} | HttpResponse function(String apiName, String version, String provider) throws APIManagerIntegrationTestException { try { checkAuthentication(); return HTTPSClientUtils.doGet( backendURL + STR + STR + apiName + STR + version + STR + provider, requestHeaders); } catch (Exception e) { throw new APIManagerIntegrationTestException(STR + apiName + STR + e.getMessage(), e); } } | /**
* Remove rating of given API
*
* @param apiName - name of api
* @param version - api version
* @param provider - provider of api
* @return - http response of remove rating request
* @throws org.wso2.am.integration.test.utils.APIManagerIntegrationTestException - Throws if remove API rating fails
*/ | Remove rating of given API | removeRatingFromAPI | {
"repo_name": "irhamiqbal/product-apim",
"path": "modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/clients/APIStoreRestClient.java",
"license": "apache-2.0",
"size": 54601
} | [
"org.wso2.am.integration.test.utils.APIManagerIntegrationTestException",
"org.wso2.am.integration.test.utils.http.HTTPSClientUtils",
"org.wso2.carbon.automation.test.utils.http.client.HttpResponse"
] | import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.http.HTTPSClientUtils; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; | import org.wso2.am.integration.test.utils.*; import org.wso2.am.integration.test.utils.http.*; import org.wso2.carbon.automation.test.utils.http.client.*; | [
"org.wso2.am",
"org.wso2.carbon"
] | org.wso2.am; org.wso2.carbon; | 106,370 |
super.doStart();
JMXEndpoint ep = (JMXEndpoint) getEndpoint();
// connect to the mbean server
if (ep.isPlatformServer()) {
setServerConnection(ManagementFactory.getPlatformMBeanServer());
} else {
JMXServiceURL url = new JMXServiceURL(ep.getServerURL());
String[] creds = {ep.getUser(), ep.getPassword()};
Map<String, String[]> map = Collections.singletonMap(JMXConnector.CREDENTIALS, creds);
JMXConnector connector = JMXConnectorFactory.connect(url, map);
setServerConnection(connector.getMBeanServerConnection());
}
// subscribe
addNotificationListener();
} | super.doStart(); JMXEndpoint ep = (JMXEndpoint) getEndpoint(); if (ep.isPlatformServer()) { setServerConnection(ManagementFactory.getPlatformMBeanServer()); } else { JMXServiceURL url = new JMXServiceURL(ep.getServerURL()); String[] creds = {ep.getUser(), ep.getPassword()}; Map<String, String[]> map = Collections.singletonMap(JMXConnector.CREDENTIALS, creds); JMXConnector connector = JMXConnectorFactory.connect(url, map); setServerConnection(connector.getMBeanServerConnection()); } addNotificationListener(); } | /**
* Initializes the mbean server connection and starts listening for
* Notification events from the object.
*/ | Initializes the mbean server connection and starts listening for Notification events from the object | doStart | {
"repo_name": "chicagozer/rheosoft",
"path": "components/camel-jmx/src/main/java/org/apache/camel/component/jmx/JMXConsumer.java",
"license": "apache-2.0",
"size": 5518
} | [
"java.lang.management.ManagementFactory",
"java.util.Collections",
"java.util.Map",
"javax.management.remote.JMXConnector",
"javax.management.remote.JMXConnectorFactory",
"javax.management.remote.JMXServiceURL"
] | import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; | import java.lang.management.*; import java.util.*; import javax.management.remote.*; | [
"java.lang",
"java.util",
"javax.management"
] | java.lang; java.util; javax.management; | 1,678,849 |
public ServiceResponse<Void> post204() throws ErrorException, IOException {
final Boolean booleanValue = null;
Call<ResponseBody> call = service.post204(booleanValue);
return post204Delegate(call.execute());
} | ServiceResponse<Void> function() throws ErrorException, IOException { final Boolean booleanValue = null; Call<ResponseBody> call = service.post204(booleanValue); return post204Delegate(call.execute()); } | /**
* Post true Boolean value in request returns 204 (no content).
*
* @throws ErrorException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the {@link ServiceResponse} object if successful.
*/ | Post true Boolean value in request returns 204 (no content) | post204 | {
"repo_name": "yaqiyang/autorest",
"path": "src/generator/AutoRest.Java.Tests/src/main/java/fixtures/http/implementation/HttpSuccessImpl.java",
"license": "mit",
"size": 71792
} | [
"com.microsoft.rest.ServiceResponse",
"java.io.IOException"
] | import com.microsoft.rest.ServiceResponse; import java.io.IOException; | import com.microsoft.rest.*; import java.io.*; | [
"com.microsoft.rest",
"java.io"
] | com.microsoft.rest; java.io; | 2,208,691 |
Set<ProcessorEntity> getProcessors(String groupId, boolean includeDescendants); | Set<ProcessorEntity> getProcessors(String groupId, boolean includeDescendants); | /**
* Gets all the Processor transfer objects for this controller.
*
* @param groupId group
* @param includeDescendants if processors from descendent groups should be included
* @return List of all the Processor transfer object
*/ | Gets all the Processor transfer objects for this controller | getProcessors | {
"repo_name": "jskora/nifi",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java",
"license": "apache-2.0",
"size": 83710
} | [
"java.util.Set",
"org.apache.nifi.web.api.entity.ProcessorEntity"
] | import java.util.Set; import org.apache.nifi.web.api.entity.ProcessorEntity; | import java.util.*; import org.apache.nifi.web.api.entity.*; | [
"java.util",
"org.apache.nifi"
] | java.util; org.apache.nifi; | 1,253,361 |
public Collection<GridFile> list(String directory) throws FileResourceException {
// Store currentDir
String currentDirectory = getCurrentDirectory();
// Change directory
setCurrentDirectory(directory);
Collection<GridFile> list = null;
try {
ftpClient.setType(Session.TYPE_ASCII);
list = list();
ftpClient.setType(Session.TYPE_IMAGE);
}
catch (Exception e) {
throw translateException("Error in list directory", e);
}
// Come back to original directory
setCurrentDirectory(currentDirectory);
return list;
} | Collection<GridFile> function(String directory) throws FileResourceException { String currentDirectory = getCurrentDirectory(); setCurrentDirectory(directory); Collection<GridFile> list = null; try { ftpClient.setType(Session.TYPE_ASCII); list = list(); ftpClient.setType(Session.TYPE_IMAGE); } catch (Exception e) { throw translateException(STR, e); } setCurrentDirectory(currentDirectory); return list; } | /**
* Equivalent to ls command on the given directory
*
* @throws FileResourceException
*/ | Equivalent to ls command on the given directory | list | {
"repo_name": "swift-lang/swift-k",
"path": "cogkit/modules/provider-gt2/src/org/globus/cog/abstraction/impl/file/ftp/FileResourceImpl.java",
"license": "apache-2.0",
"size": 20617
} | [
"java.util.Collection",
"org.globus.cog.abstraction.impl.file.FileResourceException",
"org.globus.cog.abstraction.interfaces.GridFile",
"org.globus.ftp.Session"
] | import java.util.Collection; import org.globus.cog.abstraction.impl.file.FileResourceException; import org.globus.cog.abstraction.interfaces.GridFile; import org.globus.ftp.Session; | import java.util.*; import org.globus.cog.abstraction.impl.file.*; import org.globus.cog.abstraction.interfaces.*; import org.globus.ftp.*; | [
"java.util",
"org.globus.cog",
"org.globus.ftp"
] | java.util; org.globus.cog; org.globus.ftp; | 1,078,201 |
public void setPutAmount(double putAmount) {
JodaBeanUtils.notNull(putAmount, "putAmount");
this._putAmount = putAmount;
} | void function(double putAmount) { JodaBeanUtils.notNull(putAmount, STR); this._putAmount = putAmount; } | /**
* Sets the put amount.
* @param putAmount the new value of the property, not null
*/ | Sets the put amount | setPutAmount | {
"repo_name": "jeorme/OG-Platform",
"path": "projects/OG-FinancialTypes/src/main/java/com/opengamma/financial/security/option/FXDigitalOptionSecurity.java",
"license": "apache-2.0",
"size": 21676
} | [
"org.joda.beans.JodaBeanUtils"
] | import org.joda.beans.JodaBeanUtils; | import org.joda.beans.*; | [
"org.joda.beans"
] | org.joda.beans; | 333,406 |
public void writeEnd(ContentHandler contentHandler) throws SAXException{
contentHandler.endElement(fixNull(nsUri),localName,getQName());
for( int i=ns.length-2; i>=0; i-=2 ) {
contentHandler.endPrefixMapping(fixNull(ns[i]));
}
} | void function(ContentHandler contentHandler) throws SAXException{ contentHandler.endElement(fixNull(nsUri),localName,getQName()); for( int i=ns.length-2; i>=0; i-=2 ) { contentHandler.endPrefixMapping(fixNull(ns[i])); } } | /**
* Writes the end element event.
*/ | Writes the end element event | writeEnd | {
"repo_name": "rokn/Count_Words_2015",
"path": "testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/encoding/TagInfoset.java",
"license": "mit",
"size": 8333
} | [
"org.xml.sax.ContentHandler",
"org.xml.sax.SAXException"
] | import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; | import org.xml.sax.*; | [
"org.xml.sax"
] | org.xml.sax; | 1,073,884 |
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
public static EHCachingConfigMasterComponentFactory.Meta meta() {
return EHCachingConfigMasterComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(EHCachingConfigMasterComponentFactory.Meta.INSTANCE);
} | static EHCachingConfigMasterComponentFactory.Meta function() { return EHCachingConfigMasterComponentFactory.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(EHCachingConfigMasterComponentFactory.Meta.INSTANCE); } | /**
* The meta-bean for {@code EHCachingConfigMasterComponentFactory}.
* @return the meta-bean, not null
*/ | The meta-bean for EHCachingConfigMasterComponentFactory | meta | {
"repo_name": "McLeodMoores/starling",
"path": "projects/component/src/main/java/com/opengamma/component/factory/master/EHCachingConfigMasterComponentFactory.java",
"license": "apache-2.0",
"size": 13963
} | [
"org.joda.beans.JodaBeanUtils"
] | import org.joda.beans.JodaBeanUtils; | import org.joda.beans.*; | [
"org.joda.beans"
] | org.joda.beans; | 557,077 |
@Generated
@Selector("bilateralFilterRadius")
@NUInt
public native long bilateralFilterRadius(); | @Selector(STR) native long function(); | /**
* The radius of the bilateral filter. Defaults to 2 resulting in a 5x5 filter.
*/ | The radius of the bilateral filter. Defaults to 2 resulting in a 5x5 filter | bilateralFilterRadius | {
"repo_name": "multi-os-engine/moe-core",
"path": "moe.apple/moe.platform.ios/src/main/java/apple/metalperformanceshaders/MPSSVGF.java",
"license": "apache-2.0",
"size": 51099
} | [
"org.moe.natj.objc.ann.Selector"
] | import org.moe.natj.objc.ann.Selector; | import org.moe.natj.objc.ann.*; | [
"org.moe.natj"
] | org.moe.natj; | 2,364,503 |
public static Type[] getGenericTypes(final Class<?> iClass) {
final Type genericType = iClass.getGenericInterfaces()[0];
if (genericType != null && genericType instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 1)
return pt.getActualTypeArguments();
}
return null;
}
| static Type[] function(final Class<?> iClass) { final Type genericType = iClass.getGenericInterfaces()[0]; if (genericType != null && genericType instanceof ParameterizedType) { final ParameterizedType pt = (ParameterizedType) genericType; if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 1) return pt.getActualTypeArguments(); } return null; } | /**
* Returns the declared generic types of a class.
*
* @param iClass
* Class to examine
* @return The array of Type if any, otherwise null
*/ | Returns the declared generic types of a class | getGenericTypes | {
"repo_name": "nengxu/OrientDB",
"path": "commons/src/main/java/com/orientechnologies/common/reflection/OReflectionHelper.java",
"license": "apache-2.0",
"size": 8180
} | [
"java.lang.reflect.ParameterizedType",
"java.lang.reflect.Type"
] | import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 2,618,732 |
List getAllResources(String rootFolder) throws ResourceException;
| List getAllResources(String rootFolder) throws ResourceException; | /**
* Get all the resources within the specified folder
*
* @param rootFolder the root folder resources are relative to
* @return list of all resources
* @throws ResourceException folder does not exist
*/ | Get all the resources within the specified folder | getAllResources | {
"repo_name": "fmguler/PragmaCMS",
"path": "PragmaCMS/src/java/com/pragmacraft/cms/service/resource/ResourceService.java",
"license": "agpl-3.0",
"size": 4552
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,458,298 |
@Nullable
public Teamwork get() throws ClientException {
return send(HttpMethod.GET, null);
} | Teamwork function() throws ClientException { return send(HttpMethod.GET, null); } | /**
* Gets the Teamwork from the service
*
* @return the Teamwork from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/ | Gets the Teamwork from the service | get | {
"repo_name": "microsoftgraph/msgraph-sdk-java",
"path": "src/main/java/com/microsoft/graph/requests/TeamworkRequest.java",
"license": "mit",
"size": 5705
} | [
"com.microsoft.graph.core.ClientException",
"com.microsoft.graph.http.HttpMethod",
"com.microsoft.graph.models.Teamwork"
] | import com.microsoft.graph.core.ClientException; import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.models.Teamwork; | import com.microsoft.graph.core.*; import com.microsoft.graph.http.*; import com.microsoft.graph.models.*; | [
"com.microsoft.graph"
] | com.microsoft.graph; | 1,350,708 |
public String readProperty(final String propertyName, final String defaultValue, final boolean required) {
String value = (String) properties.get(propertyName);
if (value == null && required) {
throw new ParameterRequiredException(propertyName);
}
return value == null ? defaultValue : value;
} | String function(final String propertyName, final String defaultValue, final boolean required) { String value = (String) properties.get(propertyName); if (value == null && required) { throw new ParameterRequiredException(propertyName); } return value == null ? defaultValue : value; } | /**
* Read the property with the given name
*
* @param propertyName
* the name of the property to be read
* @param defaultValue
* the default value to be returned
* @param required
* is it required
* @return the value of the property or null
* @throws ParameterRequiredException,
* if required parameter wasn't found
*/ | Read the property with the given name | readProperty | {
"repo_name": "BraintagsGmbH/netrelay",
"path": "src/main/java/de/braintags/netrelay/controller/AbstractController.java",
"license": "epl-1.0",
"size": 11447
} | [
"de.braintags.vertx.util.exception.ParameterRequiredException"
] | import de.braintags.vertx.util.exception.ParameterRequiredException; | import de.braintags.vertx.util.exception.*; | [
"de.braintags.vertx"
] | de.braintags.vertx; | 2,675,009 |
public Transformer getTransformer(); | Transformer function(); | /**
* Get the transformer associated with the serializer.
* @return Transformer the transformer associated with the serializer.
*/ | Get the transformer associated with the serializer | getTransformer | {
"repo_name": "mirkosertic/Bytecoder",
"path": "classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/com/sun/org/apache/xml/internal/serializer/SerializationHandler.java",
"license": "apache-2.0",
"size": 5299
} | [
"javax.xml.transform.Transformer"
] | import javax.xml.transform.Transformer; | import javax.xml.transform.*; | [
"javax.xml"
] | javax.xml; | 2,416,287 |
public Builder mergeDependentCcCompilationContexts(
Iterable<CcCompilationContext> exportedCcCompilationContexts,
Iterable<CcCompilationContext> ccCompilationContexts) {
for (CcCompilationContext ccCompilationContext :
Iterables.concat(exportedCcCompilationContexts, ccCompilationContexts)) {
mergeDependentCcCompilationContext(ccCompilationContext);
}
for (CcCompilationContext ccCompilationContext : exportedCcCompilationContexts) {
// For each of the exported contexts, re-export its own module map and all of the module
// maps that it exports.
CppModuleMap moduleMap = ccCompilationContext.getCppModuleMap();
if (moduleMap != null) {
exportingModuleMaps.add(moduleMap);
}
exportingModuleMaps.addAll(ccCompilationContext.exportingModuleMaps);
// Merge the modular and textual headers from the compilation context so that they are also
// re-exported.
headerInfoBuilder.mergeHeaderInfo(ccCompilationContext.headerInfo);
}
return this;
} | Builder function( Iterable<CcCompilationContext> exportedCcCompilationContexts, Iterable<CcCompilationContext> ccCompilationContexts) { for (CcCompilationContext ccCompilationContext : Iterables.concat(exportedCcCompilationContexts, ccCompilationContexts)) { mergeDependentCcCompilationContext(ccCompilationContext); } for (CcCompilationContext ccCompilationContext : exportedCcCompilationContexts) { CppModuleMap moduleMap = ccCompilationContext.getCppModuleMap(); if (moduleMap != null) { exportingModuleMaps.add(moduleMap); } exportingModuleMaps.addAll(ccCompilationContext.exportingModuleMaps); headerInfoBuilder.mergeHeaderInfo(ccCompilationContext.headerInfo); } return this; } | /**
* Merges the given {@code CcCompilationContext}s into this one by adding the contents of their
* attributes, and re-exporting the direct headers and module maps of {@code
* exportedCcCompilationContexts} through this one.
*/ | Merges the given CcCompilationContexts into this one by adding the contents of their attributes, and re-exporting the direct headers and module maps of exportedCcCompilationContexts through this one | mergeDependentCcCompilationContexts | {
"repo_name": "ulfjack/bazel",
"path": "src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationContext.java",
"license": "apache-2.0",
"size": 49395
} | [
"com.google.common.collect.Iterables"
] | import com.google.common.collect.Iterables; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,600,955 |
public void setOvertimeCost (BigDecimal OvertimeCost); | void function (BigDecimal OvertimeCost); | /** Set Overtime Cost.
* Hourly Overtime Cost
*/ | Set Overtime Cost. Hourly Overtime Cost | setOvertimeCost | {
"repo_name": "arthurmelo88/palmetalADP",
"path": "adempiere_360/base/src/org/compiere/model/I_C_Remuneration.java",
"license": "gpl-2.0",
"size": 6659
} | [
"java.math.BigDecimal"
] | import java.math.BigDecimal; | import java.math.*; | [
"java.math"
] | java.math; | 2,163,757 |
public CashReceiptFamilyBase getCashReceiptDocumentForValidation() {
return cashReceiptDocumentForValidation;
} | CashReceiptFamilyBase function() { return cashReceiptDocumentForValidation; } | /**
* Gets the cashReceiptDocumentForValidation attribute.
*
* @return Returns the cashReceiptDocumentForValidation.
*/ | Gets the cashReceiptDocumentForValidation attribute | getCashReceiptDocumentForValidation | {
"repo_name": "quikkian-ua-devops/will-financials",
"path": "kfs-core/src/main/java/org/kuali/kfs/fp/document/validation/impl/CashReceiptCashDrawerOpenValidation.java",
"license": "agpl-3.0",
"size": 7679
} | [
"org.kuali.kfs.fp.document.CashReceiptFamilyBase"
] | import org.kuali.kfs.fp.document.CashReceiptFamilyBase; | import org.kuali.kfs.fp.document.*; | [
"org.kuali.kfs"
] | org.kuali.kfs; | 1,297,336 |
public Observable<ServiceResponse<Page<AADObjectInner>>> getGroupMembersSinglePageAsync(final String objectId) {
if (objectId == null) {
throw new IllegalArgumentException("Parameter objectId is required and cannot be null.");
}
if (this.client.tenantID() == null) {
throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
} | Observable<ServiceResponse<Page<AADObjectInner>>> function(final String objectId) { if (objectId == null) { throw new IllegalArgumentException(STR); } if (this.client.tenantID() == null) { throw new IllegalArgumentException(STR); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException(STR); } | /**
* Gets the members of a group.
*
ServiceResponse<PageImpl<AADObjectInner>> * @param objectId The object ID of the group whose members should be retrieved.
* @return the PagedList<AADObjectInner> object wrapped in {@link ServiceResponse} if successful.
*/ | Gets the members of a group | getGroupMembersSinglePageAsync | {
"repo_name": "pomortaz/azure-sdk-for-java",
"path": "azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GroupsInner.java",
"license": "mit",
"size": 61868
} | [
"com.microsoft.azure.Page",
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.azure.Page; import com.microsoft.rest.ServiceResponse; | import com.microsoft.azure.*; import com.microsoft.rest.*; | [
"com.microsoft.azure",
"com.microsoft.rest"
] | com.microsoft.azure; com.microsoft.rest; | 2,643,140 |
public final QName getXmlName() {
return xmlName;
} | final QName function() { return xmlName; } | /**
* Gets the wrapper element name.
*/ | Gets the wrapper element name | getXmlName | {
"repo_name": "TheTypoMaster/Scaper",
"path": "openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/bind/v2/model/impl/ERPropertyInfoImpl.java",
"license": "gpl-2.0",
"size": 3222
} | [
"javax.xml.namespace.QName"
] | import javax.xml.namespace.QName; | import javax.xml.namespace.*; | [
"javax.xml"
] | javax.xml; | 2,103,285 |
public String dialogButtonsContinue(String okAttrs, String cancelAttrs, String detailsAttrs) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(detailsAttrs)) {
detailsAttrs = "";
} else {
detailsAttrs += " ";
}
return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL, BUTTON_DETAILS}, new String[] {
okAttrs,
cancelAttrs,
detailsAttrs + "onclick=\"switchOutputFormat();\""});
} | String function(String okAttrs, String cancelAttrs, String detailsAttrs) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(detailsAttrs)) { detailsAttrs = STR STRonclick=\STR"}); } | /**
* Builds a button row with an "Ok", a "Cancel" and a "Details" button.<p>
*
* This row is displayed when the first report is running.<p>
*
* @param okAttrs optional attributes for the ok button
* @param cancelAttrs optional attributes for the cancel button
* @param detailsAttrs optional attributes for the details button
* @return the button row
*/ | Builds a button row with an "Ok", a "Cancel" and a "Details" button. This row is displayed when the first report is running | dialogButtonsContinue | {
"repo_name": "it-tavis/opencms-core",
"path": "src/org/opencms/workplace/CmsReport.java",
"license": "lgpl-2.1",
"size": 20335
} | [
"org.opencms.util.CmsStringUtil"
] | import org.opencms.util.CmsStringUtil; | import org.opencms.util.*; | [
"org.opencms.util"
] | org.opencms.util; | 47,641 |
EList<POCType> getPOC(); | EList<POCType> getPOC(); | /**
* Returns the value of the '<em><b>POC</b></em>' containment reference list. The list contents are of type
* {@link org.search.niem.mpd.cat.POCType}. <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>POC</em>' containment reference list isn't clear, there really should be more of a
* description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>POC</em>' containment reference list.
* @see org.search.niem.mpd.cat.CatPackage#getAuthoritativeSourceType_POC()
* @model containment="true" required="true" extendedMetaData="kind='element' name='POC' namespace='##targetNamespace'"
* @generated
*/ | Returns the value of the 'POC' containment reference list. The list contents are of type <code>org.search.niem.mpd.cat.POCType</code>. If the meaning of the 'POC' containment reference list isn't clear, there really should be more of a description here... | getPOC | {
"repo_name": "info-sharing-environment/NIEM-Modeling-Tool",
"path": "plugins/org.search.niem.mpd/src/main/java/org/search/niem/mpd/cat/AuthoritativeSourceType.java",
"license": "epl-1.0",
"size": 5353
} | [
"org.eclipse.emf.common.util.EList"
] | import org.eclipse.emf.common.util.EList; | import org.eclipse.emf.common.util.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 516,079 |
public ImmutableCell withTechId(TechId techId) {
if (this.techId == techId) {
return this;
}
if (techId != null && techId.idManager != cellId.idManager) {
throw new IllegalArgumentException("techId");
}
return new ImmutableCell(this.cellId, this.groupName,
this.creationDate, this.revisionDate, techId, this.flags, getVars(), this.params);
} | ImmutableCell function(TechId techId) { if (this.techId == techId) { return this; } if (techId != null && techId.idManager != cellId.idManager) { throw new IllegalArgumentException(STR); } return new ImmutableCell(this.cellId, this.groupName, this.creationDate, this.revisionDate, techId, this.flags, getVars(), this.params); } | /**
* Returns ImmutableCell which differs from this ImmutableCell by technology.
* @param techId new technology Id.
* @return ImmutableCell which differs from this ImmutableCell by technology.
*/ | Returns ImmutableCell which differs from this ImmutableCell by technology | withTechId | {
"repo_name": "imr/Electric8",
"path": "com/sun/electric/database/ImmutableCell.java",
"license": "gpl-3.0",
"size": 18574
} | [
"com.sun.electric.database.id.TechId"
] | import com.sun.electric.database.id.TechId; | import com.sun.electric.database.id.*; | [
"com.sun.electric"
] | com.sun.electric; | 161,668 |
public static <T,U> List<U> findResults(Iterable<T> receiver, Function<T,U> filter) {
List<U> list = new ArrayList<>();
for (T t: receiver) {
U result = filter.apply(t);
if (result != null) {
list.add(result);
}
}
return list;
} | static <T,U> List<U> function(Iterable<T> receiver, Function<T,U> filter) { List<U> list = new ArrayList<>(); for (T t: receiver) { U result = filter.apply(t); if (result != null) { list.add(result); } } return list; } | /**
* Iterates through the Iterable transforming items using the supplied function and
* collecting any non-null results.
*/ | Iterates through the Iterable transforming items using the supplied function and collecting any non-null results | findResults | {
"repo_name": "nknize/elasticsearch",
"path": "modules/lang-painless/src/main/java/org/elasticsearch/painless/api/Augmentation.java",
"license": "apache-2.0",
"size": 28336
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.function.Function"
] | import java.util.ArrayList; import java.util.List; import java.util.function.Function; | import java.util.*; import java.util.function.*; | [
"java.util"
] | java.util; | 2,020,088 |
public static double probToLogOdds(double prob) {
if (gr(prob, 1) || (sm(prob, 0))) {
throw new IllegalArgumentException("probToLogOdds: probability must " +
"be in [0,1] "+prob);
}
double p = SMALL + (1.0 - 2 * SMALL) * prob;
return Math.log(p / (1 - p));
}
| static double function(double prob) { if (gr(prob, 1) (sm(prob, 0))) { throw new IllegalArgumentException(STR + STR+prob); } double p = SMALL + (1.0 - 2 * SMALL) * prob; return Math.log(p / (1 - p)); } | /**
* Returns the log-odds for a given probabilitiy.
*
* @param prob the probabilitiy
*
* @return the log-odds after the probability has been mapped to
* [Utils.SMALL, 1-Utils.SMALL]
*/ | Returns the log-odds for a given probabilitiy | probToLogOdds | {
"repo_name": "TheMurderer/keel",
"path": "src/keel/Algorithms/SVM/SMO/core/Utils.java",
"license": "gpl-3.0",
"size": 59525
} | [
"java.lang.Math"
] | import java.lang.Math; | import java.lang.*; | [
"java.lang"
] | java.lang; | 1,116,407 |
@Test
public void whenDeleteAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.DELETE_ASYNC);
} | void function() { whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.DELETE_ASYNC); } | /**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DELETE_ASYNC} is used.
*/ | Checks that the Near Cache is eventually invalidated when <code>DataStructureMethods#DELETE_ASYNC</code> is used | whenDeleteAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter | {
"repo_name": "tkountis/hazelcast",
"path": "hazelcast/src/test/java/com/hazelcast/internal/nearcache/AbstractNearCacheBasicTest.java",
"license": "apache-2.0",
"size": 79879
} | [
"com.hazelcast.internal.adapter.DataStructureAdapter"
] | import com.hazelcast.internal.adapter.DataStructureAdapter; | import com.hazelcast.internal.adapter.*; | [
"com.hazelcast.internal"
] | com.hazelcast.internal; | 1,755,138 |
public Timestamp getUpdated();
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; | Timestamp function(); public static final String COLUMNNAME_UpdatedBy = STR; | /** Get Updated.
* Date this record was updated
*/ | Get Updated. Date this record was updated | getUpdated | {
"repo_name": "klst-com/metasfresh",
"path": "de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/I_C_Withholding_Acct.java",
"license": "gpl-2.0",
"size": 4739
} | [
"java.sql.Timestamp"
] | import java.sql.Timestamp; | import java.sql.*; | [
"java.sql"
] | java.sql; | 442,476 |
private void moveAllDataToDestDisk(DataNode dataNode, int destDiskindex)
throws IOException {
Preconditions.checkNotNull(dataNode);
Preconditions.checkState(destDiskindex >= 0);
try (FsDatasetSpi.FsVolumeReferences refs =
dataNode.getFSDataset().getFsVolumeReferences()) {
if (refs.size() <= destDiskindex) {
throw new IllegalArgumentException("Invalid Disk index.");
}
FsVolumeImpl dest = (FsVolumeImpl) refs.get(destDiskindex);
for (int x = 0; x < refs.size(); x++) {
if (x == destDiskindex) {
continue;
}
FsVolumeImpl source = (FsVolumeImpl) refs.get(x);
DiskBalancerTestUtil.moveAllDataToDestVolume(dataNode.getFSDataset(),
source, dest);
}
}
} | void function(DataNode dataNode, int destDiskindex) throws IOException { Preconditions.checkNotNull(dataNode); Preconditions.checkState(destDiskindex >= 0); try (FsDatasetSpi.FsVolumeReferences refs = dataNode.getFSDataset().getFsVolumeReferences()) { if (refs.size() <= destDiskindex) { throw new IllegalArgumentException(STR); } FsVolumeImpl dest = (FsVolumeImpl) refs.get(destDiskindex); for (int x = 0; x < refs.size(); x++) { if (x == destDiskindex) { continue; } FsVolumeImpl source = (FsVolumeImpl) refs.get(x); DiskBalancerTestUtil.moveAllDataToDestVolume(dataNode.getFSDataset(), source, dest); } } } | /**
* Moves all data in the data node to one disk.
*
* @param dataNode - Datanode
* @param destDiskindex - Index of the destination disk.
*/ | Moves all data in the data node to one disk | moveAllDataToDestDisk | {
"repo_name": "steveloughran/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/diskbalancer/TestDiskBalancer.java",
"license": "apache-2.0",
"size": 29744
} | [
"com.google.common.base.Preconditions",
"java.io.IOException",
"org.apache.hadoop.hdfs.server.datanode.DataNode",
"org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi",
"org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl"
] | import com.google.common.base.Preconditions; import java.io.IOException; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl; | import com.google.common.base.*; import java.io.*; import org.apache.hadoop.hdfs.server.datanode.*; import org.apache.hadoop.hdfs.server.datanode.fsdataset.*; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.*; | [
"com.google.common",
"java.io",
"org.apache.hadoop"
] | com.google.common; java.io; org.apache.hadoop; | 1,806,594 |
@Override
public Counter<String> getGradient(Counter<String> weights,
Sequence<IString> source,
int sourceId,
List<RichTranslation<IString, String>> translations, List<Sequence<IString>> references,
double[] referenceWeights, SentenceLevelMetric<IString, String> scoreMetric) {
// Lock the loss function since we don't want updates to its statistics while we are searching
// for the hope and fear derivations.
Derivation dHope, dFear;
synchronized(scoreMetric) {
// The "correct" derivation (Crammer et al. (2006) fig.2)
dHope = getBestHopeDerivation(scoreMetric, translations, references, referenceWeights, sourceId, source);
logger.info("Hope derivation: {}", dHope.toString());
// The "max-loss" derivation (Crammer et al. (2006) fig.2)
dFear = getBestFearDerivation(scoreMetric, translations, references, referenceWeights, dHope, sourceId, source);
logger.info("Fear derivation: {}", dFear.toString());
// Update the loss function with the hope derivation a la
// Cherry and Foster (2012) (Chiang (2012) uses the 1-best translation).
// This follows the Moses implementation in mert/kbmira.cpp
if (dHope.nbestId != dFear.nbestId) {
scoreMetric.update(sourceId, references, dHope.hypothesis.translation);
}
}
final double margin = dFear.modelScore - dHope.modelScore;
// TODO(spenceg): Crammer takes the square root of the cost. We should try that.
final double deltaCost = dHope.gain - dFear.gain;
final double loss = margin + deltaCost;
logger.info(String.format("Margin: %.5f dCost: %.5f Loss: %.5f", margin, deltaCost, loss));
Counter<String> gradient = new ClassicCounter<String>();
// Hinge loss.
if (loss > 0.0) {
// Only do an update in this case.
// Compute the PA-II update, which is the loss divided by the
// squared norm of the differences between the feature vectors
Counter<String> hopeFeatures = OptimizerUtils.featureValueCollectionToCounter(dHope.hypothesis.features);
Counter<String> fearFeatures = OptimizerUtils.featureValueCollectionToCounter(dFear.hypothesis.features);
gradient = Counters.diff(hopeFeatures, fearFeatures);
logger.info("Feature difference: {}", gradient.toString());
// Compute the update
double sumSquaredFeatureDiff = Counters.sumSquares(gradient);
double tau = Math.min(C, loss / sumSquaredFeatureDiff);
logger.info("tau: {}", tau);
// Update the weights
Counters.multiplyInPlace(gradient, tau);
} else {
logger.info("NO UPDATE (loss: {})", loss);
}
return gradient;
} | Counter<String> function(Counter<String> weights, Sequence<IString> source, int sourceId, List<RichTranslation<IString, String>> translations, List<Sequence<IString>> references, double[] referenceWeights, SentenceLevelMetric<IString, String> scoreMetric) { Derivation dHope, dFear; synchronized(scoreMetric) { dHope = getBestHopeDerivation(scoreMetric, translations, references, referenceWeights, sourceId, source); logger.info(STR, dHope.toString()); dFear = getBestFearDerivation(scoreMetric, translations, references, referenceWeights, dHope, sourceId, source); logger.info(STR, dFear.toString()); if (dHope.nbestId != dFear.nbestId) { scoreMetric.update(sourceId, references, dHope.hypothesis.translation); } } final double margin = dFear.modelScore - dHope.modelScore; final double deltaCost = dHope.gain - dFear.gain; final double loss = margin + deltaCost; logger.info(String.format(STR, margin, deltaCost, loss)); Counter<String> gradient = new ClassicCounter<String>(); if (loss > 0.0) { Counter<String> hopeFeatures = OptimizerUtils.featureValueCollectionToCounter(dHope.hypothesis.features); Counter<String> fearFeatures = OptimizerUtils.featureValueCollectionToCounter(dFear.hypothesis.features); gradient = Counters.diff(hopeFeatures, fearFeatures); logger.info(STR, gradient.toString()); double sumSquaredFeatureDiff = Counters.sumSquares(gradient); double tau = Math.min(C, loss / sumSquaredFeatureDiff); logger.info(STR, tau); Counters.multiplyInPlace(gradient, tau); } else { logger.info(STR, loss); } return gradient; } | /**
* This is an implementation of Fig.2 from Crammer et al. (2006).
*/ | This is an implementation of Fig.2 from Crammer et al. (2006) | getGradient | {
"repo_name": "chrishokamp/phrasal",
"path": "src/edu/stanford/nlp/mt/tune/optimizers/MIRA1BestHopeFearOptimizer.java",
"license": "gpl-3.0",
"size": 8285
} | [
"edu.stanford.nlp.mt.metrics.SentenceLevelMetric",
"edu.stanford.nlp.mt.util.IString",
"edu.stanford.nlp.mt.util.RichTranslation",
"edu.stanford.nlp.mt.util.Sequence",
"edu.stanford.nlp.stats.ClassicCounter",
"edu.stanford.nlp.stats.Counter",
"edu.stanford.nlp.stats.Counters",
"java.util.List"
] | import edu.stanford.nlp.mt.metrics.SentenceLevelMetric; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.RichTranslation; import edu.stanford.nlp.mt.util.Sequence; import edu.stanford.nlp.stats.ClassicCounter; import edu.stanford.nlp.stats.Counter; import edu.stanford.nlp.stats.Counters; import java.util.List; | import edu.stanford.nlp.mt.metrics.*; import edu.stanford.nlp.mt.util.*; import edu.stanford.nlp.stats.*; import java.util.*; | [
"edu.stanford.nlp",
"java.util"
] | edu.stanford.nlp; java.util; | 409,156 |
public void setSiteHelper(SiteHelper siteHelper)
{
this.siteHelper = siteHelper;
}
| void function(SiteHelper siteHelper) { this.siteHelper = siteHelper; } | /**
* Sets the site helper
* @param siteHelper site helper
*/ | Sets the site helper | setSiteHelper | {
"repo_name": "loftuxab/community-edition-old",
"path": "modules/wcmquickstart/wcmquickstartmodule/source/java/org/alfresco/module/org_alfresco_module_wcmquickstart/jobs/feedback/FeedbackProcessorHandlerBase.java",
"license": "lgpl-3.0",
"size": 3278
} | [
"org.alfresco.module.org_alfresco_module_wcmquickstart.util.SiteHelper"
] | import org.alfresco.module.org_alfresco_module_wcmquickstart.util.SiteHelper; | import org.alfresco.module.org_alfresco_module_wcmquickstart.util.*; | [
"org.alfresco.module"
] | org.alfresco.module; | 2,664,383 |
@Test
public void testIndexCreationFromXML() throws Exception {
InternalDistributedSystem.getAnyInstance().disconnect();
File file = new File("persistData0");
file.mkdir();
{
Properties props = new Properties();
props.setProperty(DistributionConfig.NAME_NAME, "test");
int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
props.setProperty("mcast-port", "0");
props.setProperty("cache-xml-file", IndexCreationJUnitTest.class.getResource("index-creation-with-eviction.xml").toURI().getPath());
DistributedSystem ds = DistributedSystem.connect(props);
// Create the cache which causes the cache-xml-file to be parsed
Cache cache = CacheFactory.create(ds);
QueryService qs = cache.getQueryService();
Region region = cache.getRegion("mainReportRegion");
for (int i = 0; i < 100; i++) {
Portfolio pf = new Portfolio(i);
pf.setCreateTime(i);
region.put(""+ i, pf);
}
//verify that a query on the creation time works as expected
SelectResults results = (SelectResults)qs.newQuery("<trace>SELECT * FROM /mainReportRegion.entrySet mr Where mr.value.createTime > 1L and mr.value.createTime < 3L").execute();
assertEquals("OQL index results did not match", 1, results.size());
cache.close();
ds.disconnect();
}
{
Properties props = new Properties();
props.setProperty(DistributionConfig.NAME_NAME, "test");
props.setProperty("mcast-port", "0");
//Using a different cache.xml that changes some region properties
//That will force the disk code to copy the region entries.
props.setProperty("cache-xml-file", IndexCreationJUnitTest.class.getResource("index-creation-without-eviction.xml").toURI().getPath());
DistributedSystem ds = DistributedSystem.connect(props);
Cache cache = CacheFactory.create(ds);
QueryService qs = cache.getQueryService();
Region region = cache.getRegion("mainReportRegion");
//verify that a query on the creation time works as expected
SelectResults results = (SelectResults)qs.newQuery("<trace>SELECT * FROM /mainReportRegion.entrySet mr Where mr.value.createTime > 1L and mr.value.createTime < 3L").execute();
assertEquals("OQL index results did not match", 1, results.size());
ds.disconnect();
FileUtil.delete(file);
}
} | void function() throws Exception { InternalDistributedSystem.getAnyInstance().disconnect(); File file = new File(STR); file.mkdir(); { Properties props = new Properties(); props.setProperty(DistributionConfig.NAME_NAME, "test"); int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS); props.setProperty(STR, "0"); props.setProperty(STR, IndexCreationJUnitTest.class.getResource(STR).toURI().getPath()); DistributedSystem ds = DistributedSystem.connect(props); Cache cache = CacheFactory.create(ds); QueryService qs = cache.getQueryService(); Region region = cache.getRegion(STR); for (int i = 0; i < 100; i++) { Portfolio pf = new Portfolio(i); pf.setCreateTime(i); region.put(STR<trace>SELECT * FROM /mainReportRegion.entrySet mr Where mr.value.createTime > 1L and mr.value.createTime < 3LSTROQL index results did not matchSTRtest"); props.setProperty(STR, "0"); props.setProperty(STR, IndexCreationJUnitTest.class.getResource("index-creation-without-eviction.xml").toURI().getPath()); DistributedSystem ds = DistributedSystem.connect(props); Cache cache = CacheFactory.create(ds); QueryService qs = cache.getQueryService(); Region region = cache.getRegion(STR); SelectResults results = (SelectResults)qs.newQuery("<trace>SELECT * FROM /mainReportRegion.entrySet mr Where mr.value.createTime > 1L and mr.value.createTime < 3LSTROQL index results did not match", 1, results.size()); ds.disconnect(); FileUtil.delete(file); } } | /**
* Test for bug 46872, make sure
* we recover the index correctly if the cache.xml
* changes for a persistent region.
*/ | Test for bug 46872, make sure we recover the index correctly if the cache.xml changes for a persistent region | testIndexCreationFromXML | {
"repo_name": "nchandrappa/incubator-geode",
"path": "gemfire-core/src/test/java/com/gemstone/gemfire/cache/query/functional/IndexCreationJUnitTest.java",
"license": "apache-2.0",
"size": 47272
} | [
"com.gemstone.gemfire.cache.Cache",
"com.gemstone.gemfire.cache.CacheFactory",
"com.gemstone.gemfire.cache.Region",
"com.gemstone.gemfire.cache.query.QueryService",
"com.gemstone.gemfire.cache.query.SelectResults",
"com.gemstone.gemfire.cache.query.data.Portfolio",
"com.gemstone.gemfire.distributed.DistributedSystem",
"com.gemstone.gemfire.distributed.internal.DistributionConfig",
"com.gemstone.gemfire.distributed.internal.InternalDistributedSystem",
"com.gemstone.gemfire.internal.AvailablePort",
"com.gemstone.gemfire.internal.FileUtil",
"java.io.File",
"java.util.Properties"
] | import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.query.QueryService; import com.gemstone.gemfire.cache.query.SelectResults; import com.gemstone.gemfire.cache.query.data.Portfolio; import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; import com.gemstone.gemfire.internal.AvailablePort; import com.gemstone.gemfire.internal.FileUtil; import java.io.File; import java.util.Properties; | import com.gemstone.gemfire.cache.*; import com.gemstone.gemfire.cache.query.*; import com.gemstone.gemfire.cache.query.data.*; import com.gemstone.gemfire.distributed.*; import com.gemstone.gemfire.distributed.internal.*; import com.gemstone.gemfire.internal.*; import java.io.*; import java.util.*; | [
"com.gemstone.gemfire",
"java.io",
"java.util"
] | com.gemstone.gemfire; java.io; java.util; | 2,358,228 |
public MediaType withParameters(Multimap<String, String> parameters) {
return create(type, subtype, parameters);
} | MediaType function(Multimap<String, String> parameters) { return create(type, subtype, parameters); } | /**
* <em>Replaces</em> all parameters with the given parameters.
*
* @throws IllegalArgumentException if any parameter or value is invalid
*/ | Replaces all parameters with the given parameters | withParameters | {
"repo_name": "newrelic/guava-libraries",
"path": "guava/src/com/google/common/net/MediaType.java",
"license": "apache-2.0",
"size": 30988
} | [
"com.google.common.collect.Multimap"
] | import com.google.common.collect.Multimap; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,140,166 |
public HashMap<String, Integer> getFourgramLM() {
return fourgramLM;
} | HashMap<String, Integer> function() { return fourgramLM; } | /**
* get the fourgram language model.
*
* @return fourgram language model
*/ | get the fourgram language model | getFourgramLM | {
"repo_name": "wasiahmad/AOL-Query-Log-Analysis",
"path": "src/language model based query topic analysis/src/edu/virginia/cs/model/LanguageModel.java",
"license": "mit",
"size": 20434
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,546,610 |
URL url = new URL(urlStr);
InputStream inputStream = (InputStream) url.getContent();
return inputStream;
} | URL url = new URL(urlStr); InputStream inputStream = (InputStream) url.getContent(); return inputStream; } | /**
* Perform HTTP request and return result as a stream
*
* @param urlStr
* @return
* @throws IOException
*/ | Perform HTTP request and return result as a stream | httpStream | {
"repo_name": "phenelle/AnnonceAPI",
"path": "lib/src/main/java/com/cubitux/utils/HTTPUtil.java",
"license": "mit",
"size": 3243
} | [
"java.io.InputStream"
] | import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 2,009,563 |
public List<Passenger> findPassengers(Predicate<Passenger> passengerPredicate, Comparator<Passenger> passengerComparator) {
List<Passenger> res = findPassengers(passengerPredicate);
res.sort(passengerComparator);
return res;
} | List<Passenger> function(Predicate<Passenger> passengerPredicate, Comparator<Passenger> passengerComparator) { List<Passenger> res = findPassengers(passengerPredicate); res.sort(passengerComparator); return res; } | /**
* Finds passengers matching some criteria and sorts them
*
* @param passengerPredicate a predicate that tests passengers
* @param passengerComparator a comparator used to sort results
* @return a list of passengers
* @see #findPassengers(Predicate)
* @see Predicate
*/ | Finds passengers matching some criteria and sorts them | findPassengers | {
"repo_name": "RafaelPAndrade/LEIC-A-IST",
"path": "PO/Proj/mmt-core/src/mmt/TrainCompany.java",
"license": "mit",
"size": 15133
} | [
"java.util.Comparator",
"java.util.List",
"java.util.function.Predicate"
] | import java.util.Comparator; import java.util.List; import java.util.function.Predicate; | import java.util.*; import java.util.function.*; | [
"java.util"
] | java.util; | 531,954 |
public FindItemsResults<Item> findItems(FolderId parentFolderId,
SearchFilter searchFilter, ItemView view) throws Exception {
EwsUtilities.validateParamAllowNull(searchFilter, "searchFilter");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, searchFilter, null,
view, null,
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
} | FindItemsResults<Item> function(FolderId parentFolderId, SearchFilter searchFilter, ItemView view) throws Exception { EwsUtilities.validateParamAllowNull(searchFilter, STR); List<FolderId> folderIdArray = new ArrayList<FolderId>(); folderIdArray.add(parentFolderId); ServiceResponseCollection<FindItemResponse<Item>> responses = this .findItems(folderIdArray, searchFilter, null, view, null, ServiceErrorHandling.ThrowOnError); return responses.getResponseAtIndex(0).getResults(); } | /**
* Obtains a list of item by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderId the parent folder id
* @param searchFilter the search filter
* @param view the view
* @return An object representing the results of the search operation.
* @throws Exception the exception
*/ | Obtains a list of item by searching the contents of a specific folder. Calling this method results in a call to EWS | findItems | {
"repo_name": "candrews/ews-java-api",
"path": "src/main/java/microsoft/exchange/webservices/data/core/ExchangeService.java",
"license": "mit",
"size": 161711
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,373,966 |
public Observable<ServiceResponse<Page<HybridConnectionInner>>> listHybridConnectionsSinglePageAsync(final String resourceGroupName, final String name) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
} | Observable<ServiceResponse<Page<HybridConnectionInner>>> function(final String resourceGroupName, final String name) { if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (name == null) { throw new IllegalArgumentException(STR); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } | /**
* Retrieve all Hybrid Connections in use in an App Service plan.
* Retrieve all Hybrid Connections in use in an App Service plan.
*
ServiceResponse<PageImpl<HybridConnectionInner>> * @param resourceGroupName Name of the resource group to which the resource belongs.
ServiceResponse<PageImpl<HybridConnectionInner>> * @param name Name of the App Service plan.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<HybridConnectionInner> object wrapped in {@link ServiceResponse} if successful.
*/ | Retrieve all Hybrid Connections in use in an App Service plan. Retrieve all Hybrid Connections in use in an App Service plan | listHybridConnectionsSinglePageAsync | {
"repo_name": "jianghaolu/azure-sdk-for-java",
"path": "azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/implementation/AppServicePlansInner.java",
"license": "mit",
"size": 260114
} | [
"com.microsoft.azure.Page",
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.azure.Page; import com.microsoft.rest.ServiceResponse; | import com.microsoft.azure.*; import com.microsoft.rest.*; | [
"com.microsoft.azure",
"com.microsoft.rest"
] | com.microsoft.azure; com.microsoft.rest; | 130,164 |
EClass getViatraImport();
| EClass getViatraImport(); | /**
* Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ViatraImport <em>Viatra Import</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Viatra Import</em>'.
* @see hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ViatraImport
* @generated
*/ | Returns the meta object for class '<code>hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.ViatraImport Viatra Import</code>'. | getViatraImport | {
"repo_name": "viatra/VIATRA-Generator",
"path": "Application/hu.bme.mit.inf.dslreasoner.application/src-gen/hu/bme/mit/inf/dslreasoner/application/applicationConfiguration/ApplicationConfigurationPackage.java",
"license": "epl-1.0",
"size": 236178
} | [
"org.eclipse.emf.ecore.EClass"
] | import org.eclipse.emf.ecore.EClass; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,261,651 |
//---------------------------------------------------------------//
//Method called by SchedulerEventListener
//---------------------------------------------------------------//
public void handleJobEvent(SchedulerEvent event, JobInfo jInfo) {
synchronized (this) {
if (event.equals(SchedulerEvent.JOB_RUNNING_TO_FINISHED) ||
event.equals(SchedulerEvent.JOB_PENDING_TO_FINISHED)) {
this.finishedJobs.add(jInfo.getJobId());
}
if (!lookAndNotifyMonitor(new JobEventMonitor(event, jInfo))) {
//no monitor notified, memorize event.
addJobEvent(event, jInfo);
}
}
} | void function(SchedulerEvent event, JobInfo jInfo) { synchronized (this) { if (event.equals(SchedulerEvent.JOB_RUNNING_TO_FINISHED) event.equals(SchedulerEvent.JOB_PENDING_TO_FINISHED)) { this.finishedJobs.add(jInfo.getJobId()); } if (!lookAndNotifyMonitor(new JobEventMonitor(event, jInfo))) { addJobEvent(event, jInfo); } } } | /**
* Memorize or notify a waiter for a new job event received
*
* @param event Job event type
* @param jInfo event's associated JobInfo object
*/ | Memorize or notify a waiter for a new job event received | handleJobEvent | {
"repo_name": "laurianed/scheduling",
"path": "scheduler/scheduler-server/src/test/java/functionaltests/monitor/SchedulerMonitorsHandler.java",
"license": "agpl-3.0",
"size": 20896
} | [
"org.ow2.proactive.scheduler.common.SchedulerEvent",
"org.ow2.proactive.scheduler.common.job.JobInfo"
] | import org.ow2.proactive.scheduler.common.SchedulerEvent; import org.ow2.proactive.scheduler.common.job.JobInfo; | import org.ow2.proactive.scheduler.common.*; import org.ow2.proactive.scheduler.common.job.*; | [
"org.ow2.proactive"
] | org.ow2.proactive; | 2,814,839 |
private static void appendProcessBriefType( Element processOfferingsNode, ProcessBrief processBriefType ) {
// Add a <wps:Process> node to the <wps:ProcessOfferings> node
Element processBriefTypeNode = XMLTools.appendElement( processOfferingsNode, WPSNS, "wps:Process" );
// Add optional attribute "processVersion" to <wps:Process> node if
// present
String processVersion = processBriefType.getProcessVersion();
if ( null != processVersion && !"".equals( processVersion ) ) {
processBriefTypeNode.setAttribute( "processVersion", processVersion );
}
// Add mandatory node <ows:Identifier>
Code identifier = processBriefType.getIdentifier();
if ( null != identifier ) {
appendIdentifier( processBriefTypeNode, identifier );
} else {
LOG.logError( "identifier is null." );
}
// Add mandatory node <ows:Title>
String title = processBriefType.getTitle();
if ( null != title ) {
appendTitle( processBriefTypeNode, title );
} else {
LOG.logError( "title is null." );
}
// Add optional node <ows:Abstract/>
String _abstract = processBriefType.getAbstract();
if ( null != _abstract ) {
appendAbstract( processBriefTypeNode, _abstract );
}
// Add optional nodes <ows:Metadata/>
List<MetadataType> metaDataTypeList = processBriefType.getMetadata();
if ( null != metaDataTypeList && 0 != metaDataTypeList.size() ) {
int size = metaDataTypeList.size();
for ( int i = 0; i < size; i++ ) {
appendMetaDataType( processBriefTypeNode, metaDataTypeList.get( i ) );
}
}
}
| static void function( Element processOfferingsNode, ProcessBrief processBriefType ) { Element processBriefTypeNode = XMLTools.appendElement( processOfferingsNode, WPSNS, STR ); String processVersion = processBriefType.getProcessVersion(); if ( null != processVersion && !STRprocessVersionSTRidentifier is null.STRtitle is null." ); } String _abstract = processBriefType.getAbstract(); if ( null != _abstract ) { appendAbstract( processBriefTypeNode, _abstract ); } List<MetadataType> metaDataTypeList = processBriefType.getMetadata(); if ( null != metaDataTypeList && 0 != metaDataTypeList.size() ) { int size = metaDataTypeList.size(); for ( int i = 0; i < size; i++ ) { appendMetaDataType( processBriefTypeNode, metaDataTypeList.get( i ) ); } } } | /**
* Appends the DOM representation of the <code>ProcessBriefType</code> instance to the passed
* <code>Element</code>.
*
* @param processOfferingsNode
* @param processBriefType
*/ | Appends the DOM representation of the <code>ProcessBriefType</code> instance to the passed <code>Element</code> | appendProcessBriefType | {
"repo_name": "lat-lon/deegree2-base",
"path": "deegree2-core/src/main/java/org/deegree/ogcwebservices/wps/XMLFactory.java",
"license": "lgpl-2.1",
"size": 53285
} | [
"java.util.List",
"org.deegree.framework.xml.XMLTools",
"org.deegree.ogcwebservices.MetadataType",
"org.w3c.dom.Element"
] | import java.util.List; import org.deegree.framework.xml.XMLTools; import org.deegree.ogcwebservices.MetadataType; import org.w3c.dom.Element; | import java.util.*; import org.deegree.framework.xml.*; import org.deegree.ogcwebservices.*; import org.w3c.dom.*; | [
"java.util",
"org.deegree.framework",
"org.deegree.ogcwebservices",
"org.w3c.dom"
] | java.util; org.deegree.framework; org.deegree.ogcwebservices; org.w3c.dom; | 1,311,247 |
public static Object getPixels(BufferedImage image) {
return getPixels(image, 0, 0, image.getWidth(), image.getHeight());
} | static Object function(BufferedImage image) { return getPixels(image, 0, 0, image.getWidth(), image.getHeight()); } | /**
* Gets the image's pixel data as arrays of primitives, one per channel.
* The returned type will be either byte[][], short[][], int[][], float[][]
* or double[][], depending on the image's transfer type.
*/ | Gets the image's pixel data as arrays of primitives, one per channel. The returned type will be either byte[][], short[][], int[][], float[][] or double[][], depending on the image's transfer type | getPixels | {
"repo_name": "bramalingam/bioformats",
"path": "components/formats-bsd/src/loci/formats/gui/AWTImageTools.java",
"license": "gpl-2.0",
"size": 71667
} | [
"java.awt.image.BufferedImage"
] | import java.awt.image.BufferedImage; | import java.awt.image.*; | [
"java.awt"
] | java.awt; | 1,980,580 |
GnucashWritableInvoiceEntry createEntry(final FixedPointNumber singleUnitPrice, final FixedPointNumber quantity) throws JAXBException; | GnucashWritableInvoiceEntry createEntry(final FixedPointNumber singleUnitPrice, final FixedPointNumber quantity) throws JAXBException; | /**
* create and add a new entry.<br/>
* The entry will have 16% salex-tax and use the accounts of the
* SKR03.
* @throws JAXBException if we have issues accessing the XML-Backend.
*/ | create and add a new entry. The entry will have 16% salex-tax and use the accounts of the SKR03 | createEntry | {
"repo_name": "nhrdl/javacash",
"path": "jGnucashLib/plugins/biz.wolschon.finance.jgnucash.editor.main/src/main/java/biz/wolschon/fileformats/gnucash/GnucashWritableInvoice.java",
"license": "apache-2.0",
"size": 3359
} | [
"biz.wolschon.numbers.FixedPointNumber",
"javax.xml.bind.JAXBException"
] | import biz.wolschon.numbers.FixedPointNumber; import javax.xml.bind.JAXBException; | import biz.wolschon.numbers.*; import javax.xml.bind.*; | [
"biz.wolschon.numbers",
"javax.xml"
] | biz.wolschon.numbers; javax.xml; | 1,862,813 |
PhotoArticleCatalogue savePhotoArticleCatalogue(byte[] content, String nomFichier) throws IOException; | PhotoArticleCatalogue savePhotoArticleCatalogue(byte[] content, String nomFichier) throws IOException; | /**
* Sauvegarde sur le serveur la photo d'un article
*
* @param content la photo
* @param nomFichier le nom de la photo
* @return l'entité PhotoArticleCatalogue
* @throws IOException IOException
*/ | Sauvegarde sur le serveur la photo d'un article | savePhotoArticleCatalogue | {
"repo_name": "DSI-Ville-Noumea/appock",
"path": "src/main/java/nc/noumea/mairie/appock/services/CatalogueService.java",
"license": "lgpl-3.0",
"size": 3394
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,259,755 |
public OperatorView select(JobflowInfo jobflow, OperatorGraphView graph) {
if (name == null) {
throw new IllegalStateException();
}
return findFlowPart(graph, name)
.orElseThrow(() -> new CommandConfigurationException(MessageFormat.format(
"there are no flow part named \"{1}\" in jobflow {0}",
Optional.ofNullable(jobflow.getDescriptionClass())
.orElse(jobflow.getId()),
name)));
} | OperatorView function(JobflowInfo jobflow, OperatorGraphView graph) { if (name == null) { throw new IllegalStateException(); } return findFlowPart(graph, name) .orElseThrow(() -> new CommandConfigurationException(MessageFormat.format( STR{1}\STR, Optional.ofNullable(jobflow.getDescriptionClass()) .orElse(jobflow.getId()), name))); } | /**
* Returns the target flow-part operator view.
* @param jobflow the owner jobflow
* @param graph the target graph
* @return the target operator view
* @throws CommandConfigurationException if there is no such a flow-part
*/ | Returns the target flow-part operator view | select | {
"repo_name": "asakusafw/asakusafw",
"path": "info/cli/src/main/java/com/asakusafw/info/cli/common/FlowPartSelectorParameter.java",
"license": "apache-2.0",
"size": 3577
} | [
"com.asakusafw.info.JobflowInfo",
"com.asakusafw.info.operator.view.OperatorGraphView",
"com.asakusafw.info.operator.view.OperatorView",
"com.asakusafw.utils.jcommander.CommandConfigurationException",
"java.text.MessageFormat",
"java.util.Optional"
] | import com.asakusafw.info.JobflowInfo; import com.asakusafw.info.operator.view.OperatorGraphView; import com.asakusafw.info.operator.view.OperatorView; import com.asakusafw.utils.jcommander.CommandConfigurationException; import java.text.MessageFormat; import java.util.Optional; | import com.asakusafw.info.*; import com.asakusafw.info.operator.view.*; import com.asakusafw.utils.jcommander.*; import java.text.*; import java.util.*; | [
"com.asakusafw.info",
"com.asakusafw.utils",
"java.text",
"java.util"
] | com.asakusafw.info; com.asakusafw.utils; java.text; java.util; | 753,744 |
@Test
public void testMessageBodyIsParsed() throws Exception {
int[] fields = { MailInputField.COLUMN_BODY };
MailInputField[] farr = this.getDefaultInputFields( fields );
this.mockMailInputMeta( farr );
try {
mailInput.processRow( meta, data );
} catch ( KettleException e ) {
// don't worry about it
}
MessageParser underTest = mailInput.new MessageParser();
Object[] r = RowDataUtil.allocateRowData( data.nrFields );
underTest.parseToArray( r, message );
Assert.assertEquals( "Message Body is correct", MSG_BODY, String.class.cast( r[0] ) );
}
| void function() throws Exception { int[] fields = { MailInputField.COLUMN_BODY }; MailInputField[] farr = this.getDefaultInputFields( fields ); this.mockMailInputMeta( farr ); try { mailInput.processRow( meta, data ); } catch ( KettleException e ) { } MessageParser underTest = mailInput.new MessageParser(); Object[] r = RowDataUtil.allocateRowData( data.nrFields ); underTest.parseToArray( r, message ); Assert.assertEquals( STR, MSG_BODY, String.class.cast( r[0] ) ); } | /**
* Test that message body can be parsed correctly
*
* @throws Exception
*/ | Test that message body can be parsed correctly | testMessageBodyIsParsed | {
"repo_name": "rfellows/pentaho-kettle",
"path": "engine/test-src/org/pentaho/di/trans/steps/mailinput/ParseMailInputTest.java",
"license": "apache-2.0",
"size": 19951
} | [
"org.junit.Assert",
"org.pentaho.di.core.exception.KettleException",
"org.pentaho.di.core.row.RowDataUtil",
"org.pentaho.di.trans.steps.mailinput.MailInput"
] | import org.junit.Assert; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.trans.steps.mailinput.MailInput; | import org.junit.*; import org.pentaho.di.core.exception.*; import org.pentaho.di.core.row.*; import org.pentaho.di.trans.steps.mailinput.*; | [
"org.junit",
"org.pentaho.di"
] | org.junit; org.pentaho.di; | 268,832 |
public Path createTempFile(String prefix, String suffix) throws IOException
{
if (prefix == null || prefix.length () == 0)
prefix = "t";
if (suffix == null)
suffix = ".tmp";
synchronized (LOCK) {
for (int i = 0; i < 32768; i++) {
int r = Math.abs((int) RandomUtil.getRandomLong());
Path file = lookup(prefix + r + suffix);
if (file.createNewFile())
return file;
}
}
throw new IOException("cannot create temp file");
} | Path function(String prefix, String suffix) throws IOException { if (prefix == null prefix.length () == 0) prefix = "t"; if (suffix == null) suffix = ".tmp"; synchronized (LOCK) { for (int i = 0; i < 32768; i++) { int r = Math.abs((int) RandomUtil.getRandomLong()); Path file = lookup(prefix + r + suffix); if (file.createNewFile()) return file; } } throw new IOException(STR); } | /**
* Creates a unique temporary file as a child of this directory.
*
* @param prefix filename prefix
* @param suffix filename suffix, defaults to .tmp
* @return Path to the new file.
*/ | Creates a unique temporary file as a child of this directory | createTempFile | {
"repo_name": "CleverCloud/Quercus",
"path": "resin/src/main/java/com/caucho/vfs/Path.java",
"license": "gpl-2.0",
"size": 35252
} | [
"com.caucho.util.RandomUtil",
"java.io.IOException"
] | import com.caucho.util.RandomUtil; import java.io.IOException; | import com.caucho.util.*; import java.io.*; | [
"com.caucho.util",
"java.io"
] | com.caucho.util; java.io; | 2,690,208 |
private void parseStyles() throws ConverterException {
styleFonts = new Hashtable<String, String>();
cfTable = new Hashtable<String, String>();
for (int i = 0; i < styles.size(); i++) {
String style = styles.get(i);
StringTokenizer tk = new StringTokenizer(style, "\\{} \t", true); //$NON-NLS-1$
String control = ""; //$NON-NLS-1$
String value = ""; //$NON-NLS-1$
while (tk.hasMoreElements()) {
String token = tk.nextToken();
if (token.length() == 1) {
continue;
}
String ctl = getControl("\\" + token); //$NON-NLS-1$
if (ctl.equals("s") || // paragraph style //$NON-NLS-1$
ctl.equals("cs") || // character style //$NON-NLS-1$
ctl.equals("ts") || // table style //$NON-NLS-1$
ctl.equals("ds")) { // section style //$NON-NLS-1$
control = getValue("\\" + token); //$NON-NLS-1$
}
if (ctl.equals("f")) { //$NON-NLS-1$
value = getValue("\\" + token); //$NON-NLS-1$
}
}
if (!control.equals("") && !value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
if (fontTable.containsKey(value)) {
styleFonts.put(control, value);
} else {
MessageFormat mf = new MessageFormat(taggedRTF ? Messages.getString("rtf.Rtf2Xliff.msg5") : Messages.getString("rtf.Rtf2Xliff.msg1")); //$NON-NLS-1$
Object[] args = { value };
String msg = mf.format(args);
System.err.println(msg);
args = null;
fontTable.put(control, "0"); //$NON-NLS-1$
// throw new ConverterException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg));
}
}
cfTable.put(getStyle(style), getValue("cf", style)); //$NON-NLS-1$
}
}
| void function() throws ConverterException { styleFonts = new Hashtable<String, String>(); cfTable = new Hashtable<String, String>(); for (int i = 0; i < styles.size(); i++) { String style = styles.get(i); StringTokenizer tk = new StringTokenizer(style, STR, true); String control = STRSTR\\STRsSTRcsSTRtsSTRdsSTR\\STRfSTR\\STRSTRSTRrtf.Rtf2Xliff.msg5STRrtf.Rtf2Xliff.msg1STR0STRcf", style)); } } | /**
* Parses the styles.
* @throws ConverterException
*/ | Parses the styles | parseStyles | {
"repo_name": "heartsome/tmxeditor8",
"path": "hsconverter/net.heartsome.cat.converter.rtf/src/net/heartsome/cat/converter/rtf/Rtf2Xliff.java",
"license": "gpl-2.0",
"size": 96309
} | [
"java.util.Hashtable",
"java.util.StringTokenizer",
"net.heartsome.cat.converter.ConverterException"
] | import java.util.Hashtable; import java.util.StringTokenizer; import net.heartsome.cat.converter.ConverterException; | import java.util.*; import net.heartsome.cat.converter.*; | [
"java.util",
"net.heartsome.cat"
] | java.util; net.heartsome.cat; | 2,540,791 |
public static double calcWidthOnScreen(ChartPanel myChart, double dataWidth, ValueAxis axis,
RectangleEdge axisEdge) {
XYPlot plot = (XYPlot) myChart.getChart().getPlot();
ChartRenderingInfo info = myChart.getChartRenderingInfo();
Rectangle2D dataArea = info.getPlotInfo().getDataArea();
double width2D = axis.lengthToJava2D(dataWidth, dataArea, axisEdge);
return width2D;
} | static double function(ChartPanel myChart, double dataWidth, ValueAxis axis, RectangleEdge axisEdge) { XYPlot plot = (XYPlot) myChart.getChart().getPlot(); ChartRenderingInfo info = myChart.getChartRenderingInfo(); Rectangle2D dataArea = info.getPlotInfo().getDataArea(); double width2D = axis.lengthToJava2D(dataWidth, dataArea, axisEdge); return width2D; } | /**
* Data width to pixel width on screen
*
* @param myChart
* @param dataWidth width of data
* @param axis for width calculation
* @return
*/ | Data width to pixel width on screen | calcWidthOnScreen | {
"repo_name": "tomas-pluskal/mzmine3",
"path": "src/main/java/io/github/mzmine/gui/chartbasics/ChartLogics.java",
"license": "gpl-2.0",
"size": 27467
} | [
"java.awt.geom.Rectangle2D",
"org.jfree.chart.ChartPanel",
"org.jfree.chart.ChartRenderingInfo",
"org.jfree.chart.axis.ValueAxis",
"org.jfree.chart.plot.XYPlot",
"org.jfree.chart.ui.RectangleEdge"
] | import java.awt.geom.Rectangle2D; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.ui.RectangleEdge; | import java.awt.geom.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.*; import org.jfree.chart.ui.*; | [
"java.awt",
"org.jfree.chart"
] | java.awt; org.jfree.chart; | 423,335 |
@SuppressWarnings("unchecked")
public static Coche seleccionarCoche(String modelo) {
Coche c;
List<Coche> listaCoches;
EntityManager em = factoria.createEntityManager();
// Hacemos la consulta.
Query q = em.createQuery("SELECT u FROM Coche u WHERE u.modelo = :modelo");
q.setParameter("modelo",modelo);
// Anotamos el resultado.
listaCoches = q.getResultList();
if(listaCoches.size() != 0)
c = listaCoches.get(0);
else
return null;
// Cerramos el gestor.
em.close();
return c;
}
| @SuppressWarnings(STR) static Coche function(String modelo) { Coche c; List<Coche> listaCoches; EntityManager em = factoria.createEntityManager(); Query q = em.createQuery(STR); q.setParameter(STR,modelo); listaCoches = q.getResultList(); if(listaCoches.size() != 0) c = listaCoches.get(0); else return null; em.close(); return c; } | /**
* Selecciona un coche dado el modelo.
*
* @param modelo : Indica el modelo del coche que se va a devolver.
* @return Devuelve un objeto Coche con el 'modelo' pasado por
* par�metro que se encuentra en la base de datos.
* Si no existe devuelve 'null'.
* */ | Selecciona un coche dado el modelo | seleccionarCoche | {
"repo_name": "alvaromm/CarService",
"path": "CarService/src/paquete/CocheDB.java",
"license": "gpl-2.0",
"size": 8610
} | [
"java.util.List",
"javax.persistence.EntityManager",
"javax.persistence.Query"
] | import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; | import java.util.*; import javax.persistence.*; | [
"java.util",
"javax.persistence"
] | java.util; javax.persistence; | 1,684,105 |
@Override
public void updateProcessTree() {
if (!pid.equals(deadPid)) {
// Get the list of processes
List<String> processList = getProcessList();
Map<String, ProcessInfo> allProcessInfo = new HashMap<String, ProcessInfo>();
// cache the processTree to get the age for processes
Map<String, ProcessInfo> oldProcs =
new HashMap<String, ProcessInfo>(processTree);
processTree.clear();
ProcessInfo me = null;
for (String proc : processList) {
// Get information for each process
ProcessInfo pInfo = new ProcessInfo(proc);
if (constructProcessInfo(pInfo, procfsDir) != null) {
allProcessInfo.put(proc, pInfo);
if (proc.equals(this.pid)) {
me = pInfo; // cache 'me'
processTree.put(proc, pInfo);
}
}
}
if (me == null) {
return;
}
// Add each process to its parent.
for (Map.Entry<String, ProcessInfo> entry : allProcessInfo.entrySet()) {
String pID = entry.getKey();
if (!pID.equals("1")) {
ProcessInfo pInfo = entry.getValue();
ProcessInfo parentPInfo = allProcessInfo.get(pInfo.getPpid());
if (parentPInfo != null) {
parentPInfo.addChild(pInfo);
}
}
}
// now start constructing the process-tree
LinkedList<ProcessInfo> pInfoQueue = new LinkedList<ProcessInfo>();
pInfoQueue.addAll(me.getChildren());
while (!pInfoQueue.isEmpty()) {
ProcessInfo pInfo = pInfoQueue.remove();
if (!processTree.containsKey(pInfo.getPid())) {
processTree.put(pInfo.getPid(), pInfo);
}
pInfoQueue.addAll(pInfo.getChildren());
}
// update age values and compute the number of jiffies since last update
for (Map.Entry<String, ProcessInfo> procs : processTree.entrySet()) {
ProcessInfo oldInfo = oldProcs.get(procs.getKey());
if (procs.getValue() != null) {
procs.getValue().updateJiffy(oldInfo);
if (oldInfo != null) {
procs.getValue().updateAge(oldInfo);
}
}
}
if (LOG.isDebugEnabled()) {
// Log.debug the ProcfsBasedProcessTree
LOG.debug(this.toString());
}
}
} | void function() { if (!pid.equals(deadPid)) { List<String> processList = getProcessList(); Map<String, ProcessInfo> allProcessInfo = new HashMap<String, ProcessInfo>(); Map<String, ProcessInfo> oldProcs = new HashMap<String, ProcessInfo>(processTree); processTree.clear(); ProcessInfo me = null; for (String proc : processList) { ProcessInfo pInfo = new ProcessInfo(proc); if (constructProcessInfo(pInfo, procfsDir) != null) { allProcessInfo.put(proc, pInfo); if (proc.equals(this.pid)) { me = pInfo; processTree.put(proc, pInfo); } } } if (me == null) { return; } for (Map.Entry<String, ProcessInfo> entry : allProcessInfo.entrySet()) { String pID = entry.getKey(); if (!pID.equals("1")) { ProcessInfo pInfo = entry.getValue(); ProcessInfo parentPInfo = allProcessInfo.get(pInfo.getPpid()); if (parentPInfo != null) { parentPInfo.addChild(pInfo); } } } LinkedList<ProcessInfo> pInfoQueue = new LinkedList<ProcessInfo>(); pInfoQueue.addAll(me.getChildren()); while (!pInfoQueue.isEmpty()) { ProcessInfo pInfo = pInfoQueue.remove(); if (!processTree.containsKey(pInfo.getPid())) { processTree.put(pInfo.getPid(), pInfo); } pInfoQueue.addAll(pInfo.getChildren()); } for (Map.Entry<String, ProcessInfo> procs : processTree.entrySet()) { ProcessInfo oldInfo = oldProcs.get(procs.getKey()); if (procs.getValue() != null) { procs.getValue().updateJiffy(oldInfo); if (oldInfo != null) { procs.getValue().updateAge(oldInfo); } } } if (LOG.isDebugEnabled()) { LOG.debug(this.toString()); } } } | /**
* Update process-tree with latest state. If the root-process is not alive,
* tree will be empty.
*
*/ | Update process-tree with latest state. If the root-process is not alive, tree will be empty | updateProcessTree | {
"repo_name": "moreus/hadoop",
"path": "hadoop-0.23.10/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/ProcfsBasedProcessTree.java",
"license": "apache-2.0",
"size": 18765
} | [
"java.util.HashMap",
"java.util.LinkedList",
"java.util.List",
"java.util.Map"
] | import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 2,769,552 |
public void handleImportedWorkflow(FileUploadEvent event) {
try {
final String path = ConfigurationRepository.TEMPORARY_WORKFLOW_PATH + event.getFile().getFileName();
final File workflowFile = new File(path);
try (
final BufferedReader br = new BufferedReader(new FileReader(workflowFile));) {
final StringBuilder builder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
}
final ObjectMapper mapper = new ObjectMapper();
final Workflow workflow = mapper.readValue(builder.toString(), Workflow.class);
System.out.println("Tamanho: " + workflow.getJobs().size());
System.out.println("Descriçao: " + workflow.getDescription());
System.out.println("UserId: " + workflow.getUserId());
}
} catch (final Exception ex) {
LOGGER.error("[Exception] - " + ex.getMessage());
}
}
/**
* COMMENTED BECAUSE IT IS BEEN PASSED DIRECTLY TO THE SERVER (WITHOUT SAVE
* IN DISK) Saves temporary file in disk
*
* @param fileName
* @param in
* @return public String saveTempFile(String fileName, InputStream in)
* throws FileNotFoundException, IOException { String path =
* ConfigurationRepository.TEMPORARY_WORKFLOW_PATH + fileName; // write the
* inputStream to a FileOutputStream OutputStream outputStream = new
* FileOutputStream(new File(path));
*
* int read = 0; byte[] bytes = new byte[1024];
*
* while ((read = in.read(bytes)) != -1) { outputStream.write(bytes, 0,
* read); }
*
* // in.close(); LOGGER.info("Temporary file created [path=" +
* ConfigurationRepository.UPLOADED_FILES_PATH + fileName + "]");
*
* return path; } | void function(FileUploadEvent event) { try { final String path = ConfigurationRepository.TEMPORARY_WORKFLOW_PATH + event.getFile().getFileName(); final File workflowFile = new File(path); try ( final BufferedReader br = new BufferedReader(new FileReader(workflowFile));) { final StringBuilder builder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { builder.append(line); } final ObjectMapper mapper = new ObjectMapper(); final Workflow workflow = mapper.readValue(builder.toString(), Workflow.class); System.out.println(STR + workflow.getJobs().size()); System.out.println(STR + workflow.getDescription()); System.out.println(STR + workflow.getUserId()); } } catch (final Exception ex) { LOGGER.error(STR + ex.getMessage()); } } /** * COMMENTED BECAUSE IT IS BEEN PASSED DIRECTLY TO THE SERVER (WITHOUT SAVE * IN DISK) Saves temporary file in disk * * @param fileName * @param in * @return public String saveTempFile(String fileName, InputStream in) * throws FileNotFoundException, IOException { String path = * ConfigurationRepository.TEMPORARY_WORKFLOW_PATH + fileName; * inputStream to a FileOutputStream OutputStream outputStream = new * FileOutputStream(new File(path)); * * int read = 0; byte[] bytes = new byte[1024]; * * while ((read = in.read(bytes)) != -1) { outputStream.write(bytes, 0, * read); } * * * ConfigurationRepository.UPLOADED_FILES_PATH + fileName + "]"); * * return path; } | /**
* Called when an user clicks to import a workflow file to application
*
* @param event
*/ | Called when an user clicks to import a workflow file to application | handleImportedWorkflow | {
"repo_name": "bionimbuz/BionimbuzClient",
"path": "src/main/java/br/unb/cic/bionimbuz/web/beans/WorkflowComposerBean.java",
"license": "gpl-3.0",
"size": 35581
} | [
"br.unb.cic.bionimbuz.configuration.ConfigurationRepository",
"br.unb.cic.bionimbuz.model.Workflow",
"com.fasterxml.jackson.databind.ObjectMapper",
"java.io.BufferedReader",
"java.io.File",
"java.io.FileReader",
"java.io.IOException",
"org.primefaces.event.FileUploadEvent"
] | import br.unb.cic.bionimbuz.configuration.ConfigurationRepository; import br.unb.cic.bionimbuz.model.Workflow; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.primefaces.event.FileUploadEvent; | import br.unb.cic.bionimbuz.configuration.*; import br.unb.cic.bionimbuz.model.*; import com.fasterxml.jackson.databind.*; import java.io.*; import org.primefaces.event.*; | [
"br.unb.cic",
"com.fasterxml.jackson",
"java.io",
"org.primefaces.event"
] | br.unb.cic; com.fasterxml.jackson; java.io; org.primefaces.event; | 2,023,870 |
public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List<Group> hetatms1, List<Group> hetatms2 ) throws StructureException {
List<Atom> twistedAs = new ArrayList<Atom>();
for ( Group g: twistedGroups){
if ( g == null )
continue;
if ( g.size() < 1)
continue;
Atom a = g.getAtom(0);
twistedAs.add(a);
}
Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]);
twistedAtoms = StructureTools.cloneAtomArray(twistedAtoms);
Atom[] arr1 = getAtomArray(ca1, hetatms1);
Atom[] arr2 = getAtomArray(twistedAtoms, hetatms2);
//
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
String title = afpChain.getAlgorithmName() + " V." +afpChain.getVersion() + " : " + afpChain.getName1() + " vs. " + afpChain.getName2();
//System.out.println(artificial.toPDB());
StructureAlignmentJmol jmol = new StructureAlignmentJmol(afpChain,arr1,arr2);
//jmol.setStructure(artificial);
System.out.format("CA2[0]=(%.2f,%.2f,%.2f)%n", arr2[0].getX(), arr2[0].getY(), arr2[0].getZ());
//jmol.setTitle("Structure Alignment: " + afpChain.getName1() + " vs. " + afpChain.getName2());
jmol.setTitle(title);
return jmol;
} | static final StructureAlignmentJmol function(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List<Group> hetatms1, List<Group> hetatms2 ) throws StructureException { List<Atom> twistedAs = new ArrayList<Atom>(); for ( Group g: twistedGroups){ if ( g == null ) continue; if ( g.size() < 1) continue; Atom a = g.getAtom(0); twistedAs.add(a); } Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); twistedAtoms = StructureTools.cloneAtomArray(twistedAtoms); Atom[] arr1 = getAtomArray(ca1, hetatms1); Atom[] arr2 = getAtomArray(twistedAtoms, hetatms2); String title = afpChain.getAlgorithmName() + STR +afpChain.getVersion() + STR + afpChain.getName1() + STR + afpChain.getName2(); StructureAlignmentJmol jmol = new StructureAlignmentJmol(afpChain,arr1,arr2); System.out.format(STR, arr2[0].getX(), arr2[0].getY(), arr2[0].getZ()); jmol.setTitle(title); return jmol; } | /** Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here...
* */ | Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here.. | display | {
"repo_name": "andreasprlic/biojava",
"path": "biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java",
"license": "lgpl-2.1",
"size": 15417
} | [
"java.util.ArrayList",
"java.util.List",
"org.biojava.nbio.structure.Atom",
"org.biojava.nbio.structure.Group",
"org.biojava.nbio.structure.StructureException",
"org.biojava.nbio.structure.StructureTools",
"org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol",
"org.biojava.nbio.structure.align.model.AFPChain"
] | import java.util.ArrayList; import java.util.List; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.align.model.AFPChain; | import java.util.*; import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.jmol.*; import org.biojava.nbio.structure.align.model.*; | [
"java.util",
"org.biojava.nbio"
] | java.util; org.biojava.nbio; | 790,860 |
public BlockConfig getBlockConfig() {
return (BlockConfig) configurations.get(ConfigType.BLOCKS);
}
| BlockConfig function() { return (BlockConfig) configurations.get(ConfigType.BLOCKS); } | /**
* returns the block configuration
*
* @author xize
* @return BlockConfig
*/ | returns the block configuration | getBlockConfig | {
"repo_name": "xEssentials/xEssentials",
"path": "src/tv/mineinthebox/essentials/GlobalConfiguration.java",
"license": "gpl-3.0",
"size": 10967
} | [
"tv.mineinthebox.essentials.configurations.BlockConfig",
"tv.mineinthebox.essentials.enums.ConfigType"
] | import tv.mineinthebox.essentials.configurations.BlockConfig; import tv.mineinthebox.essentials.enums.ConfigType; | import tv.mineinthebox.essentials.configurations.*; import tv.mineinthebox.essentials.enums.*; | [
"tv.mineinthebox.essentials"
] | tv.mineinthebox.essentials; | 960,136 |
public java_cup.runtime.Symbol next_token() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
boolean zzR = false;
for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;
zzCurrentPosL++) {
switch (zzBufferL[zzCurrentPosL]) {
case '\u000B':
case '\u000C':
case '\u0085':
case '\u2028':
case '\u2029':
yyline++;
yycolumn = 0;
zzR = false;
break;
case '\r':
yyline++;
yycolumn = 0;
zzR = true;
break;
case '\n':
if (zzR)
zzR = false;
else {
yyline++;
yycolumn = 0;
}
break;
default:
zzR = false;
yycolumn++;
}
}
if (zzR) {
// peek one character ahead if it is \n (if we have counted one line too much)
boolean zzPeek;
if (zzMarkedPosL < zzEndReadL)
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
else if (zzAtEOF)
zzPeek = false;
else {
boolean eof = zzRefill();
zzEndReadL = zzEndRead;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
if (eof)
zzPeek = false;
else
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
}
if (zzPeek) yyline--;
}
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 14:
{ string.append('\n');
}
case 26: break;
case 23:
{ return symbol(Sym_file.CONTACTOS);
}
case 27: break;
case 16:
{ return symbol(Sym_file.FECHA);
}
case 28: break;
case 9:
{ string.append( yytext() );
}
case 29: break;
case 22:
{ return symbol(Sym_file.PASSWORD);
}
case 30: break;
case 17:
{ return symbol(Sym_file.EMISOR);
}
case 31: break;
case 20:
{ return symbol(Sym_file.MENSAJE);
}
case 32: break;
case 21:
{ return symbol(Sym_file.RECEPTOR);
}
case 33: break;
case 11:
{ string.append('\\');
}
case 34: break;
case 8:
{ return symbol(Sym_file.PCOMA);
}
case 35: break;
case 18:
{ return symbol(Sym_file.CUENTA);
}
case 36: break;
case 3:
{ return symbol(Sym_file.INT);
}
case 37: break;
case 25:
{ return symbol(Sym_file.FECHA_HORA);
}
case 38: break;
case 10:
{ yybegin(YYINITIAL);
return symbol(Sym_file.CONTENIDO,string.toString());
}
case 39: break;
case 13:
{ string.append('\r');
}
case 40: break;
case 15:
{ string.append('\"');
}
case 41: break;
case 6:
{ return symbol(Sym_file.RP);
}
case 42: break;
case 4:
{ return symbol(Sym_file.ID);
}
case 43: break;
case 19:
{ return symbol(Sym_file.USUARIO);
}
case 44: break;
case 1:
{ error("Illegal character.");
}
case 45: break;
case 5:
{ return symbol(Sym_file.LP);
}
case 46: break;
case 7:
{ return symbol(Sym_file.EQUAL);
}
case 47: break;
case 12:
{ string.append('\t');
}
case 48: break;
case 24:
{ string.setLength(0);yybegin(YYCONTENIDO);
}
case 49: break;
case 2:
{
}
case 50: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
zzDoEOF();
{
return symbol(Sym_file.EOF);
}
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
} | java_cup.runtime.Symbol function() throws java.io.IOException { int zzInput; int zzAction; int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; boolean zzR = false; for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; zzCurrentPosL++) { switch (zzBufferL[zzCurrentPosL]) { case '\u000B': case '\u000C': case '\u0085': case '\u2028': case '\u2029': yyline++; yycolumn = 0; zzR = false; break; case '\r': yyline++; yycolumn = 0; zzR = true; break; case '\n': if (zzR) zzR = false; else { yyline++; yycolumn = 0; } break; default: zzR = false; yycolumn++; } } if (zzR) { boolean zzPeek; if (zzMarkedPosL < zzEndReadL) zzPeek = zzBufferL[zzMarkedPosL] == '\n'; else if (zzAtEOF) zzPeek = false; else { boolean eof = zzRefill(); zzEndReadL = zzEndRead; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; if (eof) zzPeek = false; else zzPeek = zzBufferL[zzMarkedPosL] == '\n'; } if (zzPeek) yyline--; } zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 14: { string.append('\n'); } case 26: break; case 23: { return symbol(Sym_file.CONTACTOS); } case 27: break; case 16: { return symbol(Sym_file.FECHA); } case 28: break; case 9: { string.append( yytext() ); } case 29: break; case 22: { return symbol(Sym_file.PASSWORD); } case 30: break; case 17: { return symbol(Sym_file.EMISOR); } case 31: break; case 20: { return symbol(Sym_file.MENSAJE); } case 32: break; case 21: { return symbol(Sym_file.RECEPTOR); } case 33: break; case 11: { string.append('\\'); } case 34: break; case 8: { return symbol(Sym_file.PCOMA); } case 35: break; case 18: { return symbol(Sym_file.CUENTA); } case 36: break; case 3: { return symbol(Sym_file.INT); } case 37: break; case 25: { return symbol(Sym_file.FECHA_HORA); } case 38: break; case 10: { yybegin(YYINITIAL); return symbol(Sym_file.CONTENIDO,string.toString()); } case 39: break; case 13: { string.append('\r'); } case 40: break; case 15: { string.append('\STRIllegal character."); } case 45: break; case 5: { return symbol(Sym_file.LP); } case 46: break; case 7: { return symbol(Sym_file.EQUAL); } case 47: break; case 12: { string.append('\t'); } case 48: break; case 24: { string.setLength(0);yybegin(YYCONTENIDO); } case 49: break; case 2: { } case 50: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; zzDoEOF(); { return symbol(Sym_file.EOF); } } else { zzScanError(ZZ_NO_MATCH); } } } } | /**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/ | Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error occurs | next_token | {
"repo_name": "mayace/mensajeria",
"path": "src/com/github/mensajeria/compiler/servidor/Scanner_file.java",
"license": "gpl-2.0",
"size": 27978
} | [
"java_cup.runtime.Symbol"
] | import java_cup.runtime.Symbol; | import java_cup.runtime.*; | [
"java_cup.runtime"
] | java_cup.runtime; | 1,411,834 |
@Override
public B must(@Nonnull final String key, boolean value) {
mandatoryKeys.add(key);
options.setBoolean(key, value);
return getThisBuilder();
} | B function(@Nonnull final String key, boolean value) { mandatoryKeys.add(key); options.setBoolean(key, value); return getThisBuilder(); } | /**
* Set mandatory boolean option.
*
* @see #must(String, String)
*/ | Set mandatory boolean option | must | {
"repo_name": "apurtell/hadoop",
"path": "hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/impl/AbstractFSBuilderImpl.java",
"license": "apache-2.0",
"size": 10278
} | [
"javax.annotation.Nonnull"
] | import javax.annotation.Nonnull; | import javax.annotation.*; | [
"javax.annotation"
] | javax.annotation; | 1,893,178 |
RegistryClientEntity createRegistryClient(Revision revision, RegistryDTO registryDTO); | RegistryClientEntity createRegistryClient(Revision revision, RegistryDTO registryDTO); | /**
* Creates a registry.
*
* @param revision revision
* @param registryDTO The registry DTO
* @return The reporting task DTO
*/ | Creates a registry | createRegistryClient | {
"repo_name": "mcgilman/nifi",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java",
"license": "apache-2.0",
"size": 85713
} | [
"org.apache.nifi.web.api.dto.RegistryDTO",
"org.apache.nifi.web.api.entity.RegistryClientEntity"
] | import org.apache.nifi.web.api.dto.RegistryDTO; import org.apache.nifi.web.api.entity.RegistryClientEntity; | import org.apache.nifi.web.api.dto.*; import org.apache.nifi.web.api.entity.*; | [
"org.apache.nifi"
] | org.apache.nifi; | 2,542,550 |
public static List<Op> reversePolish(List<Op> tokens) {
List<Op> segments = new ArrayList<Op>();
Stack<Operator> operatorStack = new Stack<Operator>();
for (int i = 0; i < tokens.size(); i++) {
Op token = tokens.get(i);
if (isOperand(token)) {
segments.add(token);
} else if (isLeftParenthesis(token)) {
operatorStack.push((Operator) token);
} else if (isRightParenthesis(token)) {
Operator opNew = null;
while (!operatorStack.empty() && LEFTPARENTHESIS != (opNew = operatorStack.pop())) {
segments.add(opNew);
}
if (null == opNew || LEFTPARENTHESIS != opNew)
throw new IllegalArgumentException("mismatched parentheses");
} else if (isOperator(token)) {
Operator opNew = (Operator) token;
if (!operatorStack.empty()) {
Operator opOld = operatorStack.peek();
if (opOld.isCompareable() && opNew.compare(opOld) != 1) {
segments.add(operatorStack.pop());
}
}
operatorStack.push(opNew);
} else
throw new IllegalArgumentException("illegal token " + token);
}
while (!operatorStack.empty()) {
Operator operator = operatorStack.pop();
if (LEFTPARENTHESIS == operator || RIGHTPARENTHESIS == operator)
throw new IllegalArgumentException("mismatched parentheses " + operator);
segments.add(operator);
}
return segments;
} | static List<Op> function(List<Op> tokens) { List<Op> segments = new ArrayList<Op>(); Stack<Operator> operatorStack = new Stack<Operator>(); for (int i = 0; i < tokens.size(); i++) { Op token = tokens.get(i); if (isOperand(token)) { segments.add(token); } else if (isLeftParenthesis(token)) { operatorStack.push((Operator) token); } else if (isRightParenthesis(token)) { Operator opNew = null; while (!operatorStack.empty() && LEFTPARENTHESIS != (opNew = operatorStack.pop())) { segments.add(opNew); } if (null == opNew LEFTPARENTHESIS != opNew) throw new IllegalArgumentException(STR); } else if (isOperator(token)) { Operator opNew = (Operator) token; if (!operatorStack.empty()) { Operator opOld = operatorStack.peek(); if (opOld.isCompareable() && opNew.compare(opOld) != 1) { segments.add(operatorStack.pop()); } } operatorStack.push(opNew); } else throw new IllegalArgumentException(STR + token); } while (!operatorStack.empty()) { Operator operator = operatorStack.pop(); if (LEFTPARENTHESIS == operator RIGHTPARENTHESIS == operator) throw new IllegalArgumentException(STR + operator); segments.add(operator); } return segments; } | /**
* Shunting-yard algorithm <br/>
* http://en.wikipedia.org/wiki/Shunting_yard_algorithm
*
* @param tokens
* @return the compute result of Shunting-yard algorithm
*/ | Shunting-yard algorithm HREF | reversePolish | {
"repo_name": "Todd-start/RocketMQ",
"path": "common/src/main/java/org/apache/rocketmq/common/filter/impl/PolishExpr.java",
"license": "apache-2.0",
"size": 7000
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.Stack"
] | import java.util.ArrayList; import java.util.List; import java.util.Stack; | import java.util.*; | [
"java.util"
] | java.util; | 2,391,783 |
private boolean checkServerStatus(Set<String> errors) {
boolean isResponsive = true;
HttpURLConnection engineConn = null;
try {
engineConn = (HttpURLConnection) serverUrl.openConnection();
if (isHttpsProtocol) {
((HttpsURLConnection) engineConn).setSSLSocketFactory(sslFactory);
if (sslIgnoreHostVerification) {
((HttpsURLConnection) engineConn).setHostnameVerifier(IgnoredHostnameVerifier);
}
}
} catch (IOException e) {
errors.add(e.getMessage());
isResponsive = false;
}
if (isResponsive) {
try {
int responseCode = engineConn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
isResponsive = false;
log.debug("Server is non responsive with response code: {}", responseCode);
}
} catch (Exception e) {
errors.add(e.getMessage());
isResponsive = false;
} finally {
if (engineConn != null) {
engineConn.disconnect();
engineConn = null;
}
}
}
log.debug("checkServerStatus return: {}", isResponsive);
return isResponsive;
}
/**
* Adds an event to audit_log table, representing server status
* @param eventType
* {@code AuditLogType.VDC_START} or {@code AuditLogType.VDC_STOP} events
* @param eventId
* id associated with {@code eventType} parameter
* @param severity
* severity associated with eventType, values are taken from {@code AuditLogSeverity} | boolean function(Set<String> errors) { boolean isResponsive = true; HttpURLConnection engineConn = null; try { engineConn = (HttpURLConnection) serverUrl.openConnection(); if (isHttpsProtocol) { ((HttpsURLConnection) engineConn).setSSLSocketFactory(sslFactory); if (sslIgnoreHostVerification) { ((HttpsURLConnection) engineConn).setHostnameVerifier(IgnoredHostnameVerifier); } } } catch (IOException e) { errors.add(e.getMessage()); isResponsive = false; } if (isResponsive) { try { int responseCode = engineConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { isResponsive = false; log.debug(STR, responseCode); } } catch (Exception e) { errors.add(e.getMessage()); isResponsive = false; } finally { if (engineConn != null) { engineConn.disconnect(); engineConn = null; } } } log.debug(STR, isResponsive); return isResponsive; } /** * Adds an event to audit_log table, representing server status * @param eventType * {@code AuditLogType.VDC_START} or {@code AuditLogType.VDC_STOP} events * @param eventId * id associated with {@code eventType} parameter * @param severity * severity associated with eventType, values are taken from {@code AuditLogSeverity} | /**
* Examines the status of the backend engine server
*
* @param serverUrl
* the engine server url of Health Servlet
* @param errors
* collection which aggregates any error
* @return true is engine server is responsive (response with code 200 - HTTP_OK), else false
*/ | Examines the status of the backend engine server | checkServerStatus | {
"repo_name": "OpenUniversity/ovirt-engine",
"path": "backend/manager/tools/src/main/java/org/ovirt/engine/core/notifier/EngineMonitorService.java",
"license": "apache-2.0",
"size": 17419
} | [
"java.io.IOException",
"java.net.HttpURLConnection",
"java.util.Set",
"javax.net.ssl.HttpsURLConnection",
"org.ovirt.engine.core.common.AuditLogSeverity",
"org.ovirt.engine.core.common.AuditLogType"
] | import java.io.IOException; import java.net.HttpURLConnection; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import org.ovirt.engine.core.common.AuditLogSeverity; import org.ovirt.engine.core.common.AuditLogType; | import java.io.*; import java.net.*; import java.util.*; import javax.net.ssl.*; import org.ovirt.engine.core.common.*; | [
"java.io",
"java.net",
"java.util",
"javax.net",
"org.ovirt.engine"
] | java.io; java.net; java.util; javax.net; org.ovirt.engine; | 253,411 |
@Test
public void testInt16() {
Short[] vals =
{ Short.MIN_VALUE, Short.MIN_VALUE / 2, 0, Short.MAX_VALUE / 2, Short.MAX_VALUE };
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[3 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 3 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
3, OrderedBytes.encodeInt16(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising serialized length.", 3, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
assertEquals("Buffer overflow.", 0, a[a.length - 1]);
// verify skip
buf1.setPosition(1);
assertEquals("Surprising return value.", 3, OrderedBytes.skip(buf1));
assertEquals("Did not skip enough bytes.", 3, buf1.getPosition() - 1);
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
vals[i].shortValue(), OrderedBytes.decodeInt16(buf1));
assertEquals("Did not consume enough bytes.", 3, buf1.getPosition() - 1);
}
}
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
byte[][] encoded = new byte[vals.length][3];
PositionedByteRange pbr = new SimplePositionedMutableByteRange();
for (int i = 0; i < vals.length; i++) {
OrderedBytes.encodeInt16(pbr.set(encoded[i]), vals[i], ord);
}
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Short[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
for (int i = 0; i < sortedVals.length; i++) {
int decoded = OrderedBytes.decodeInt16(pbr.set(encoded[i]));
assertEquals(
String.format(
"Encoded representations do not preserve natural order: <%s>, <%s>, %s",
sortedVals[i], decoded, ord),
sortedVals[i].shortValue(), decoded);
}
}
} | void function() { Short[] vals = { Short.MIN_VALUE, Short.MIN_VALUE / 2, 0, Short.MAX_VALUE / 2, Short.MAX_VALUE }; for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) { for (int i = 0; i < vals.length; i++) { byte[] a = new byte[3 + 3]; PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 3 + 1); buf1.setPosition(1); assertEquals(STR, 3, OrderedBytes.encodeInt16(buf1, vals[i], ord)); assertEquals(STR, buf1.getLength(), buf1.getPosition()); assertEquals(STR, 3, buf1.getPosition() - 1); assertEquals(STR, 0, a[0]); assertEquals(STR, 0, a[1]); assertEquals(STR, 0, a[a.length - 1]); buf1.setPosition(1); assertEquals(STR, 3, OrderedBytes.skip(buf1)); assertEquals(STR, 3, buf1.getPosition() - 1); buf1.setPosition(1); assertEquals(STR, vals[i].shortValue(), OrderedBytes.decodeInt16(buf1)); assertEquals(STR, 3, buf1.getPosition() - 1); } } for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) { byte[][] encoded = new byte[vals.length][3]; PositionedByteRange pbr = new SimplePositionedMutableByteRange(); for (int i = 0; i < vals.length; i++) { OrderedBytes.encodeInt16(pbr.set(encoded[i]), vals[i], ord); } Arrays.sort(encoded, Bytes.BYTES_COMPARATOR); Short[] sortedVals = Arrays.copyOf(vals, vals.length); if (ord == Order.ASCENDING) Arrays.sort(sortedVals); else Arrays.sort(sortedVals, Collections.reverseOrder()); for (int i = 0; i < sortedVals.length; i++) { int decoded = OrderedBytes.decodeInt16(pbr.set(encoded[i])); assertEquals( String.format( STR, sortedVals[i], decoded, ord), sortedVals[i].shortValue(), decoded); } } } | /**
* Test int16 encoding.
*/ | Test int16 encoding | testInt16 | {
"repo_name": "ultratendency/hbase",
"path": "hbase-common/src/test/java/org/apache/hadoop/hbase/util/TestOrderedBytes.java",
"license": "apache-2.0",
"size": 51263
} | [
"java.util.Arrays",
"java.util.Collections",
"org.junit.Assert"
] | import java.util.Arrays; import java.util.Collections; import org.junit.Assert; | import java.util.*; import org.junit.*; | [
"java.util",
"org.junit"
] | java.util; org.junit; | 1,305,610 |
public void notifyAttackedObservers(Creature creature) {
notifyObservers(ObserverType.ATTACKED, creature);
}
| void function(Creature creature) { notifyObservers(ObserverType.ATTACKED, creature); } | /**
* notify that creature attacked
*/ | notify that creature attacked | notifyAttackedObservers | {
"repo_name": "GiGatR00n/Aion-Core-v4.7.5",
"path": "AC-Game/src/com/aionemu/gameserver/controllers/ObserveController.java",
"license": "gpl-2.0",
"size": 11944
} | [
"com.aionemu.gameserver.controllers.observer.ObserverType",
"com.aionemu.gameserver.model.gameobjects.Creature"
] | import com.aionemu.gameserver.controllers.observer.ObserverType; import com.aionemu.gameserver.model.gameobjects.Creature; | import com.aionemu.gameserver.controllers.observer.*; import com.aionemu.gameserver.model.gameobjects.*; | [
"com.aionemu.gameserver"
] | com.aionemu.gameserver; | 1,830,997 |
@Test(enabled = true, dependsOnMethods = { "createSuitabilityLUTest" }, groups = {
"setup", "service" }, expectedExceptions = InvalidLabelException.class)
public void createBadSuitabilityLU2Test() throws Exception {
SuitabilityLU suitabilityLU = new SuitabilityLU();
suitabilityLU.setLabel(suitabilityLULabel);
suitabilityLU.setProjectId(newProjectId);
suitabilityLU = suitabilityLUService.createSuitabilityLU(suitabilityLU,
newProjectId);
} | @Test(enabled = true, dependsOnMethods = { STR }, groups = { "setup", STR }, expectedExceptions = InvalidLabelException.class) void function() throws Exception { SuitabilityLU suitabilityLU = new SuitabilityLU(); suitabilityLU.setLabel(suitabilityLULabel); suitabilityLU.setProjectId(newProjectId); suitabilityLU = suitabilityLUService.createSuitabilityLU(suitabilityLU, newProjectId); } | /**
* Creates the bad suitability l u2 test.
*
* @throws Exception
* the exception
*/ | Creates the bad suitability l u2 test | createBadSuitabilityLU2Test | {
"repo_name": "tosseto/online-whatif",
"path": "src/test/java/au/org/aurin/wif/svc/suitability/SuitabilityLUServiceIT.java",
"license": "mit",
"size": 8888
} | [
"au.org.aurin.wif.exception.validate.InvalidLabelException",
"au.org.aurin.wif.model.suitability.SuitabilityLU",
"org.testng.annotations.Test"
] | import au.org.aurin.wif.exception.validate.InvalidLabelException; import au.org.aurin.wif.model.suitability.SuitabilityLU; import org.testng.annotations.Test; | import au.org.aurin.wif.exception.validate.*; import au.org.aurin.wif.model.suitability.*; import org.testng.annotations.*; | [
"au.org.aurin",
"org.testng.annotations"
] | au.org.aurin; org.testng.annotations; | 577,159 |
CmdAndAddressRet header = CmdAndAddressRet.parse(input, true);
if (header != null) {
Matcher matcher;
switch (header.getCmd().toUpperCase()) {
case "VAR_RESET":
case "VAR_RESET_OLD":
if ((matcher = PATTERN_VAR_RESET.matcher(header.getRestInput())).matches()) {
return new VarReset(header.getAddr(),
LcnDefs.Var.varIdToVar(Integer.parseInt(matcher.group("varId")) - 1),
header.getCmd().toUpperCase().endsWith("_OLD"));
}
break;
case "SETPOINT_RESET":
if ((matcher = PATTERN_SETPOINT_RESET.matcher(header.getRestInput())).matches()) {
return new VarReset(header.getAddr(),
LcnDefs.Var.setPointIdToVar(Integer.parseInt(matcher.group("regId")) - 1),
header.getCmd().toUpperCase().endsWith("_OLD"));
}
break;
}
}
return null;
} | CmdAndAddressRet header = CmdAndAddressRet.parse(input, true); if (header != null) { Matcher matcher; switch (header.getCmd().toUpperCase()) { case STR: case STR: if ((matcher = PATTERN_VAR_RESET.matcher(header.getRestInput())).matches()) { return new VarReset(header.getAddr(), LcnDefs.Var.varIdToVar(Integer.parseInt(matcher.group("varId")) - 1), header.getCmd().toUpperCase().endsWith("_OLD")); } break; case STR: if ((matcher = PATTERN_SETPOINT_RESET.matcher(header.getRestInput())).matches()) { return new VarReset(header.getAddr(), LcnDefs.Var.setPointIdToVar(Integer.parseInt(matcher.group("regId")) - 1), header.getCmd().toUpperCase().endsWith("_OLD")); } break; } } return null; } | /**
* Tries to parse the given input text.
*
* @param input the text to parse
* @return the parsed {@link VarReset} or null
*/ | Tries to parse the given input text | tryParseTarget | {
"repo_name": "joek/openhab1-addons",
"path": "bundles/binding/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/mappingtarget/VarReset.java",
"license": "epl-1.0",
"size": 6541
} | [
"java.util.regex.Matcher",
"org.openhab.binding.lcn.common.LcnDefs"
] | import java.util.regex.Matcher; import org.openhab.binding.lcn.common.LcnDefs; | import java.util.regex.*; import org.openhab.binding.lcn.common.*; | [
"java.util",
"org.openhab.binding"
] | java.util; org.openhab.binding; | 1,726,125 |
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> closeAllConnectionsWithResponseAsync(
String hub, RequestOptions requestOptions, Context context) {
if (hub == null) {
return Mono.error(new IllegalArgumentException("Parameter hub is required and cannot be null."));
}
return service.closeAllConnections(
this.client.getEndpoint(), hub, this.client.getServiceVersion().getVersion(), requestOptions, context);
} | @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Void>> function( String hub, RequestOptions requestOptions, Context context) { if (hub == null) { return Mono.error(new IllegalArgumentException(STR)); } return service.closeAllConnections( this.client.getEndpoint(), hub, this.client.getServiceVersion().getVersion(), requestOptions, context); } | /**
* Close the connections in the hub.
*
* <p><strong>Query Parameters</strong>
*
* <table border="1">
* <caption>Query Parameters</caption>
* <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
* <tr><td>excluded</td><td>String</td><td>No</td><td>Exclude these connectionIds when closing the connections in the hub.</td></tr>
* <tr><td>reason</td><td>String</td><td>No</td><td>The reason closing the client connection.</td></tr>
* <tr><td>apiVersion</td><td>String</td><td>Yes</td><td>Api Version</td></tr>
* </table>
*
* @param hub Target hub name, which should start with alphabetic characters and only contain alpha-numeric
* characters or underscore.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @param context The context to associate with this operation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @return the completion.
*/ | Close the connections in the hub. Query Parameters Query Parameters NameTypeRequiredDescription excludedStringNoExclude these connectionIds when closing the connections in the hub. reasonStringNoThe reason closing the client connection. apiVersionStringYesApi Version | closeAllConnectionsWithResponseAsync | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/webpubsub/azure-messaging-webpubsub/src/main/java/com/azure/messaging/webpubsub/implementation/WebPubSubsImpl.java",
"license": "mit",
"size": 121300
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.RequestOptions",
"com.azure.core.http.rest.Response",
"com.azure.core.util.Context"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.core.util.*; | [
"com.azure.core"
] | com.azure.core; | 1,218,249 |
public void removeJobInfo(JobInfo info) {
Job job = info.getJob();
jobs.remove(job);
runnableMonitors.remove(job);
Object[] listenersArray = listeners.getListeners();
for (int i = 0; i < listenersArray.length; i++) {
IJobProgressManagerListener listener = (IJobProgressManagerListener) listenersArray[i];
if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) {
listener.removeJob(info);
}
}
} | void function(JobInfo info) { Job job = info.getJob(); jobs.remove(job); runnableMonitors.remove(job); Object[] listenersArray = listeners.getListeners(); for (int i = 0; i < listenersArray.length; i++) { IJobProgressManagerListener listener = (IJobProgressManagerListener) listenersArray[i]; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.removeJob(info); } } } | /**
* Refresh the content providers as a result of a deletion of info.
*
* @param info
* JobInfo
*/ | Refresh the content providers as a result of a deletion of info | removeJobInfo | {
"repo_name": "CohesionForce/eclipse4-parts",
"path": "org.eclipse.e4.ui.part/src/org/eclipse/e4/ui/internal/progress/ProgressManager.java",
"license": "epl-1.0",
"size": 32895
} | [
"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; | 2,891,238 |
public void close() throws IOException {
randomAccessFile.close();
}
private class FilePart {
private final long no;
private final byte[] data;
private byte[] leftOver;
private int currentLastBytePos;
private FilePart(final long no, final int length, final byte[] leftOverOfLastFilePart) throws IOException {
this.no = no;
int dataLength = length + (leftOverOfLastFilePart != null ? leftOverOfLastFilePart.length : 0);
this.data = new byte[dataLength];
final long off = (no - 1) * blockSize;
// read data
if (no > 0 ) {
randomAccessFile.seek(off);
final int countRead = randomAccessFile.read(data, 0, length);
if (countRead != length) {
throw new IllegalStateException("Count of requested bytes and actually read bytes don't match");
}
}
// copy left over part into data arr
if (leftOverOfLastFilePart != null) {
System.arraycopy(leftOverOfLastFilePart, 0, data, length, leftOverOfLastFilePart.length);
}
this.currentLastBytePos = data.length - 1;
this.leftOver = null;
}
| void function() throws IOException { randomAccessFile.close(); } private class FilePart { private final long no; private final byte[] data; private byte[] leftOver; private int currentLastBytePos; private FilePart(final long no, final int length, final byte[] leftOverOfLastFilePart) throws IOException { this.no = no; int dataLength = length + (leftOverOfLastFilePart != null ? leftOverOfLastFilePart.length : 0); this.data = new byte[dataLength]; final long off = (no - 1) * blockSize; if (no > 0 ) { randomAccessFile.seek(off); final int countRead = randomAccessFile.read(data, 0, length); if (countRead != length) { throw new IllegalStateException(STR); } } if (leftOverOfLastFilePart != null) { System.arraycopy(leftOverOfLastFilePart, 0, data, length, leftOverOfLastFilePart.length); } this.currentLastBytePos = data.length - 1; this.leftOver = null; } | /**
* Closes underlying resources.
*
* @throws IOException if an I/O error occurs
*/ | Closes underlying resources | close | {
"repo_name": "sabob/ratel",
"path": "ratel/src/com/google/ratel/deps/io/input/ReversedLinesFileReader.java",
"license": "apache-2.0",
"size": 13449
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 805,239 |
return this.visibleOnActivities(Arrays.asList(activities));
} | return this.visibleOnActivities(Arrays.asList(activities)); } | /**
* Sets activities on which the page should be visible.
* @return the same instance of {@link PhialPageBuilder}
*/ | Sets activities on which the page should be visible | visibleOnActivities | {
"repo_name": "roshakorost/Phial",
"path": "phial-overlay/src/main/java/com/mindcoders/phial/PhialPageBuilder.java",
"license": "apache-2.0",
"size": 2760
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 1,578,906 |
@Test
public void testRemoveString() throws Exception {
HTableDescriptor desc = new HTableDescriptor("table");
String key = "Some";
String value = "value";
desc.setValue(key, value);
assertEquals(value, desc.getValue(key));
desc.remove(key);
assertEquals(null, desc.getValue(key));
} | void function() throws Exception { HTableDescriptor desc = new HTableDescriptor("table"); String key = "Some"; String value = "value"; desc.setValue(key, value); assertEquals(value, desc.getValue(key)); desc.remove(key); assertEquals(null, desc.getValue(key)); } | /**
* Test that we add and remove strings from settings properly.
* @throws Exception
*/ | Test that we add and remove strings from settings properly | testRemoveString | {
"repo_name": "indi60/hbase-pmc",
"path": "target/hbase-0.94.1/hbase-0.94.1/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java",
"license": "apache-2.0",
"size": 2178
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 1,314,829 |
public static Object add(Object left, Object right) {
return InfixOpNode.add(left, right, null);
} | static Object function(Object left, Object right) { return InfixOpNode.add(left, right, null); } | /**
* FEEL spec Table 45
* Delegates to {@link InfixOpNode} except evaluationcontext
*/ | FEEL spec Table 45 Delegates to <code>InfixOpNode</code> except evaluationcontext | add | {
"repo_name": "mbiarnes/drools",
"path": "kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java",
"license": "apache-2.0",
"size": 17646
} | [
"org.kie.dmn.feel.lang.ast.InfixOpNode"
] | import org.kie.dmn.feel.lang.ast.InfixOpNode; | import org.kie.dmn.feel.lang.ast.*; | [
"org.kie.dmn"
] | org.kie.dmn; | 2,766,054 |
void beforeDatabaseDelete(String world, ProtectedRegion region); | void beforeDatabaseDelete(String world, ProtectedRegion region); | /**
* Called before a region is deleted.
*
* @param world The name of the world
* @param region The {@link ProtectedRegion} which should be deleted
*/ | Called before a region is deleted | beforeDatabaseDelete | {
"repo_name": "maxikg/mongowg",
"path": "src/main/java/de/maxikg/mongowg/RegionStorageListener.java",
"license": "gpl-3.0",
"size": 1343
} | [
"com.sk89q.worldguard.protection.regions.ProtectedRegion"
] | import com.sk89q.worldguard.protection.regions.ProtectedRegion; | import com.sk89q.worldguard.protection.regions.*; | [
"com.sk89q.worldguard"
] | com.sk89q.worldguard; | 958,140 |
public Label or(Label rhs) {
return new LabelExpression.Or(this,rhs);
} | Label function(Label rhs) { return new LabelExpression.Or(this,rhs); } | /**
* Returns the label that represents "this|rhs"
*/ | Returns the label that represents "this|rhs" | or | {
"repo_name": "github-api-test-org/jenkins",
"path": "core/src/main/java/hudson/model/Label.java",
"license": "mit",
"size": 19799
} | [
"hudson.model.labels.LabelExpression"
] | import hudson.model.labels.LabelExpression; | import hudson.model.labels.*; | [
"hudson.model.labels"
] | hudson.model.labels; | 468,186 |
public synchronized void queueDBTask(Runnable bgTask) {
if (!dbExecutor.isShutdown()) {
incrementQueueSize();
dbExecutor.submit(bgTask).addListener(this::decrementQueueSize, MoreExecutors.directExecutor());
}
} | synchronized void function(Runnable bgTask) { if (!dbExecutor.isShutdown()) { incrementQueueSize(); dbExecutor.submit(bgTask).addListener(this::decrementQueueSize, MoreExecutors.directExecutor()); } } | /**
* add InnerTask to the queue that the worker thread gets its work from
*
* @param bgTask
*/ | add InnerTask to the queue that the worker thread gets its work from | queueDBTask | {
"repo_name": "sleuthkit/autopsy",
"path": "ImageGallery/src/org/sleuthkit/autopsy/imagegallery/ImageGalleryController.java",
"license": "apache-2.0",
"size": 41508
} | [
"com.google.common.util.concurrent.MoreExecutors"
] | import com.google.common.util.concurrent.MoreExecutors; | import com.google.common.util.concurrent.*; | [
"com.google.common"
] | com.google.common; | 1,639,353 |
public static long getFirstLong(ResultSet resultSet) throws SQLException {
if (resultSet.next() == true) {
return resultSet.getLong(1);
}
return -1;
} | static long function(ResultSet resultSet) throws SQLException { if (resultSet.next() == true) { return resultSet.getLong(1); } return -1; } | /**
* Returns long value of very first column in result set.
*/ | Returns long value of very first column in result set | getFirstLong | {
"repo_name": "wsldl123292/jodd",
"path": "jodd-db/src/main/java/jodd/db/DbUtil.java",
"license": "bsd-3-clause",
"size": 3462
} | [
"java.sql.ResultSet",
"java.sql.SQLException"
] | import java.sql.ResultSet; import java.sql.SQLException; | import java.sql.*; | [
"java.sql"
] | java.sql; | 1,948,222 |
@Override
public GatewayOperationResponse beginSetSharedKeyV2(String gatewayId, String connectedentityId, GatewaySetSharedKeyParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
// Validate
if (gatewayId == null) {
throw new NullPointerException("gatewayId");
}
if (connectedentityId == null) {
throw new NullPointerException("connectedentityId");
}
if (parameters == null) {
throw new NullPointerException("parameters");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("gatewayId", gatewayId);
tracingParameters.put("connectedentityId", connectedentityId);
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "beginSetSharedKeyV2Async", tracingParameters);
}
// Construct URL
String url = "";
url = url + "/";
if (this.getClient().getCredentials().getSubscriptionId() != null) {
url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
}
url = url + "/services/networking/virtualnetworkgateways/";
url = url + URLEncoder.encode(gatewayId, "UTF-8");
url = url + "/connectedentity/";
url = url + URLEncoder.encode(connectedentityId, "UTF-8");
url = url + "/sharedkey";
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpPost httpRequest = new HttpPost(url);
// Set Headers
httpRequest.setHeader("Content-Type", "application/xml");
httpRequest.setHeader("x-ms-version", "2015-04-01");
// Serialize Request
String requestContent = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document requestDoc = documentBuilder.newDocument();
Element sharedKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SharedKey");
requestDoc.appendChild(sharedKeyElement);
if (parameters.getValue() != null) {
Element valueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
valueElement.appendChild(requestDoc.createTextNode(parameters.getValue()));
sharedKeyElement.appendChild(valueElement);
}
DOMSource domSource = new DOMSource(requestDoc);
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, streamResult);
requestContent = stringWriter.toString();
StringEntity entity = new StringEntity(requestContent);
httpRequest.setEntity(entity);
httpRequest.setHeader("Content-Type", "application/xml");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
GatewayOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatus.SC_ACCEPTED) {
InputStream responseContent = httpResponse.getEntity().getContent();
result = new GatewayOperationResponse();
DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
documentBuilderFactory2.setNamespaceAware(true);
DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));
Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
if (gatewayOperationAsyncResponseElement != null) {
Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID");
if (idElement != null) {
String idInstance;
idInstance = idElement.getTextContent();
result.setOperationId(idInstance);
}
}
}
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
} | GatewayOperationResponse function(String gatewayId, String connectedentityId, GatewaySetSharedKeyParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { if (gatewayId == null) { throw new NullPointerException(STR); } if (connectedentityId == null) { throw new NullPointerException(STR); } if (parameters == null) { throw new NullPointerException(STR); } boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put(STR, gatewayId); tracingParameters.put(STR, connectedentityId); tracingParameters.put(STR, parameters); CloudTracing.enter(invocationId, this, STR, tracingParameters); } String url = STR/STRUTF-8STR/services/networking/virtualnetworkgateways/STRUTF-8STR/connectedentity/STRUTF-8STR/sharedkeySTR/STR STR%20STRContent-TypeSTRapplication/xmlSTRx-ms-versionSTR2015-04-01STRhttp: requestDoc.appendChild(sharedKeyElement); if (parameters.getValue() != null) { Element valueElement = requestDoc.createElementNS(STRContent-TypeSTRapplication/xmlSTRhttp: if (gatewayOperationAsyncResponseElement != null) { Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, STRx-ms-request-idSTRx-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } } | /**
* The Begin Set Virtual Network Gateway Shared Key V2 operation sets the
* shared key used between the gateway and customer vpn for the specified
* site.
*
* @param gatewayId Required. The virtual network for this gateway Id.
* @param connectedentityId Required. The connected entity Id.
* @param parameters Required. Parameters supplied to the Begin Virtual
* Network Gateway Set Shared Key V2 request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/ | The Begin Set Virtual Network Gateway Shared Key V2 operation sets the shared key used between the gateway and customer vpn for the specified site | beginSetSharedKeyV2 | {
"repo_name": "flydream2046/azure-sdk-for-java",
"path": "service-management/azure-svc-mgmt-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperationsImpl.java",
"license": "apache-2.0",
"size": 573643
} | [
"com.microsoft.windowsazure.core.utils.XmlUtility",
"com.microsoft.windowsazure.exception.ServiceException",
"com.microsoft.windowsazure.management.network.models.GatewayOperationResponse",
"com.microsoft.windowsazure.management.network.models.GatewaySetSharedKeyParameters",
"com.microsoft.windowsazure.tracing.CloudTracing",
"java.io.IOException",
"java.util.HashMap",
"javax.xml.parsers.ParserConfigurationException",
"javax.xml.transform.TransformerException",
"org.w3c.dom.Element",
"org.xml.sax.SAXException"
] | import com.microsoft.windowsazure.core.utils.XmlUtility; import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse; import com.microsoft.windowsazure.management.network.models.GatewaySetSharedKeyParameters; import com.microsoft.windowsazure.tracing.CloudTracing; import java.io.IOException; import java.util.HashMap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.Element; import org.xml.sax.SAXException; | import com.microsoft.windowsazure.core.utils.*; import com.microsoft.windowsazure.exception.*; import com.microsoft.windowsazure.management.network.models.*; import com.microsoft.windowsazure.tracing.*; import java.io.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.*; import org.w3c.dom.*; import org.xml.sax.*; | [
"com.microsoft.windowsazure",
"java.io",
"java.util",
"javax.xml",
"org.w3c.dom",
"org.xml.sax"
] | com.microsoft.windowsazure; java.io; java.util; javax.xml; org.w3c.dom; org.xml.sax; | 1,499,575 |
public ISelection getSelection() {
return editorSelection;
} | ISelection function() { return editorSelection; } | /**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to return this editor's overall selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This implements <code>org.eclipse.jface.viewers.ISelectionProvider</code> to return this editor's overall selection. | getSelection | {
"repo_name": "CarlAtComputer/tracker",
"path": "src/java_version/tracker_model/tracker_model.editor/src/tracker/presentation/TrackerEditor.java",
"license": "gpl-2.0",
"size": 54013
} | [
"org.eclipse.jface.viewers.ISelection"
] | import org.eclipse.jface.viewers.ISelection; | import org.eclipse.jface.viewers.*; | [
"org.eclipse.jface"
] | org.eclipse.jface; | 1,128,039 |
public Map<Token, String> getTokenToEndpointMap(); | Map<Token, String> function(); | /**
* Retrieve a map of tokens to endpoints, including the bootstrapping
* ones.
*
* @return a map of tokens to endpoints
*/ | Retrieve a map of tokens to endpoints, including the bootstrapping ones | getTokenToEndpointMap | {
"repo_name": "segfault/apache_cassandra",
"path": "src/java/org/apache/cassandra/service/StorageServiceMBean.java",
"license": "apache-2.0",
"size": 12148
} | [
"java.util.Map",
"org.apache.cassandra.dht.Token"
] | import java.util.Map; import org.apache.cassandra.dht.Token; | import java.util.*; import org.apache.cassandra.dht.*; | [
"java.util",
"org.apache.cassandra"
] | java.util; org.apache.cassandra; | 115,368 |
public void setValidateTo(Date validateTo) {
this.validateTo = validateTo;
} | void function(Date validateTo) { this.validateTo = validateTo; } | /**
* Sets the validate to date.
*
* @param validateTo the validate to date.
*/ | Sets the validate to date | setValidateTo | {
"repo_name": "lorislab/appky",
"path": "appky-application/src/main/java/org/lorislab/appky/application/tmpresource/criteria/TemporaryResourceSearchCriteria.java",
"license": "apache-2.0",
"size": 2498
} | [
"java.util.Date"
] | import java.util.Date; | import java.util.*; | [
"java.util"
] | java.util; | 1,569,893 |
private void setShellSize(int width, int height) {
Rectangle preferred = getShell().getBounds();
preferred.width = width;
preferred.height = height;
getShell().setBounds(getConstrainedShellBounds(preferred));
} | void function(int width, int height) { Rectangle preferred = getShell().getBounds(); preferred.width = width; preferred.height = height; getShell().setBounds(getConstrainedShellBounds(preferred)); } | /**
* Changes the shell size to the given size, ensuring that it is no larger than the display bounds.
* @param width
* the shell width
* @param height
* the shell height
*/ | Changes the shell size to the given size, ensuring that it is no larger than the display bounds | setShellSize | {
"repo_name": "heartsome/translationstudio8",
"path": "database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/TermDbManagerDialog.java",
"license": "gpl-2.0",
"size": 55131
} | [
"org.eclipse.swt.graphics.Rectangle"
] | import org.eclipse.swt.graphics.Rectangle; | import org.eclipse.swt.graphics.*; | [
"org.eclipse.swt"
] | org.eclipse.swt; | 1,545,830 |
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileEntityHopper();
} | TileEntity function(World worldIn, int meta) { return new TileEntityHopper(); } | /**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/ | Returns a new instance of a block's tile entity class. Called on placing the block | createNewTileEntity | {
"repo_name": "SuperUnitato/UnLonely",
"path": "build/tmp/recompileMc/sources/net/minecraft/block/BlockHopper.java",
"license": "lgpl-2.1",
"size": 10212
} | [
"net.minecraft.tileentity.TileEntity",
"net.minecraft.tileentity.TileEntityHopper",
"net.minecraft.world.World"
] | import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityHopper; import net.minecraft.world.World; | import net.minecraft.tileentity.*; import net.minecraft.world.*; | [
"net.minecraft.tileentity",
"net.minecraft.world"
] | net.minecraft.tileentity; net.minecraft.world; | 871,489 |
public void update(Observable o, Object arg) {
if (arg instanceof Integer) {
Integer eventId = (Integer) arg;
switch (eventId) {
case ApplicationContext.MODEL_CLOSED:
this.jScrollPane1.getViewport().removeAll();
break;
case ApplicationContext.MODEL_LOADED:
IContextStackViewerPanel panel = new IContextStackViewerPanel();
this.jScrollPane1.setViewportView(panel);
break;
}
}
} | void function(Observable o, Object arg) { if (arg instanceof Integer) { Integer eventId = (Integer) arg; switch (eventId) { case ApplicationContext.MODEL_CLOSED: this.jScrollPane1.getViewport().removeAll(); break; case ApplicationContext.MODEL_LOADED: IContextStackViewerPanel panel = new IContextStackViewerPanel(); this.jScrollPane1.setViewportView(panel); break; } } } | /**
* Handle update event.
* @param o Observable
* @param arg Argument
*/ | Handle update event | update | {
"repo_name": "elmarquez/Federation",
"path": "src/ca/sfu/federation/viewer/stackviewer/StackViewerPanel.java",
"license": "gpl-2.0",
"size": 2480
} | [
"ca.sfu.federation.ApplicationContext",
"java.util.Observable"
] | import ca.sfu.federation.ApplicationContext; import java.util.Observable; | import ca.sfu.federation.*; import java.util.*; | [
"ca.sfu.federation",
"java.util"
] | ca.sfu.federation; java.util; | 2,158,904 |
public ServiceResponse<Object> get200ModelA201ModelC404ModelDDefaultError201Valid() throws ErrorException, IOException {
Call<ResponseBody> call = service.get200ModelA201ModelC404ModelDDefaultError201Valid();
return get200ModelA201ModelC404ModelDDefaultError201ValidDelegate(call.execute());
} | ServiceResponse<Object> function() throws ErrorException, IOException { Call<ResponseBody> call = service.get200ModelA201ModelC404ModelDDefaultError201Valid(); return get200ModelA201ModelC404ModelDDefaultError201ValidDelegate(call.execute()); } | /**
* Send a 200 response with valid payload: {'httpCode': '201'}.
*
* @throws ErrorException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the Object object wrapped in {@link ServiceResponse} if successful.
*/ | Send a 200 response with valid payload: {'httpCode': '201'} | get200ModelA201ModelC404ModelDDefaultError201Valid | {
"repo_name": "John-Hart/autorest",
"path": "src/generator/AutoRest.Java.Tests/src/main/java/fixtures/http/implementation/MultipleResponsesImpl.java",
"license": "mit",
"size": 84047
} | [
"com.microsoft.rest.ServiceResponse",
"java.io.IOException"
] | import com.microsoft.rest.ServiceResponse; import java.io.IOException; | import com.microsoft.rest.*; import java.io.*; | [
"com.microsoft.rest",
"java.io"
] | com.microsoft.rest; java.io; | 120,834 |
@Override
public void setBackgroundTranslucence(float alpha) {
this.bgAC = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
} | void function(float alpha) { this.bgAC = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); } | /**
* Set the translucence value of this button's background.
*
* @param alpha blending value, in [0.0,1.0]. Default is 0.8
*/ | Set the translucence value of this button's background | setBackgroundTranslucence | {
"repo_name": "sharwell/zgrnbviewer",
"path": "org-tvl-netbeans-zgrviewer/src/fr/inria/zvtm/widgets/TranslucentButton.java",
"license": "lgpl-3.0",
"size": 4535
} | [
"java.awt.AlphaComposite"
] | import java.awt.AlphaComposite; | import java.awt.*; | [
"java.awt"
] | java.awt; | 2,807,918 |
public boolean disseminateMsgNoPOW(byte[] msgPayload, int nonceTrialsPerByte, int extraBytes)
{
String hexPayload = ByteFormatter.byteArrayToHexString(msgPayload);
Log.d(TAG, "Attempting to disseminate an encrypted msg without POW done.\n"
+ "Encrypted msg payload: " + hexPayload);
// Attempt to make the API call
ApiCaller caller = new ApiCaller();
int successfulCalls = 0;
for(int i = 0; i < MSG_DISSEMINATION_REDUNDANCY_FACTOR; i++)
{
Object callResult = caller.call(API_METHOD_DISSEMINATE_MSG_NO_POW, hexPayload);
String resultString = callResult.toString();
Log.d(TAG, "The result of the 'disseminate msg' API call was: " + resultString);
if (resultString.equals(RESULT_CODE_DISSEMINATE_MSG))
{
successfulCalls = successfulCalls + 1;
}
else
{
Log.e(TAG, "While running disseminateMsgNoPOW(), a server connection was established \n" +
"successfully, but the API call failed. The result of the api call was: " + resultString);
}
try
{
caller.switchToNextServer();
}
catch (RuntimeException e)
{
break;
}
}
// If we successfully disseminated the payload to at least one server, return true
if (successfulCalls > 0)
{
return true;
}
else
{
return false;
}
}
| boolean function(byte[] msgPayload, int nonceTrialsPerByte, int extraBytes) { String hexPayload = ByteFormatter.byteArrayToHexString(msgPayload); Log.d(TAG, STR + STR + hexPayload); ApiCaller caller = new ApiCaller(); int successfulCalls = 0; for(int i = 0; i < MSG_DISSEMINATION_REDUNDANCY_FACTOR; i++) { Object callResult = caller.call(API_METHOD_DISSEMINATE_MSG_NO_POW, hexPayload); String resultString = callResult.toString(); Log.d(TAG, STR + resultString); if (resultString.equals(RESULT_CODE_DISSEMINATE_MSG)) { successfulCalls = successfulCalls + 1; } else { Log.e(TAG, STR + STR + resultString); } try { caller.switchToNextServer(); } catch (RuntimeException e) { break; } } if (successfulCalls > 0) { return true; } else { return false; } } | /**
* Attempts to disseminate a message to the rest of the Bitmessage
* network by sending it to one or more Bitseal servers. The proof of work for
* the message has NOT yet been done, so the server will do the proof
* of work and then disseminate the message.
*
* @param msgPayload - A byte[] containing the message to be disseminated.
* @param nonceTrialsPerByte - An int representing the nonceTrialsPerByte value for
* the proof of work required by the destination address
* @param extraBytes - An int representing the extraBytes value for
* the proof of work required by the destination address
*
* @return A boolean indicating whether or not the dissemination attempt was successful.
*/ | Attempts to disseminate a message to the rest of the Bitmessage network by sending it to one or more Bitseal servers. The proof of work for the message has NOT yet been done, so the server will do the proof of work and then disseminate the message | disseminateMsgNoPOW | {
"repo_name": "prashantwosti/bitseal",
"path": "src/org/bitseal/network/ServerCommunicator.java",
"license": "gpl-3.0",
"size": 25009
} | [
"android.util.Log",
"org.bitseal.util.ByteFormatter"
] | import android.util.Log; import org.bitseal.util.ByteFormatter; | import android.util.*; import org.bitseal.util.*; | [
"android.util",
"org.bitseal.util"
] | android.util; org.bitseal.util; | 2,172,692 |
public FScoreCalculator<String> getFscoreUnknownInLexicon() {
return fscoreUnknownInLexicon;
} | FScoreCalculator<String> function() { return fscoreUnknownInLexicon; } | /**
* An f-score calculator for unknown words in the lexicon.
*/ | An f-score calculator for unknown words in the lexicon | getFscoreUnknownInLexicon | {
"repo_name": "safety-data/talismane",
"path": "talismane_core/src/main/java/com/joliciel/talismane/posTagger/PosTagEvaluationFScoreCalculator.java",
"license": "agpl-3.0",
"size": 6132
} | [
"com.joliciel.talismane.stats.FScoreCalculator"
] | import com.joliciel.talismane.stats.FScoreCalculator; | import com.joliciel.talismane.stats.*; | [
"com.joliciel.talismane"
] | com.joliciel.talismane; | 559,345 |
public static final SourceModel.Expr toList(SourceModel.Expr s) {
return
SourceModel.Expr.Application.make(
new SourceModel.Expr[] {SourceModel.Expr.Var.make(Functions.toList), s});
}
public static final QualifiedName toList =
QualifiedName.make(CAL_Set.MODULE_NAME, "toList");
| static final SourceModel.Expr function(SourceModel.Expr s) { return SourceModel.Expr.Application.make( new SourceModel.Expr[] {SourceModel.Expr.Var.make(Functions.toList), s}); } static final QualifiedName function = QualifiedName.make(CAL_Set.MODULE_NAME, STR); | /**
* Converts the set to an ascending list of elements.
* <p>
* Complexity: O(n)
*
* @param s (CAL type: <code>Cal.Collections.Set.Set a</code>)
* the set.
* @return (CAL type: <code>[a]</code>)
* a list of elements in the set in ascending order.
*/ | Converts the set to an ascending list of elements. Complexity: O(n) | toList | {
"repo_name": "levans/Open-Quark",
"path": "src/CAL_Platform/src/org/openquark/cal/module/Cal/Collections/CAL_Set.java",
"license": "bsd-3-clause",
"size": 39863
} | [
"org.openquark.cal.compiler.QualifiedName",
"org.openquark.cal.compiler.SourceModel"
] | import org.openquark.cal.compiler.QualifiedName; import org.openquark.cal.compiler.SourceModel; | import org.openquark.cal.compiler.*; | [
"org.openquark.cal"
] | org.openquark.cal; | 246,509 |
@SuppressLint("InlinedApi")
private void createCameraSource(boolean autoFocus, boolean useFlash) {
Context context = getApplicationContext();
// A barcode detector is created to track barcodes. An associated multi-processor instance
// is set to receive the barcode detection results, track the barcodes, and maintain
// graphics for each barcode on screen. The factory is used by the multi-processor to
// create a separate tracker instance for each barcode.
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.setProcessor(
new MultiProcessor.Builder<>(barcodeFactory).build());
if (!barcodeDetector.isOperational()) {
// Note: The first time that an app using the barcode or face API is installed on a
// device, GMS will download a native libraries to the device in order to do detection.
// Usually this completes before the app is run for the first time. But if that
// download has not yet completed, then the above call will not detect any barcodes
// and/or faces.
//
// isOperational() can be used to check if the required native libraries are currently
// available. The detectors will automatically become operational once the library
// downloads complete on device.
Log.w(TAG, "Detector dependencies are not yet available.");
// Check for low storage. If there is low storage, the native library will not be
// downloaded, so detection will not become operational.
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
Log.w(TAG, getString(R.string.low_storage_error));
}
}
// Creates and starts the camera. Note that this uses a higher resolution in comparison
// to other detection examples to enable the barcode detector to detect small barcodes
// at long distances.
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600, 1024)
.setRequestedFps(15.0f);
// make sure that auto focus is an available option
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
builder = builder.setFocusMode(
autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
}
mCameraSource = builder
.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
.build();
} | @SuppressLint(STR) void function(boolean autoFocus, boolean useFlash) { Context context = getApplicationContext(); BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build(); BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay); barcodeDetector.setProcessor( new MultiProcessor.Builder<>(barcodeFactory).build()); if (!barcodeDetector.isOperational()) { Log.w(TAG, STR); IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW); boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null; if (hasLowStorage) { Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show(); Log.w(TAG, getString(R.string.low_storage_error)); } } CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(1600, 1024) .setRequestedFps(15.0f); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { builder = builder.setFocusMode( autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null); } mCameraSource = builder .setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null) .build(); } | /**
* Creates and starts the camera. Note that this uses a higher resolution in comparison
* to other detection examples to enable the barcode detector to detect small barcodes
* at long distances.
*
* Suppressing InlinedApi since there is a check that the minimum version is met before using
* the constant.
*/ | Creates and starts the camera. Note that this uses a higher resolution in comparison to other detection examples to enable the barcode detector to detect small barcodes at long distances. Suppressing InlinedApi since there is a check that the minimum version is met before using the constant | createCameraSource | {
"repo_name": "WataruSuzuki/Now-Slack-Android",
"path": "mobile/src/main/java/jp/co/devjchankchan/now_slack_android/barcodereader/BarcodeCaptureActivity.java",
"license": "apache-2.0",
"size": 17863
} | [
"android.annotation.SuppressLint",
"android.content.Context",
"android.content.Intent",
"android.content.IntentFilter",
"android.hardware.Camera",
"android.os.Build",
"android.util.Log",
"android.widget.Toast",
"com.google.android.gms.vision.MultiProcessor",
"com.google.android.gms.vision.barcode.BarcodeDetector",
"jp.co.devjchankchan.now_slack_android.barcodereader.ui.camera.CameraSource"
] | import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.Camera; import android.os.Build; import android.util.Log; import android.widget.Toast; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.barcode.BarcodeDetector; import jp.co.devjchankchan.now_slack_android.barcodereader.ui.camera.CameraSource; | import android.annotation.*; import android.content.*; import android.hardware.*; import android.os.*; import android.util.*; import android.widget.*; import com.google.android.gms.vision.*; import com.google.android.gms.vision.barcode.*; import jp.co.devjchankchan.now_slack_android.barcodereader.ui.camera.*; | [
"android.annotation",
"android.content",
"android.hardware",
"android.os",
"android.util",
"android.widget",
"com.google.android",
"jp.co.devjchankchan"
] | android.annotation; android.content; android.hardware; android.os; android.util; android.widget; com.google.android; jp.co.devjchankchan; | 1,739,082 |
public void testDb2Url()
{
assertEquals(Db2Platform.DATABASENAME,
_platformUtils.determineDatabaseType(null, "jdbc:db2://sysmvs1.stl.ibm.com:5021/san_jose"));
assertEquals(Db2Platform.DATABASENAME,
_platformUtils.determineDatabaseType(null, "jdbc:db2os390://sysmvs1.stl.ibm.com:5021/san_jose"));
assertEquals(Db2Platform.DATABASENAME,
_platformUtils.determineDatabaseType(null, "jdbc:db2os390sqlj://sysmvs1.stl.ibm.com:5021/san_jose"));
// DataDirect Connect
assertEquals(Db2Platform.DATABASENAME,
_platformUtils.determineDatabaseType(null, "jdbc:datadirect:db2://server1:50000;DatabaseName=jdbc;User=test;Password=secret"));
// i-net
assertEquals(Db2Platform.DATABASENAME,
_platformUtils.determineDatabaseType(null, "jdbc:inetdb2://server1:50000"));
}
| void function() { assertEquals(Db2Platform.DATABASENAME, _platformUtils.determineDatabaseType(null, STRjdbc:db2os390: assertEquals(Db2Platform.DATABASENAME, _platformUtils.determineDatabaseType(null, STRjdbc:datadirect:db2: assertEquals(Db2Platform.DATABASENAME, _platformUtils.determineDatabaseType(null, "jdbc:inetdb2: } | /**
* Tests the determination of the Db2 platform via JDBC connection urls.
*/ | Tests the determination of the Db2 platform via JDBC connection urls | testDb2Url | {
"repo_name": "etiago/apache-ddlutils",
"path": "src/test/org/apache/ddlutils/platform/TestPlatformUtils.java",
"license": "apache-2.0",
"size": 19409
} | [
"org.apache.ddlutils.platform.db2.Db2Platform"
] | import org.apache.ddlutils.platform.db2.Db2Platform; | import org.apache.ddlutils.platform.db2.*; | [
"org.apache.ddlutils"
] | org.apache.ddlutils; | 2,172,967 |
public void delete(GwtXSRFToken xsfrToken, String stringScopeId, String gwtCredentialId)
throws GwtKapuaException; | void function(GwtXSRFToken xsfrToken, String stringScopeId, String gwtCredentialId) throws GwtKapuaException; | /**
* Delete the supplied Credential.
*
* @param gwtCredentialId
* @throws GwtKapuaException
*/ | Delete the supplied Credential | delete | {
"repo_name": "stzilli/kapua",
"path": "console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/shared/service/GwtCredentialService.java",
"license": "epl-1.0",
"size": 2618
} | [
"org.eclipse.kapua.app.console.module.api.client.GwtKapuaException",
"org.eclipse.kapua.app.console.module.api.shared.model.GwtXSRFToken"
] | import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.shared.model.GwtXSRFToken; | import org.eclipse.kapua.app.console.module.api.client.*; import org.eclipse.kapua.app.console.module.api.shared.model.*; | [
"org.eclipse.kapua"
] | org.eclipse.kapua; | 499,173 |
@Override
public byte readByte() throws EOFException {
checkFileSize();
int b = content[dataPointer];
dataPointer++;
return (byte) (b);
} | byte function() throws EOFException { checkFileSize(); int b = content[dataPointer]; dataPointer++; return (byte) (b); } | /**
* Read signed byte.
*
* @return return signed byte
*
* @throws EOFException if end of file
*/ | Read signed byte | readByte | {
"repo_name": "tectronics/openjill",
"path": "abstractfile/src/main/java/org/jill/file/FileAbstractByteImpl.java",
"license": "mpl-2.0",
"size": 10497
} | [
"java.io.EOFException"
] | import java.io.EOFException; | import java.io.*; | [
"java.io"
] | java.io; | 2,907,481 |
public synchronized HeartbeatResponse heartbeat(TaskTrackerStatus status,
boolean restarted,
boolean initialContact,
boolean acceptNewTasks,
short responseId)
throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Got heartbeat from: " + status.getTrackerName() +
" (restarted: " + restarted +
" initialContact: " + initialContact +
" acceptNewTasks: " + acceptNewTasks + ")" +
" with responseId: " + responseId);
}
// Make sure heartbeat is from a tasktracker allowed by the jobtracker.
if (!acceptTaskTracker(status)) {
throw new DisallowedTaskTrackerException(status);
}
// First check if the last heartbeat response got through
String trackerName = status.getTrackerName();
long now = clock.getTime();
if (restarted) {
faultyTrackers.markTrackerHealthy(status.getHost());
} else {
faultyTrackers.checkTrackerFaultTimeout(status.getHost(), now);
}
HeartbeatResponse prevHeartbeatResponse =
trackerToHeartbeatResponseMap.get(trackerName);
boolean addRestartInfo = false;
if (initialContact != true) {
// If this isn't the 'initial contact' from the tasktracker,
// there is something seriously wrong if the JobTracker has
// no record of the 'previous heartbeat'; if so, ask the
// tasktracker to re-initialize itself.
if (prevHeartbeatResponse == null) {
// This is the first heartbeat from the old tracker to the newly
// started JobTracker
if (hasRestarted()) {
addRestartInfo = true;
// inform the recovery manager about this tracker joining back
recoveryManager.unMarkTracker(trackerName);
} else {
// Jobtracker might have restarted but no recovery is needed
// otherwise this code should not be reached
LOG.warn("Serious problem, cannot find record of 'previous' " +
"heartbeat for '" + trackerName +
"'; reinitializing the tasktracker");
return new HeartbeatResponse(responseId,
new TaskTrackerAction[] {new ReinitTrackerAction()});
}
} else {
// It is completely safe to not process a 'duplicate' heartbeat from a
// {@link TaskTracker} since it resends the heartbeat when rpcs are
// lost see {@link TaskTracker.transmitHeartbeat()};
// acknowledge it by re-sending the previous response to let the
// {@link TaskTracker} go forward.
if (prevHeartbeatResponse.getResponseId() != responseId) {
LOG.info("Ignoring 'duplicate' heartbeat from '" +
trackerName + "'; resending the previous 'lost' response");
return prevHeartbeatResponse;
}
}
}
// Process this heartbeat
short newResponseId = (short)(responseId + 1);
status.setLastSeen(now);
if (!processHeartbeat(status, initialContact, now)) {
if (prevHeartbeatResponse != null) {
trackerToHeartbeatResponseMap.remove(trackerName);
}
return new HeartbeatResponse(newResponseId,
new TaskTrackerAction[] {new ReinitTrackerAction()});
}
// Initialize the response to be sent for the heartbeat
HeartbeatResponse response = new HeartbeatResponse(newResponseId, null);
List<TaskTrackerAction> actions = new ArrayList<TaskTrackerAction>();
boolean isBlacklisted = faultyTrackers.isBlacklisted(status.getHost());
// Check for new tasks to be executed on the tasktracker
if (recoveryManager.shouldSchedule() && acceptNewTasks && !isBlacklisted) {
TaskTrackerStatus taskTrackerStatus = getTaskTrackerStatus(trackerName);
if (taskTrackerStatus == null) {
LOG.warn("Unknown task tracker polling; ignoring: " + trackerName);
} else {
List<Task> tasks = getSetupAndCleanupTasks(taskTrackerStatus);
if (tasks == null ) {
tasks = taskScheduler.assignTasks(taskTrackers.get(trackerName));
}
if (tasks != null) {
for (Task task : tasks) {
expireLaunchingTasks.addNewTask(task.getTaskID());
if(LOG.isDebugEnabled()) {
LOG.debug(trackerName + " -> LaunchTask: " + task.getTaskID());
}
actions.add(new LaunchTaskAction(task));
}
}
}
}
// Check for tasks to be killed
List<TaskTrackerAction> killTasksList = getTasksToKill(trackerName);
if (killTasksList != null) {
actions.addAll(killTasksList);
}
// Check for jobs to be killed/cleanedup
List<TaskTrackerAction> killJobsList = getJobsForCleanup(trackerName);
if (killJobsList != null) {
actions.addAll(killJobsList);
}
// Check for tasks whose outputs can be saved
List<TaskTrackerAction> commitTasksList = getTasksToSave(status);
if (commitTasksList != null) {
actions.addAll(commitTasksList);
}
// calculate next heartbeat interval and put in heartbeat response
int nextInterval = getNextHeartbeatInterval();
response.setHeartbeatInterval(nextInterval);
response.setActions(
actions.toArray(new TaskTrackerAction[actions.size()]));
// check if the restart info is req
if (addRestartInfo) {
response.setRecoveredJobs(recoveryManager.getJobsToRecover());
}
// Update the trackerToHeartbeatResponseMap
trackerToHeartbeatResponseMap.put(trackerName, response);
// Done processing the hearbeat, now remove 'marked' tasks
removeMarkedTasks(trackerName);
return response;
} | synchronized HeartbeatResponse function(TaskTrackerStatus status, boolean restarted, boolean initialContact, boolean acceptNewTasks, short responseId) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug(STR + status.getTrackerName() + STR + restarted + STR + initialContact + STR + acceptNewTasks + ")" + STR + responseId); } if (!acceptTaskTracker(status)) { throw new DisallowedTaskTrackerException(status); } String trackerName = status.getTrackerName(); long now = clock.getTime(); if (restarted) { faultyTrackers.markTrackerHealthy(status.getHost()); } else { faultyTrackers.checkTrackerFaultTimeout(status.getHost(), now); } HeartbeatResponse prevHeartbeatResponse = trackerToHeartbeatResponseMap.get(trackerName); boolean addRestartInfo = false; if (initialContact != true) { if (prevHeartbeatResponse == null) { if (hasRestarted()) { addRestartInfo = true; recoveryManager.unMarkTracker(trackerName); } else { LOG.warn(STR + STR + trackerName + STR); return new HeartbeatResponse(responseId, new TaskTrackerAction[] {new ReinitTrackerAction()}); } } else { if (prevHeartbeatResponse.getResponseId() != responseId) { LOG.info(STR + trackerName + STR); return prevHeartbeatResponse; } } } short newResponseId = (short)(responseId + 1); status.setLastSeen(now); if (!processHeartbeat(status, initialContact, now)) { if (prevHeartbeatResponse != null) { trackerToHeartbeatResponseMap.remove(trackerName); } return new HeartbeatResponse(newResponseId, new TaskTrackerAction[] {new ReinitTrackerAction()}); } HeartbeatResponse response = new HeartbeatResponse(newResponseId, null); List<TaskTrackerAction> actions = new ArrayList<TaskTrackerAction>(); boolean isBlacklisted = faultyTrackers.isBlacklisted(status.getHost()); if (recoveryManager.shouldSchedule() && acceptNewTasks && !isBlacklisted) { TaskTrackerStatus taskTrackerStatus = getTaskTrackerStatus(trackerName); if (taskTrackerStatus == null) { LOG.warn(STR + trackerName); } else { List<Task> tasks = getSetupAndCleanupTasks(taskTrackerStatus); if (tasks == null ) { tasks = taskScheduler.assignTasks(taskTrackers.get(trackerName)); } if (tasks != null) { for (Task task : tasks) { expireLaunchingTasks.addNewTask(task.getTaskID()); if(LOG.isDebugEnabled()) { LOG.debug(trackerName + STR + task.getTaskID()); } actions.add(new LaunchTaskAction(task)); } } } } List<TaskTrackerAction> killTasksList = getTasksToKill(trackerName); if (killTasksList != null) { actions.addAll(killTasksList); } List<TaskTrackerAction> killJobsList = getJobsForCleanup(trackerName); if (killJobsList != null) { actions.addAll(killJobsList); } List<TaskTrackerAction> commitTasksList = getTasksToSave(status); if (commitTasksList != null) { actions.addAll(commitTasksList); } int nextInterval = getNextHeartbeatInterval(); response.setHeartbeatInterval(nextInterval); response.setActions( actions.toArray(new TaskTrackerAction[actions.size()])); if (addRestartInfo) { response.setRecoveredJobs(recoveryManager.getJobsToRecover()); } trackerToHeartbeatResponseMap.put(trackerName, response); removeMarkedTasks(trackerName); return response; } | /**
* The periodic heartbeat mechanism between the {@link TaskTracker} and
* the {@link JobTracker}.
*
* The {@link JobTracker} processes the status information sent by the
* {@link TaskTracker} and responds with instructions to start/stop
* tasks or jobs, and also 'reset' instructions during contingencies.
*/ | The periodic heartbeat mechanism between the <code>TaskTracker</code> and the <code>JobTracker</code>. The <code>JobTracker</code> processes the status information sent by the <code>TaskTracker</code> and responds with instructions to start/stop tasks or jobs, and also 'reset' instructions during contingencies | heartbeat | {
"repo_name": "zxqt223/hadoop-ha.1.0.3",
"path": "src/mapred/org/apache/hadoop/mapred/JobTracker.java",
"license": "apache-2.0",
"size": 199505
} | [
"java.io.IOException",
"java.util.ArrayList",
"java.util.List"
] | import java.io.IOException; import java.util.ArrayList; import java.util.List; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,906,871 |
public void readFrom(ChannelBuffer data) {
this.portNumber = data.readShort();
if (this.hardwareAddress == null)
this.hardwareAddress = new byte[OFP_ETH_ALEN];
data.readBytes(this.hardwareAddress);
byte[] name = new byte[16];
data.readBytes(name);
// find the first index of 0
int index = 0;
for (byte b : name) {
if (0 == b)
break;
++index;
}
this.name = new String(Arrays.copyOf(name, index),
Charset.forName("ascii"));
this.config = data.readInt();
this.state = data.readInt();
this.currentFeatures = data.readInt();
this.advertisedFeatures = data.readInt();
this.supportedFeatures = data.readInt();
this.peerFeatures = data.readInt();
} | void function(ChannelBuffer data) { this.portNumber = data.readShort(); if (this.hardwareAddress == null) this.hardwareAddress = new byte[OFP_ETH_ALEN]; data.readBytes(this.hardwareAddress); byte[] name = new byte[16]; data.readBytes(name); int index = 0; for (byte b : name) { if (0 == b) break; ++index; } this.name = new String(Arrays.copyOf(name, index), Charset.forName("ascii")); this.config = data.readInt(); this.state = data.readInt(); this.currentFeatures = data.readInt(); this.advertisedFeatures = data.readInt(); this.supportedFeatures = data.readInt(); this.peerFeatures = data.readInt(); } | /**
* Read this message off the wire from the specified ByteBuffer
* @param data
*/ | Read this message off the wire from the specified ByteBuffer | readFrom | {
"repo_name": "jmiserez/floodlight",
"path": "src/main/java/org/openflow/protocol/OFPhysicalPort.java",
"license": "apache-2.0",
"size": 17564
} | [
"java.nio.charset.Charset",
"java.util.Arrays",
"org.jboss.netty.buffer.ChannelBuffer"
] | import java.nio.charset.Charset; import java.util.Arrays; import org.jboss.netty.buffer.ChannelBuffer; | import java.nio.charset.*; import java.util.*; import org.jboss.netty.buffer.*; | [
"java.nio",
"java.util",
"org.jboss.netty"
] | java.nio; java.util; org.jboss.netty; | 194,703 |
public Vector getSourceExposure() {
return exposure;
} | Vector function() { return exposure; } | /**
* Returns the {@link Vector Vector} containing the exposures
* for each accident period.
*/ | Returns the <code>Vector Vector</code> containing the exposures for each accident period | getSourceExposure | {
"repo_name": "Depter/JRLib",
"path": "NetbeansProject/jrlib/src/main/java/org/jreserve/jrlib/estimate/CapeCodEstimateInput.java",
"license": "lgpl-3.0",
"size": 2692
} | [
"org.jreserve.jrlib.vector.Vector"
] | import org.jreserve.jrlib.vector.Vector; | import org.jreserve.jrlib.vector.*; | [
"org.jreserve.jrlib"
] | org.jreserve.jrlib; | 2,287,286 |
@Nonnull
@com.intellij.util.xml.Attribute ("class")
@Required
@Convert(MappingClassResolveConverter.class)
GenericAttributeValue<PsiClass> getClazz(); | @com.intellij.util.xml.Attribute ("class") @Convert(MappingClassResolveConverter.class) GenericAttributeValue<PsiClass> getClazz(); | /**
* Returns the value of the class child.
* Attribute class
* @return the value of the class child.
*/ | Returns the value of the class child. Attribute class | getClazz | {
"repo_name": "consulo-trash/consulo-hibernate",
"path": "plugin/src/main/java/com/intellij/hibernate/model/xml/mapping/HbmIndexManyToMany.java",
"license": "apache-2.0",
"size": 1946
} | [
"com.intellij.hibernate.model.converters.MappingClassResolveConverter",
"com.intellij.psi.PsiClass",
"com.intellij.util.xml.Convert",
"com.intellij.util.xml.GenericAttributeValue"
] | import com.intellij.hibernate.model.converters.MappingClassResolveConverter; import com.intellij.psi.PsiClass; import com.intellij.util.xml.Convert; import com.intellij.util.xml.GenericAttributeValue; | import com.intellij.hibernate.model.converters.*; import com.intellij.psi.*; import com.intellij.util.xml.*; | [
"com.intellij.hibernate",
"com.intellij.psi",
"com.intellij.util"
] | com.intellij.hibernate; com.intellij.psi; com.intellij.util; | 2,528,051 |
public void touch(Matrix4 localTransform) {
if (GlobalConf.scene.LAZY_TEXTURE_INIT && !texInitialised) {
if (tc != null) {
if (!texLoading) {
logger.info(I18n.bundle.format("notif.loading", tc.base));
tc.initialize(manager);
// Set to loading
texLoading = true;
} else if (tc.isFinishedLoading(manager)) {
Gdx.app.postRunnable(() -> {
tc.initMaterial(manager, instance, cc, culling);
});
// Set to initialised
texInitialised = true;
texLoading = false;
}
} else if (localTransform == null) {
// Use color if necessary
addColorToMat();
// Set to initialised
texInitialised = true;
texLoading = false;
}
}
if (localTransform != null && GlobalConf.scene.LAZY_MESH_INIT && !modelInitialised) {
if (!modelLoading) {
logger.info(I18n.bundle.format("notif.loading", modelFile));
AssetBean.addAsset(modelFile, Model.class);
modelLoading = true;
} else if (manager.isLoaded(modelFile)) {
Model model = null;
Map<String, Material> materials = null;
Pair<Model, Map<String, Material>> modmat = initModelFile();
model = modmat.getFirst();
materials = modmat.getSecond();
instance = new ModelInstance(model, localTransform);
// COLOR IF NO TEXTURE
if (tc == null && instance != null) {
addColorToMat();
}
modelInitialised = true;
modelLoading = false;
}
}
} | void function(Matrix4 localTransform) { if (GlobalConf.scene.LAZY_TEXTURE_INIT && !texInitialised) { if (tc != null) { if (!texLoading) { logger.info(I18n.bundle.format(STR, tc.base)); tc.initialize(manager); texLoading = true; } else if (tc.isFinishedLoading(manager)) { Gdx.app.postRunnable(() -> { tc.initMaterial(manager, instance, cc, culling); }); texInitialised = true; texLoading = false; } } else if (localTransform == null) { addColorToMat(); texInitialised = true; texLoading = false; } } if (localTransform != null && GlobalConf.scene.LAZY_MESH_INIT && !modelInitialised) { if (!modelLoading) { logger.info(I18n.bundle.format(STR, modelFile)); AssetBean.addAsset(modelFile, Model.class); modelLoading = true; } else if (manager.isLoaded(modelFile)) { Model model = null; Map<String, Material> materials = null; Pair<Model, Map<String, Material>> modmat = initModelFile(); model = modmat.getFirst(); materials = modmat.getSecond(); instance = new ModelInstance(model, localTransform); if (tc == null && instance != null) { addColorToMat(); } modelInitialised = true; modelLoading = false; } } } | /**
* Initialises the texture if it is not initialised yet
*/ | Initialises the texture if it is not initialised yet | touch | {
"repo_name": "vga101/gaiasky",
"path": "core/src/gaia/cu9/ari/gaiaorbit/scenegraph/component/ModelComponent.java",
"license": "mpl-2.0",
"size": 14609
} | [
"com.badlogic.gdx.Gdx",
"com.badlogic.gdx.graphics.g3d.Material",
"com.badlogic.gdx.graphics.g3d.Model",
"com.badlogic.gdx.graphics.g3d.ModelInstance",
"com.badlogic.gdx.math.Matrix4",
"java.util.Map"
] | import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.math.Matrix4; import java.util.Map; | import com.badlogic.gdx.*; import com.badlogic.gdx.graphics.g3d.*; import com.badlogic.gdx.math.*; import java.util.*; | [
"com.badlogic.gdx",
"java.util"
] | com.badlogic.gdx; java.util; | 1,119,379 |
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TagDetailsInner>> createOrUpdateWithResponseAsync(String tagName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (tagName == null) {
return Mono.error(new IllegalArgumentException("Parameter tagName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.createOrUpdate(
this.client.getEndpoint(),
tagName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
accept,
context))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
} | @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<TagDetailsInner>> function(String tagName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( STR)); } if (tagName == null) { return Mono.error(new IllegalArgumentException(STR)); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( STR)); } final String accept = STR; return FluxUtil .withContext( context -> service .createOrUpdate( this.client.getEndpoint(), tagName, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } | /**
* This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name
* can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which
* are reserved for Azure use: 'microsoft', 'azure', 'windows'.
*
* @param tagName The name of the tag to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return tag details.
*/ | This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows' | createOrUpdateWithResponseAsync | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanagerhybrid/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsClientImpl.java",
"license": "mit",
"size": 71642
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.Response",
"com.azure.core.util.FluxUtil",
"com.azure.resourcemanager.resources.fluent.models.TagDetailsInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.resources.fluent.models.TagDetailsInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.core.util.*; import com.azure.resourcemanager.resources.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 2,714,816 |
private boolean isTagStartOnLine(IDocument doc, DocumentCommand command) {
int position = command.offset - 1;
String docData = doc.get();
//
// First, search backwards. We should hit a '<' before we hit a '>'.
int i = position;
try {
for (; i > 0; i--) {
char c = docData.charAt(i);
if (c == '\r' || c == '\n')
return false; // Got to the start of the line.
if (docData.charAt(i) == '<') {
return true;
}
}
} catch (Exception e) {
System.err
.println("TagIndentStrategy::isEnterInTag() - Caught exception \'"
+ e.getMessage() + "\'. Dumping.");
e.printStackTrace();
return false;
}
return false;
}
// private int findEndOfTag(String data, int offset) {
/*
* private int findEndOfTag(IDocument data, int offset) { int pos = offset;
* int startOfTag = 0;
*
* try { startOfTag = findStartofTag(data, pos-1);
* }catch(BadLocationException ex) { ex.printStackTrace(); return 0; }
*
* if(startOfTag == -1) return 0;
*
* try { for(int i = startOfTag; i < data.getLength(); i++) { char currChar =
* data.getChar(i); if(isWhitespace(currChar)) { return i; } } }
* catch(Exception e) { e.printStackTrace(); return 0; } return pos; } | boolean function(IDocument doc, DocumentCommand command) { int position = command.offset - 1; String docData = doc.get(); int i = position; try { for (; i > 0; i--) { char c = docData.charAt(i); if (c == '\r' c == '\n') return false; if (docData.charAt(i) == '<') { return true; } } } catch (Exception e) { System.err .println(STR + e.getMessage() + STR); e.printStackTrace(); return false; } return false; } /* * private int findEndOfTag(IDocument data, int offset) { int pos = offset; * int startOfTag = 0; * * try { startOfTag = findStartofTag(data, pos-1); * }catch(BadLocationException ex) { ex.printStackTrace(); return 0; } * * if(startOfTag == -1) return 0; * * try { for(int i = startOfTag; i < data.getLength(); i++) { char currChar = * data.getChar(i); if(isWhitespace(currChar)) { return i; } } } * catch(Exception e) { e.printStackTrace(); return 0; } return pos; } | /**
* Figures out if the document command occurred inside a tag that starts on
* the current line.
*
* @param doc
* @param docCommand
* @return
*/ | Figures out if the document command occurred inside a tag that starts on the current line | isTagStartOnLine | {
"repo_name": "cybersonic/org.cfeclipse.cfml",
"path": "src/org/cfeclipse/cfml/editors/indentstrategies/TagIndentStrategy.java",
"license": "mit",
"size": 35512
} | [
"org.eclipse.jface.text.BadLocationException",
"org.eclipse.jface.text.DocumentCommand",
"org.eclipse.jface.text.IDocument"
] | import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; | import org.eclipse.jface.text.*; | [
"org.eclipse.jface"
] | org.eclipse.jface; | 1,773,644 |
private KeyStoreManager prepareServerKeystore() {
KeyStoreManager keystore = keyStoreService.getSystemKeyStore();
if(!keystore.aliasExists(X509ExtendedKeyManagerImpl.HTTPS_ALIAS)) {
keystore.createOrUpdateKey(X509ExtendedKeyManagerImpl.HTTPS_ALIAS, "RSA", 2048, generateCertificateInfo());
keyStoreService.saveKeyStore(keystore);
}
return keystore;
} | KeyStoreManager function() { KeyStoreManager keystore = keyStoreService.getSystemKeyStore(); if(!keystore.aliasExists(X509ExtendedKeyManagerImpl.HTTPS_ALIAS)) { keystore.createOrUpdateKey(X509ExtendedKeyManagerImpl.HTTPS_ALIAS, "RSA", 2048, generateCertificateInfo()); keyStoreService.saveKeyStore(keystore); } return keystore; } | /**
* Prepares the keystore for serving HTTPs requests. This method will create the keystore if it does not exist
* and generate a self-signed certificate. If the keystore already exists, it is not modified in any way.
*
* @return a prepared keystore
*/ | Prepares the keystore for serving HTTPs requests. This method will create the keystore if it does not exist and generate a self-signed certificate. If the keystore already exists, it is not modified in any way | prepareServerKeystore | {
"repo_name": "apruden/mica2",
"path": "mica-webapp/src/main/java/org/obiba/mica/config/ssl/SslContextFactoryImpl.java",
"license": "gpl-3.0",
"size": 2492
} | [
"org.obiba.security.KeyStoreManager",
"org.obiba.ssl.X509ExtendedKeyManagerImpl"
] | import org.obiba.security.KeyStoreManager; import org.obiba.ssl.X509ExtendedKeyManagerImpl; | import org.obiba.security.*; import org.obiba.ssl.*; | [
"org.obiba.security",
"org.obiba.ssl"
] | org.obiba.security; org.obiba.ssl; | 900,481 |
public static String getProductInfoPrintout()
{
//read properties
Properties properties=LibraryConfigurationLoader.readInternalConfiguration();
//get values
String name=properties.getProperty("org.fax4j.product.name");
String version=properties.getProperty("org.fax4j.product.version");
//init buffer
StringBuilder buffer=new StringBuilder();
buffer.append(name);
buffer.append(" library.");
buffer.append(Logger.SYSTEM_EOL);
buffer.append("Version: ");
buffer.append(version);
//get text
String text=buffer.toString();
return text;
} | static String function() { Properties properties=LibraryConfigurationLoader.readInternalConfiguration(); String name=properties.getProperty(STR); String version=properties.getProperty(STR); StringBuilder buffer=new StringBuilder(); buffer.append(name); buffer.append(STR); buffer.append(Logger.SYSTEM_EOL); buffer.append(STR); buffer.append(version); String text=buffer.toString(); return text; } | /**
* Returns the product info printout.
*
* @return The product info printout
*/ | Returns the product info printout | getProductInfoPrintout | {
"repo_name": "ZhernakovMikhail/fax4j",
"path": "src/main/java/org/fax4j/ProductInfo.java",
"license": "apache-2.0",
"size": 1572
} | [
"java.util.Properties",
"org.fax4j.common.Logger",
"org.fax4j.util.LibraryConfigurationLoader"
] | import java.util.Properties; import org.fax4j.common.Logger; import org.fax4j.util.LibraryConfigurationLoader; | import java.util.*; import org.fax4j.common.*; import org.fax4j.util.*; | [
"java.util",
"org.fax4j.common",
"org.fax4j.util"
] | java.util; org.fax4j.common; org.fax4j.util; | 1,374,901 |
public void doCalculation(String[] args) throws Exception {
String operation;
double operand1;
double operand2;
// Get the number format for the default local.
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
// Validate the arguments.
// Arguments are in the form: Operation, Operand1, Operand2.
if (args.length != 3) {
printUsageSyntax();
return;
}
operation = args[0];
try {
// Retrieve operands respective of the locale
operand1 = numberFormat.parse(args[1]).doubleValue();
operand2 = numberFormat.parse(args[2]).doubleValue();
} catch(ParseException pe) {
printUsageSyntax("Parse exception on number input. Please enter a valid number.");
return;
} catch(NumberFormatException nfe) {
printUsageSyntax("Invalid number entered. Please enter a valid number.");
return;
}
try {
BasicCalculatorSessionBeanRemote basicCalc = getBasicCalculatorRemoteEJB();
BasicCalculatorClientResult calcResult = calculate(basicCalc,operation,(double)operand1,(double)operand2);
printMessage("Result: " + numberFormat.format( new Double (calcResult.getOperand1())) + calcResult.getOperation() + numberFormat.format(new Double(calcResult.getOperand2())) + " = " + numberFormat.format(new Double (calcResult.getResult())) );
printMessage("Good bye.\n");
} catch (Exception e) {
e.printStackTrace();
}
} | void function(String[] args) throws Exception { String operation; double operand1; double operand2; NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); if (args.length != 3) { printUsageSyntax(); return; } operation = args[0]; try { operand1 = numberFormat.parse(args[1]).doubleValue(); operand2 = numberFormat.parse(args[2]).doubleValue(); } catch(ParseException pe) { printUsageSyntax(STR); return; } catch(NumberFormatException nfe) { printUsageSyntax(STR); return; } try { BasicCalculatorSessionBeanRemote basicCalc = getBasicCalculatorRemoteEJB(); BasicCalculatorClientResult calcResult = calculate(basicCalc,operation,(double)operand1,(double)operand2); printMessage(STR + numberFormat.format( new Double (calcResult.getOperand1())) + calcResult.getOperation() + numberFormat.format(new Double(calcResult.getOperand2())) + STR + numberFormat.format(new Double (calcResult.getResult())) ); printMessage(STR); } catch (Exception e) { e.printStackTrace(); } } | /**
* Handles all of the user-interaction for the BasicCalculatorClient.
* This method takes an array of strings in the order {<Operation>,<Operand1>,<Operand2>}.
* The calculation result is returned in a BasicCalculatorClientResult object to be displayed to the user.
* @throws Exception
*/ | Handles all of the user-interaction for the BasicCalculatorClient. This method takes an array of strings in the order {,,}. The calculation result is returned in a BasicCalculatorClientResult object to be displayed to the user | doCalculation | {
"repo_name": "WASdev/sample.appclient.basiccalc",
"path": "basiccalc/basiccalc-client/src/main/java/net/wasdev/sample/basiccalc/client/BasicCalculatorClient.java",
"license": "apache-2.0",
"size": 5250
} | [
"java.text.NumberFormat",
"java.text.ParseException",
"java.util.Locale",
"net.wasdev.sample.basiccalc.ejb.BasicCalculatorSessionBeanRemote"
] | import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import net.wasdev.sample.basiccalc.ejb.BasicCalculatorSessionBeanRemote; | import java.text.*; import java.util.*; import net.wasdev.sample.basiccalc.ejb.*; | [
"java.text",
"java.util",
"net.wasdev.sample"
] | java.text; java.util; net.wasdev.sample; | 288,876 |
static public BigDecimal scalePrec(final BigDecimal x, int d)
{
return x.setScale(d+x.scale()) ;
} | static BigDecimal function(final BigDecimal x, int d) { return x.setScale(d+x.scale()) ; } | /** Append decimal zeros to the value. This returns a value which appears to have
* a higher precision than the input.
* @param x The input value
* @param d The (positive) value of zeros to be added as least significant digits.
* @return The same value as the input but with increased (pseudo) precision.
*/ | Append decimal zeros to the value. This returns a value which appears to have a higher precision than the input | scalePrec | {
"repo_name": "dangerousfood/Cast-Preprocessor",
"path": "slicer/src/org/nevec/rjm/BigDecimalMath.java",
"license": "apache-2.0",
"size": 140938
} | [
"java.math.BigDecimal"
] | import java.math.BigDecimal; | import java.math.*; | [
"java.math"
] | java.math; | 753,513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.