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
list
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
list
libraries_info
stringlengths
6
661
id
int64
0
2.92M
Entity newContainer(Element element);
Entity newContainer(Element element);
/** * Construct a new container resource, from an XML element. * * @param element * The XML. * @return The new container resource. */
Construct a new container resource, from an XML element
newContainer
{ "repo_name": "harfalm/Sakai-10.1", "path": "kernel/api/src/main/java/org/sakaiproject/util/DoubleStorageUser.java", "license": "apache-2.0", "size": 3285 }
[ "org.sakaiproject.entity.api.Entity", "org.w3c.dom.Element" ]
import org.sakaiproject.entity.api.Entity; import org.w3c.dom.Element;
import org.sakaiproject.entity.api.*; import org.w3c.dom.*;
[ "org.sakaiproject.entity", "org.w3c.dom" ]
org.sakaiproject.entity; org.w3c.dom;
885,150
public ContentletDataGen folder(Folder folder) { this.folder = folder; return this; }
ContentletDataGen function(Folder folder) { this.folder = folder; return this; }
/** * Sets folder property to the ContentletDataGen instance. This will * be used when a new {@link Contentlet} instance is created * * @param folder the inode of the folder * @return ContentletDataGen with folder set */
Sets folder property to the ContentletDataGen instance. This will be used when a new <code>Contentlet</code> instance is created
folder
{ "repo_name": "dotCMS/core", "path": "dotCMS/src/integration-test/java/com/dotcms/datagen/ContentletDataGen.java", "license": "gpl-3.0", "size": 14537 }
[ "com.dotmarketing.portlets.folders.model.Folder" ]
import com.dotmarketing.portlets.folders.model.Folder;
import com.dotmarketing.portlets.folders.model.*;
[ "com.dotmarketing.portlets" ]
com.dotmarketing.portlets;
624,032
public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map<String, String> tags) { return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); }
CertificateBundle function(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map<String, String> tags) { return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, certificateAttributes, tags).toBlocking().single().body(); }
/** * Updates the specified attributes associated with the given certificate. * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated are the certificate's attributes. This operation requires the certificates/update permission. * * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate in the given key vault. * @param certificateVersion The version of the certificate. * @param certificatePolicy The management policy for the certificate. * @param certificateAttributes The attributes of the certificate (optional). * @param tags Application specific metadata in the form of key-value pairs. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws KeyVaultErrorException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the CertificateBundle object if successful. */
Updates the specified attributes associated with the given certificate. The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated are the certificate's attributes. This operation requires the certificates/update permission
updateCertificate
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java", "license": "mit", "size": 884227 }
[ "com.microsoft.azure.keyvault.models.CertificateAttributes", "com.microsoft.azure.keyvault.models.CertificateBundle", "com.microsoft.azure.keyvault.models.CertificatePolicy", "java.util.Map" ]
import com.microsoft.azure.keyvault.models.CertificateAttributes; import com.microsoft.azure.keyvault.models.CertificateBundle; import com.microsoft.azure.keyvault.models.CertificatePolicy; import java.util.Map;
import com.microsoft.azure.keyvault.models.*; import java.util.*;
[ "com.microsoft.azure", "java.util" ]
com.microsoft.azure; java.util;
1,553,126
public static Net readNetFromDarknet(MatOfByte bufferCfg, MatOfByte bufferModel) { Mat bufferCfg_mat = bufferCfg; Mat bufferModel_mat = bufferModel; return new Net(readNetFromDarknet_2(bufferCfg_mat.nativeObj, bufferModel_mat.nativeObj)); }
static Net function(MatOfByte bufferCfg, MatOfByte bufferModel) { Mat bufferCfg_mat = bufferCfg; Mat bufferModel_mat = bufferModel; return new Net(readNetFromDarknet_2(bufferCfg_mat.nativeObj, bufferModel_mat.nativeObj)); }
/** * Reads a network model stored in &lt;a href="https://pjreddie.com/darknet/"&gt;Darknet&lt;/a&gt; model files. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. * @param bufferModel A buffer contains a content of .weights file with learned network. * @return Net object. */
Reads a network model stored in &lt;a href="HREF"&gt;Darknet&lt;/a&gt; model files
readNetFromDarknet
{ "repo_name": "donaldmunro/AARemu", "path": "OpenCV/src/main/java/org/opencv/dnn/Dnn.java", "license": "apache-2.0", "size": 59819 }
[ "org.opencv.core.Mat", "org.opencv.core.MatOfByte", "org.opencv.dnn.Net" ]
import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.dnn.Net;
import org.opencv.core.*; import org.opencv.dnn.*;
[ "org.opencv.core", "org.opencv.dnn" ]
org.opencv.core; org.opencv.dnn;
1,262,974
protected Rule getBestFitRule( String groupId, String artifactId ) { Rule bestFit = null; final List<Rule> rules = ruleSet.getRules(); int bestGroupIdScore = Integer.MAX_VALUE; int bestArtifactIdScore = Integer.MAX_VALUE; boolean exactGroupId = false; boolean exactArtifactId = false; for ( Rule rule : rules ) { int groupIdScore = RegexUtils.getWildcardScore( rule.getGroupId() ); if ( groupIdScore > bestGroupIdScore ) { continue; } boolean exactMatch = exactMatch( rule.getGroupId(), groupId ); boolean match = exactMatch || match( rule.getGroupId(), groupId ); if ( !match || ( exactGroupId && !exactMatch ) ) { continue; } if ( bestGroupIdScore > groupIdScore ) { bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } bestGroupIdScore = groupIdScore; if ( exactMatch && !exactGroupId ) { exactGroupId = true; bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } int artifactIdScore = RegexUtils.getWildcardScore( rule.getArtifactId() ); if ( artifactIdScore > bestArtifactIdScore ) { continue; } exactMatch = exactMatch( rule.getArtifactId(), artifactId ); match = exactMatch || match( rule.getArtifactId(), artifactId ); if ( !match || ( exactArtifactId && !exactMatch ) ) { continue; } bestArtifactIdScore = artifactIdScore; if ( exactMatch && !exactArtifactId ) { exactArtifactId = true; } bestFit = rule; } return bestFit; } /** * {@inheritDoc}
Rule function( String groupId, String artifactId ) { Rule bestFit = null; final List<Rule> rules = ruleSet.getRules(); int bestGroupIdScore = Integer.MAX_VALUE; int bestArtifactIdScore = Integer.MAX_VALUE; boolean exactGroupId = false; boolean exactArtifactId = false; for ( Rule rule : rules ) { int groupIdScore = RegexUtils.getWildcardScore( rule.getGroupId() ); if ( groupIdScore > bestGroupIdScore ) { continue; } boolean exactMatch = exactMatch( rule.getGroupId(), groupId ); boolean match = exactMatch match( rule.getGroupId(), groupId ); if ( !match ( exactGroupId && !exactMatch ) ) { continue; } if ( bestGroupIdScore > groupIdScore ) { bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } bestGroupIdScore = groupIdScore; if ( exactMatch && !exactGroupId ) { exactGroupId = true; bestArtifactIdScore = Integer.MAX_VALUE; exactArtifactId = false; } int artifactIdScore = RegexUtils.getWildcardScore( rule.getArtifactId() ); if ( artifactIdScore > bestArtifactIdScore ) { continue; } exactMatch = exactMatch( rule.getArtifactId(), artifactId ); match = exactMatch match( rule.getArtifactId(), artifactId ); if ( !match ( exactArtifactId && !exactMatch ) ) { continue; } bestArtifactIdScore = artifactIdScore; if ( exactMatch && !exactArtifactId ) { exactArtifactId = true; } bestFit = rule; } return bestFit; } /** * {@inheritDoc}
/** * Find the rule, if any, which best fits the artifact details given. * * @param groupId Group id of the artifact * @param artifactId Artifact id of the artifact * @return Rule which best describes the given artifact */
Find the rule, if any, which best fits the artifact details given
getBestFitRule
{ "repo_name": "cjdev/versions-maven-plugin", "path": "src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java", "license": "apache-2.0", "size": 40424 }
[ "java.util.List", "org.codehaus.mojo.versions.model.Rule", "org.codehaus.mojo.versions.utils.RegexUtils" ]
import java.util.List; import org.codehaus.mojo.versions.model.Rule; import org.codehaus.mojo.versions.utils.RegexUtils;
import java.util.*; import org.codehaus.mojo.versions.model.*; import org.codehaus.mojo.versions.utils.*;
[ "java.util", "org.codehaus.mojo" ]
java.util; org.codehaus.mojo;
27,572
TemplateDTO getTemplate(String id);
TemplateDTO getTemplate(String id);
/** * Gets the template with the specified id. * * @param id id * @return template */
Gets the template with the specified id
getTemplate
{ "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 }
[ "org.apache.nifi.web.api.dto.TemplateDTO" ]
import org.apache.nifi.web.api.dto.TemplateDTO;
import org.apache.nifi.web.api.dto.*;
[ "org.apache.nifi" ]
org.apache.nifi;
1,253,350
public Builder setApplication(Application application) { mApplication = application; return this; }
Builder function(Application application) { mApplication = application; return this; }
/** * Required. This must be your {@code Application} instance. */
Required. This must be your Application instance
setApplication
{ "repo_name": "dut3062796s/react-native", "path": "ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java", "license": "bsd-3-clause", "size": 21405 }
[ "android.app.Application" ]
import android.app.Application;
import android.app.*;
[ "android.app" ]
android.app;
1,232,733
public static void closeRegion(final AdminService.BlockingInterface admin, final ServerName server, final byte[] regionName) throws IOException { CloseRegionRequest closeRegionRequest = RequestConverter.buildCloseRegionRequest(server, regionName); try { admin.closeRegion(null, closeRegionRequest); } catch (ServiceException se) { throw getRemoteException(se); } }
static void function(final AdminService.BlockingInterface admin, final ServerName server, final byte[] regionName) throws IOException { CloseRegionRequest closeRegionRequest = RequestConverter.buildCloseRegionRequest(server, regionName); try { admin.closeRegion(null, closeRegionRequest); } catch (ServiceException se) { throw getRemoteException(se); } }
/** * A helper to close a region given a region name * using admin protocol. * * @param admin * @param regionName * @throws IOException */
A helper to close a region given a region name using admin protocol
closeRegion
{ "repo_name": "lshmouse/hbase", "path": "hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java", "license": "apache-2.0", "size": 118965 }
[ "com.google.protobuf.ServiceException", "java.io.IOException", "org.apache.hadoop.hbase.ServerName", "org.apache.hadoop.hbase.protobuf.generated.AdminProtos" ]
import com.google.protobuf.ServiceException; import java.io.IOException; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
import com.google.protobuf.*; import java.io.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.protobuf.generated.*;
[ "com.google.protobuf", "java.io", "org.apache.hadoop" ]
com.google.protobuf; java.io; org.apache.hadoop;
186,471
public List<ValueOferta> choices0RemoveFromOfertas() { return getComanda().getOfertas(); } @Persistent(dependentElement = "true") @Join(deleteAction = ForeignKeyAction.CASCADE) private List<ValueProductoNoElaborado> bebidas = new ArrayList<ValueProductoNoElaborado>();
List<ValueOferta> function() { return getComanda().getOfertas(); } @Persistent(dependentElement = "true") @Join(deleteAction = ForeignKeyAction.CASCADE) private List<ValueProductoNoElaborado> bebidas = new ArrayList<ValueProductoNoElaborado>();
/** * Obtiene una lista de Ofertas * @return List<Oferta> */
Obtiene una lista de Ofertas
choices0RemoveFromOfertas
{ "repo_name": "resto-tesis/resto-tesis", "path": "dom/src/main/java/dom/pedido/Pedido.java", "license": "apache-2.0", "size": 27996 }
[ "java.util.ArrayList", "java.util.List", "javax.jdo.annotations.ForeignKeyAction", "javax.jdo.annotations.Join", "javax.jdo.annotations.Persistent" ]
import java.util.ArrayList; import java.util.List; import javax.jdo.annotations.ForeignKeyAction; import javax.jdo.annotations.Join; import javax.jdo.annotations.Persistent;
import java.util.*; import javax.jdo.annotations.*;
[ "java.util", "javax.jdo" ]
java.util; javax.jdo;
1,525,321
public static Map<String, PastebinProvider> getAllPastebinProviders() { return Collections.unmodifiableMap(pastebinProviders); }
static Map<String, PastebinProvider> function() { return Collections.unmodifiableMap(pastebinProviders); }
/** * Get a map of all {@link PastebinProvider}s, in no particular order. * * @return Map of providers */
Get a map of all <code>PastebinProvider</code>s, in no particular order
getAllPastebinProviders
{ "repo_name": "richardg867/CrashReporter", "path": "src/crashreporter/api/Registry.java", "license": "unlicense", "size": 3754 }
[ "java.util.Collections", "java.util.Map" ]
import java.util.Collections; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,284,680
public void setDTDHandler(XMLDTDHandler dtdHandler) { fDTDHandler = dtdHandler; } // setDTDHandler(XMLDTDHandler)
void function(XMLDTDHandler dtdHandler) { fDTDHandler = dtdHandler; }
/** * Sets the DTD handler. * * @param dtdHandler The DTD handler. */
Sets the DTD handler
setDTDHandler
{ "repo_name": "lostdj/Jaklin-OpenJDK-JAXP", "path": "src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java", "license": "gpl-2.0", "size": 65960 }
[ "com.sun.org.apache.xerces.internal.xni.XMLDTDHandler" ]
import com.sun.org.apache.xerces.internal.xni.XMLDTDHandler;
import com.sun.org.apache.xerces.internal.xni.*;
[ "com.sun.org" ]
com.sun.org;
88,976
public void testCompleteOnTimeout_completed() { for (Integer v1 : new Integer[] { 1, null }) { CompletableFuture<Integer> f = new CompletableFuture<>(); CompletableFuture<Integer> g = new CompletableFuture<>(); long startTime = System.nanoTime(); f.complete(v1); assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); g.complete(v1); checkCompletedNormally(f, v1); checkCompletedNormally(g, v1); assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); }}
void function() { for (Integer v1 : new Integer[] { 1, null }) { CompletableFuture<Integer> f = new CompletableFuture<>(); CompletableFuture<Integer> g = new CompletableFuture<>(); long startTime = System.nanoTime(); f.complete(v1); assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); g.complete(v1); checkCompletedNormally(f, v1); checkCompletedNormally(g, v1); assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); }}
/** * completeOnTimeout has no effect if completed within timeout */
completeOnTimeout has no effect if completed within timeout
testCompleteOnTimeout_completed
{ "repo_name": "FauxFaux/jdk9-jdk", "path": "test/java/util/concurrent/tck/CompletableFutureTest.java", "license": "gpl-2.0", "size": 175854 }
[ "java.util.concurrent.CompletableFuture" ]
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
563,730
public void setSecondaryShadowDrawable(Drawable d) { mViewBehind.setSecondaryShadowDrawable(d); }
void function(Drawable d) { mViewBehind.setSecondaryShadowDrawable(d); }
/** * Sets the secondary (right) shadow drawable. * * @param d the new shadow drawable */
Sets the secondary (right) shadow drawable
setSecondaryShadowDrawable
{ "repo_name": "qmc000/NewMessage", "path": "message/src/main/java/com/jeremyfeinstein/slidingmenu/lib/SlidingMenu.java", "license": "apache-2.0", "size": 28211 }
[ "android.graphics.drawable.Drawable" ]
import android.graphics.drawable.Drawable;
import android.graphics.drawable.*;
[ "android.graphics" ]
android.graphics;
219,022
public Entity getEntity() { return this.entity; }
Entity function() { return this.entity; }
/** * Gets the entity attached to this message or <code>null</code> if no entity is attached. */
Gets the entity attached to this message or <code>null</code> if no entity is attached
getEntity
{ "repo_name": "gbumgard/js4ms", "path": "js4ms-jsdk/rest/src/main/java/org/js4ms/rest/message/Message.java", "license": "apache-2.0", "size": 8984 }
[ "org.js4ms.rest.entity.Entity" ]
import org.js4ms.rest.entity.Entity;
import org.js4ms.rest.entity.*;
[ "org.js4ms.rest" ]
org.js4ms.rest;
734,693
Location getNewLocation();
Location getNewLocation();
/** * Gets the new {@link Location} that the entity is in. * * @return The new location */
Gets the new <code>Location</code> that the entity is in
getNewLocation
{ "repo_name": "Fozie/SpongeAPI", "path": "src/main/java/org/spongepowered/api/event/entity/EntityMoveEvent.java", "license": "mit", "size": 1889 }
[ "org.spongepowered.api.world.Location" ]
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.*;
[ "org.spongepowered.api" ]
org.spongepowered.api;
420,940
@Test public void testDelimiterParsingDisabledMultiAttrValues() throws ConfigurationException { conf.clear(); conf.setDelimiterParsingDisabled(true); conf.load(); List<Object> expr = conf.getList("expressions[@value]"); assertEquals("Wrong list size", 2, expr.size()); assertEquals("Wrong element 1", "a || (b && c)", expr.get(0)); assertEquals("Wrong element 2", "!d", expr.get(1)); }
void function() throws ConfigurationException { conf.clear(); conf.setDelimiterParsingDisabled(true); conf.load(); List<Object> expr = conf.getList(STR); assertEquals(STR, 2, expr.size()); assertEquals(STR, STR, expr.get(0)); assertEquals(STR, "!d", expr.get(1)); }
/** * Tests multiple attribute values in delimiter parsing disabled mode. */
Tests multiple attribute values in delimiter parsing disabled mode
testDelimiterParsingDisabledMultiAttrValues
{ "repo_name": "XClouded/t4f-core", "path": "devops/java/src/test/java/io/datalayer/conf/XmlConfigurationTest.java", "license": "apache-2.0", "size": 66459 }
[ "java.util.List", "org.apache.commons.configuration.ConfigurationException", "org.junit.Assert" ]
import java.util.List; import org.apache.commons.configuration.ConfigurationException; import org.junit.Assert;
import java.util.*; import org.apache.commons.configuration.*; import org.junit.*;
[ "java.util", "org.apache.commons", "org.junit" ]
java.util; org.apache.commons; org.junit;
1,574,392
public ModuleInput getDefaultModuleInput(List<ModuleColumn> moduleColumns) { ModuleInput moduleInput = new ModuleInput(); moduleInput.setColumnValues( moduleColumns.stream().filter(mc -> mc.getDefaultValue() != null) .collect(Collectors.toMap(mc -> mc.getId(), mc -> mc.getDefaultValue())) ); return moduleInput; }
ModuleInput function(List<ModuleColumn> moduleColumns) { ModuleInput moduleInput = new ModuleInput(); moduleInput.setColumnValues( moduleColumns.stream().filter(mc -> mc.getDefaultValue() != null) .collect(Collectors.toMap(mc -> mc.getId(), mc -> mc.getDefaultValue())) ); return moduleInput; }
/** * Creates default {@link ModuleInput} by setting it with the default column values from database * @param moduleColumns Module columns to fill the input with * @return Module input filled with default column values */
Creates default <code>ModuleInput</code> by setting it with the default column values from database
getDefaultModuleInput
{ "repo_name": "tfeldmanis/agnostic-cms", "path": "agnostic-cms-web/src/main/java/com/agnosticcms/web/service/ModuleService.java", "license": "apache-2.0", "size": 3599 }
[ "com.agnosticcms.web.dto.ModuleColumn", "com.agnosticcms.web.dto.form.ModuleInput", "java.util.List", "java.util.stream.Collectors" ]
import com.agnosticcms.web.dto.ModuleColumn; import com.agnosticcms.web.dto.form.ModuleInput; import java.util.List; import java.util.stream.Collectors;
import com.agnosticcms.web.dto.*; import com.agnosticcms.web.dto.form.*; import java.util.*; import java.util.stream.*;
[ "com.agnosticcms.web", "java.util" ]
com.agnosticcms.web; java.util;
1,858,434
@ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PremierAddOnOfferInner> listPremierAddOnOffers();
@ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<PremierAddOnOfferInner> listPremierAddOnOffers();
/** * Description for List all premier add-on offers. * * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return collection of premier add-on offers. */
Description for List all premier add-on offers
listPremierAddOnOffers
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/fluent/ResourceProvidersClient.java", "license": "mit", "size": 46577 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.http.rest.PagedIterable", "com.azure.resourcemanager.appservice.fluent.models.PremierAddOnOfferInner" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.appservice.fluent.models.PremierAddOnOfferInner;
import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.appservice.fluent.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
1,824,562
public static L2ModificationInstruction modVlanPcp(Byte vlanPcp) { checkNotNull(vlanPcp, "VLAN Pcp cannot be null"); return new L2ModificationInstruction.ModVlanPcpInstruction(vlanPcp); }
static L2ModificationInstruction function(Byte vlanPcp) { checkNotNull(vlanPcp, STR); return new L2ModificationInstruction.ModVlanPcpInstruction(vlanPcp); }
/** * Creates a VLAN PCP modification. * * @param vlanPcp the PCP to modify to * @return a L2 modification */
Creates a VLAN PCP modification
modVlanPcp
{ "repo_name": "CNlukai/onos-gerrit-test", "path": "core/api/src/main/java/org/onosproject/net/flow/instructions/Instructions.java", "license": "apache-2.0", "size": 17125 }
[ "com.google.common.base.Preconditions" ]
import com.google.common.base.Preconditions;
import com.google.common.base.*;
[ "com.google.common" ]
com.google.common;
595,425
public static void print(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) .append("Name: ").append(elasticPool.name()) .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) .append("\n\tRegion: ").append(elasticPool.region()) .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) .append("\n\tState of the elastic pool: ").append(elasticPool.state()) .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageMB()); System.out.println(builder.toString()); }
static void function(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append(STR).append(elasticPool.id()) .append(STR).append(elasticPool.name()) .append(STR).append(elasticPool.resourceGroupName()) .append(STR).append(elasticPool.region()) .append(STR).append(elasticPool.sqlServerName()) .append(STR).append(elasticPool.edition()) .append(STR).append(elasticPool.dtu()) .append(STR).append(elasticPool.databaseDtuMax()) .append(STR).append(elasticPool.databaseDtuMin()) .append(STR).append(elasticPool.creationDate()) .append(STR).append(elasticPool.state()) .append(STR).append(elasticPool.storageMB()); System.out.println(builder.toString()); }
/** * Prints information of the elastic pool passed in. * @param elasticPool elastic pool to be printed */
Prints information of the elastic pool passed in
print
{ "repo_name": "martinsawicki/azure-sdk-for-java", "path": "azure-samples/src/main/java/com/microsoft/azure/management/samples/Utils.java", "license": "mit", "size": 124123 }
[ "com.microsoft.azure.management.sql.SqlElasticPool" ]
import com.microsoft.azure.management.sql.SqlElasticPool;
import com.microsoft.azure.management.sql.*;
[ "com.microsoft.azure" ]
com.microsoft.azure;
1,270,172
public final RefactoringStatus createInputFatalStatus(final Object element, final String id) { return createInputFatalStatus(element, getName(), id); }
final RefactoringStatus function(final Object element, final String id) { return createInputFatalStatus(element, getName(), id); }
/** * Creates a fatal error status telling that the input element does not * exist. * * @param element * the input element, or <code>null</code> * @param id * the id of the refactoring * @return the refactoring status */
Creates a fatal error status telling that the input element does not exist
createInputFatalStatus
{ "repo_name": "boniatillo-com/PhaserEditor", "path": "source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ScriptableRefactoring.java", "license": "epl-1.0", "size": 4372 }
[ "org.eclipse.ltk.core.refactoring.RefactoringStatus" ]
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.*;
[ "org.eclipse.ltk" ]
org.eclipse.ltk;
2,262,813
JavaRDD<String> input = jsc.textFile(fileName); return input.map(normalizationFunction); }
JavaRDD<String> input = jsc.textFile(fileName); return input.map(normalizationFunction); }
/** * Reads the content of a text file to get lines. * @param fileName * @return a RDD of text lines. */
Reads the content of a text file to get lines
readTextFile
{ "repo_name": "phuonglh/vn.vitk", "path": "src/main/java/vn/vitk/tok/Tokenizer.java", "license": "gpl-3.0", "size": 28573 }
[ "org.apache.spark.api.java.JavaRDD" ]
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.*;
[ "org.apache.spark" ]
org.apache.spark;
899,094
EClass getRoutetable();
EClass getRoutetable();
/** * Returns the meta object for class '{@link de.hub.clickwatch.specificmodels.brn.lt_routes.Routetable <em>Routetable</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Routetable</em>'. * @see de.hub.clickwatch.specificmodels.brn.lt_routes.Routetable * @generated */
Returns the meta object for class '<code>de.hub.clickwatch.specificmodels.brn.lt_routes.Routetable Routetable</code>'.
getRoutetable
{ "repo_name": "markus1978/clickwatch", "path": "analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/lt_routes/Lt_routesPackage.java", "license": "apache-2.0", "size": 25374 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
309,496
public ArrayList<ShipmentOrder> list(ArrayList cList){ calculateinsurance(); //Initiates CalculateInurance Method cList.add(count,OrderNumber); cList.add((count+1),weight); cList.add((count+2),method); cList.add((count+3),shipping); cList.add((count+4),insuranceCost); cList.add((count+5),totalCost); count=count+6; return cList; }
ArrayList<ShipmentOrder> function(ArrayList cList){ calculateinsurance(); cList.add(count,OrderNumber); cList.add((count+1),weight); cList.add((count+2),method); cList.add((count+3),shipping); cList.add((count+4),insuranceCost); cList.add((count+5),totalCost); count=count+6; return cList; }
/** * Sets ShipmentOrder objects into ArrayList List in Main.java * @param cList Used to set values for ArrayList List in Main.java * @return The ShipmentOrder variables to List in Main.java **/
Sets ShipmentOrder objects into ArrayList List in Main.java
list
{ "repo_name": "Tjpiano/Past-Projects", "path": "ShipmentOrder.java", "license": "unlicense", "size": 2146 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
1,105,673
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE_RESULT: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { selectImages(); Toast.makeText(activity, R.string.toast_permissions_given, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.toast_insufficient_permissions, Toast.LENGTH_LONG).show(); } } } }
void function(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE_RESULT: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { selectImages(); Toast.makeText(activity, R.string.toast_permissions_given, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.toast_insufficient_permissions, Toast.LENGTH_LONG).show(); } } } }
/** * Called after user is asked to grant permissions * * @param requestCode REQUEST Code for opening permissions * @param permissions permissions asked to user * @param grantResults bool array indicating if permission is granted */
Called after user is asked to grant permissions
onRequestPermissionsResult
{ "repo_name": "Azooz2014/Images-to-PDF", "path": "app/src/main/java/swati4star/createpdf/Home.java", "license": "gpl-3.0", "size": 14853 }
[ "android.content.pm.PackageManager", "android.widget.Toast" ]
import android.content.pm.PackageManager; import android.widget.Toast;
import android.content.pm.*; import android.widget.*;
[ "android.content", "android.widget" ]
android.content; android.widget;
2,705,828
private XMLInputFactory getXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE); factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE); return factory; }
XMLInputFactory function() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(STR, Boolean.TRUE); factory.setProperty(STR, Boolean.FALSE); return factory; }
/** * Creates a new, initialized XML input factory object. * * @return The factory object */
Creates a new, initialized XML input factory object
getXMLInputFactory
{ "repo_name": "papicella/snappy-store", "path": "gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/io/DataReader.java", "license": "apache-2.0", "size": 17997 }
[ "javax.xml.stream.XMLInputFactory" ]
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.*;
[ "javax.xml" ]
javax.xml;
894,542
public List<ListBlock> getListBlocks() { return lists; }
List<ListBlock> function() { return lists; }
/** * Get specified list block. * * @return number of list block */
Get specified list block
getListBlocks
{ "repo_name": "ainoya/redpen", "path": "redpen-core/src/main/java/org/bigram/docvalidator/model/Section.java", "license": "apache-2.0", "size": 7718 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
280,525
protected void addInstanceTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_I3_16xlarge_instanceType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_I3_16xlarge_instanceType_feature", "_UI_I3_16xlarge_type"), Ec2Package.eINSTANCE.getI3_16xlarge_InstanceType(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); }
void function(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString(STR), getString(STR, STR, STR), Ec2Package.eINSTANCE.getI3_16xlarge_InstanceType(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); }
/** * This adds a property descriptor for the Instance Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This adds a property descriptor for the Instance Type feature.
addInstanceTypePropertyDescriptor
{ "repo_name": "occiware/Multi-Cloud-Studio", "path": "plugins/org.eclipse.cmf.occi.multicloud.aws.ec2.edit/src-gen/org/eclipse/cmf/occi/multicloud/aws/ec2/provider/I3_16xlargeItemProvider.java", "license": "epl-1.0", "size": 7049 }
[ "org.eclipse.cmf.occi.multicloud.aws.ec2.Ec2Package", "org.eclipse.emf.edit.provider.ComposeableAdapterFactory", "org.eclipse.emf.edit.provider.ItemPropertyDescriptor" ]
import org.eclipse.cmf.occi.multicloud.aws.ec2.Ec2Package; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.cmf.occi.multicloud.aws.ec2.*; import org.eclipse.emf.edit.provider.*;
[ "org.eclipse.cmf", "org.eclipse.emf" ]
org.eclipse.cmf; org.eclipse.emf;
976,404
public static void addGISTypes72(org.postgresql.PGConnection pgconn) throws SQLException { loadTypesAdder("72").addGT((Connection) pgconn, false); }
static void function(org.postgresql.PGConnection pgconn) throws SQLException { loadTypesAdder("72").addGT((Connection) pgconn, false); }
/** * adds the JTS/PostGIS Data types to a PG 7.2 Connection. * * @throws SQLException */
adds the JTS/PostGIS Data types to a PG 7.2 Connection
addGISTypes72
{ "repo_name": "luisbosque/package-postgis", "path": "java/jdbc/src/org/postgis/DriverWrapper.java", "license": "gpl-2.0", "size": 11872 }
[ "java.sql.Connection", "java.sql.SQLException", "org.postgresql.PGConnection" ]
import java.sql.Connection; import java.sql.SQLException; import org.postgresql.PGConnection;
import java.sql.*; import org.postgresql.*;
[ "java.sql", "org.postgresql" ]
java.sql; org.postgresql;
2,498,159
public static Set<BlockNode> collectBlocksDominatedByWithExcHandlers(MethodNode mth, BlockNode dominator, BlockNode start) { Set<BlockNode> result = new LinkedHashSet<>(); collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), true); return result; }
static Set<BlockNode> function(MethodNode mth, BlockNode dominator, BlockNode start) { Set<BlockNode> result = new LinkedHashSet<>(); collectWhileDominates(dominator, start, result, newBlocksBitSet(mth), true); return result; }
/** * Collect all block dominated by 'dominator', starting from 'start', including exception handlers */
Collect all block dominated by 'dominator', starting from 'start', including exception handlers
collectBlocksDominatedByWithExcHandlers
{ "repo_name": "skylot/jadx", "path": "jadx-core/src/main/java/jadx/core/utils/BlockUtils.java", "license": "apache-2.0", "size": 33022 }
[ "java.util.LinkedHashSet", "java.util.Set" ]
import java.util.LinkedHashSet; import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,753,566
public static ims.ocrr.configuration.domain.objects.InvestigationIndex extractInvestigationIndex(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.InvestigationIndexForNewResulysOcsOrderVo valueObject) { return extractInvestigationIndex(domainFactory, valueObject, new HashMap()); }
static ims.ocrr.configuration.domain.objects.InvestigationIndex function(ims.domain.ILightweightDomainFactory domainFactory, ims.ocrr.vo.InvestigationIndexForNewResulysOcsOrderVo valueObject) { return extractInvestigationIndex(domainFactory, valueObject, new HashMap()); }
/** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */
Create the domain object from the value object
extractInvestigationIndex
{ "repo_name": "openhealthcare/openMAXIMS", "path": "openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/domain/InvestigationIndexForNewResulysOcsOrderVoAssembler.java", "license": "agpl-3.0", "size": 17415 }
[ "java.util.HashMap" ]
import java.util.HashMap;
import java.util.*;
[ "java.util" ]
java.util;
2,512,676
private void writeMetaTable(TableLayoutDesc update) throws IOException { LOG.info("Updating layout for table {} from layout ID {} to layout ID {} in meta-table.", mTableURI, update.getReferenceLayout(), update.getLayoutId()); final String table = update.getName(); mNewLayout = mKiji.getMetaTable().updateTableLayout(table, update); }
void function(TableLayoutDesc update) throws IOException { LOG.info(STR, mTableURI, update.getReferenceLayout(), update.getLayoutId()); final String table = update.getName(); mNewLayout = mKiji.getMetaTable().updateTableLayout(table, update); }
/** * Writes the new table layout to the meta-table. * * @param update Layout update to write to the meta-table. * @throws java.io.IOException on I/O error. */
Writes the new table layout to the meta-table
writeMetaTable
{ "repo_name": "rpinzon/kiji-schema", "path": "kiji-schema-cassandra/src/main/java/org/kiji/schema/impl/cassandra/CassandraTableLayoutUpdater.java", "license": "apache-2.0", "size": 16201 }
[ "java.io.IOException", "org.kiji.schema.avro.TableLayoutDesc" ]
import java.io.IOException; import org.kiji.schema.avro.TableLayoutDesc;
import java.io.*; import org.kiji.schema.avro.*;
[ "java.io", "org.kiji.schema" ]
java.io; org.kiji.schema;
481,772
public List<CtType<?>> getAffectedClasses(){ List<CtType<?>> r = new ArrayList<CtType<?>>(); for (CtClass c:loadClasses.values()) { r.add(c); } return Collections.unmodifiableList(r); }
List<CtType<?>> function(){ List<CtType<?>> r = new ArrayList<CtType<?>>(); for (CtClass c:loadClasses.values()) { r.add(c); } return Collections.unmodifiableList(r); }
/** * Return the classes affected by the variant. Note that those classes are shared between all variant, * so, they do not have applied the changes proposed by the variant after the variant is validated. * @return */
Return the classes affected by the variant. Note that those classes are shared between all variant, so, they do not have applied the changes proposed by the variant after the variant is validated
getAffectedClasses
{ "repo_name": "justinwm/astor", "path": "src/main/java/fr/inria/astor/core/entities/ProgramVariant.java", "license": "gpl-2.0", "size": 7649 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,759,703
public int getHours() { if (getValue().length() == 0) { return -1; } else { try { return JSDateUtil.getHours(getValue()); } catch (Exception e) { //if unparseable return -1 return -1; } } }
int function() { if (getValue().length() == 0) { return -1; } else { try { return JSDateUtil.getHours(getValue()); } catch (Exception e) { return -1; } } }
/** * Gets the current hours value of the text box * * @return the hours value or -1 if it isn't specified */
Gets the current hours value of the text box
getHours
{ "repo_name": "spiffyui/spiffyui", "path": "spiffyui/src/main/java/org/spiffyui/client/widgets/TimePickerTextBox.java", "license": "apache-2.0", "size": 6346 }
[ "org.spiffyui.client.JSDateUtil" ]
import org.spiffyui.client.JSDateUtil;
import org.spiffyui.client.*;
[ "org.spiffyui.client" ]
org.spiffyui.client;
2,024,637
@Override protected void fixInstanceClass(EClassifier eClassifier) { if (eClassifier.getInstanceClassName() == null) { eClassifier.setInstanceClassName("CIM15.IEC61970.SCADA." + eClassifier.getName()); setGeneratedClassName(eClassifier); } } public interface Literals { public static final EClass REMOTE_SOURCE = eINSTANCE.getRemoteSource(); public static final EAttribute REMOTE_SOURCE__SENSOR_MINIMUM = eINSTANCE.getRemoteSource_SensorMinimum(); public static final EAttribute REMOTE_SOURCE__DEADBAND = eINSTANCE.getRemoteSource_Deadband(); public static final EAttribute REMOTE_SOURCE__SENSOR_MAXIMUM = eINSTANCE.getRemoteSource_SensorMaximum(); public static final EAttribute REMOTE_SOURCE__SCAN_INTERVAL = eINSTANCE.getRemoteSource_ScanInterval(); public static final EReference REMOTE_SOURCE__MEASUREMENT_VALUE = eINSTANCE.getRemoteSource_MeasurementValue(); public static final EClass REMOTE_POINT = eINSTANCE.getRemotePoint(); public static final EReference REMOTE_POINT__REMOTE_UNIT = eINSTANCE.getRemotePoint_RemoteUnit(); public static final EClass REMOTE_UNIT = eINSTANCE.getRemoteUnit(); public static final EAttribute REMOTE_UNIT__REMOTE_UNIT_TYPE = eINSTANCE.getRemoteUnit_RemoteUnitType(); public static final EReference REMOTE_UNIT__REMOTE_POINTS = eINSTANCE.getRemoteUnit_RemotePoints(); public static final EReference REMOTE_UNIT__COMMUNICATION_LINKS = eINSTANCE.getRemoteUnit_CommunicationLinks(); public static final EClass REMOTE_CONTROL = eINSTANCE.getRemoteControl(); public static final EReference REMOTE_CONTROL__CONTROL = eINSTANCE.getRemoteControl_Control(); public static final EAttribute REMOTE_CONTROL__ACTUATOR_MAXIMUM = eINSTANCE.getRemoteControl_ActuatorMaximum(); public static final EAttribute REMOTE_CONTROL__ACTUATOR_MINIMUM = eINSTANCE.getRemoteControl_ActuatorMinimum(); public static final EAttribute REMOTE_CONTROL__REMOTE_CONTROLLED = eINSTANCE.getRemoteControl_RemoteControlled(); public static final EClass COMMUNICATION_LINK = eINSTANCE.getCommunicationLink(); public static final EReference COMMUNICATION_LINK__REMOTE_UNITS = eINSTANCE.getCommunicationLink_RemoteUnits(); public static final EEnum REMOTE_UNIT_TYPE = eINSTANCE.getRemoteUnitType(); public static final EEnum SOURCE = eINSTANCE.getSource(); }
void function(EClassifier eClassifier) { if (eClassifier.getInstanceClassName() == null) { eClassifier.setInstanceClassName(STR + eClassifier.getName()); setGeneratedClassName(eClassifier); } } public interface Literals { public static final EClass REMOTE_SOURCE = eINSTANCE.getRemoteSource(); public static final EAttribute REMOTE_SOURCE__SENSOR_MINIMUM = eINSTANCE.getRemoteSource_SensorMinimum(); public static final EAttribute REMOTE_SOURCE__DEADBAND = eINSTANCE.getRemoteSource_Deadband(); public static final EAttribute REMOTE_SOURCE__SENSOR_MAXIMUM = eINSTANCE.getRemoteSource_SensorMaximum(); public static final EAttribute REMOTE_SOURCE__SCAN_INTERVAL = eINSTANCE.getRemoteSource_ScanInterval(); public static final EReference REMOTE_SOURCE__MEASUREMENT_VALUE = eINSTANCE.getRemoteSource_MeasurementValue(); public static final EClass REMOTE_POINT = eINSTANCE.getRemotePoint(); public static final EReference REMOTE_POINT__REMOTE_UNIT = eINSTANCE.getRemotePoint_RemoteUnit(); public static final EClass REMOTE_UNIT = eINSTANCE.getRemoteUnit(); public static final EAttribute REMOTE_UNIT__REMOTE_UNIT_TYPE = eINSTANCE.getRemoteUnit_RemoteUnitType(); public static final EReference REMOTE_UNIT__REMOTE_POINTS = eINSTANCE.getRemoteUnit_RemotePoints(); public static final EReference REMOTE_UNIT__COMMUNICATION_LINKS = eINSTANCE.getRemoteUnit_CommunicationLinks(); public static final EClass REMOTE_CONTROL = eINSTANCE.getRemoteControl(); public static final EReference REMOTE_CONTROL__CONTROL = eINSTANCE.getRemoteControl_Control(); public static final EAttribute REMOTE_CONTROL__ACTUATOR_MAXIMUM = eINSTANCE.getRemoteControl_ActuatorMaximum(); public static final EAttribute REMOTE_CONTROL__ACTUATOR_MINIMUM = eINSTANCE.getRemoteControl_ActuatorMinimum(); public static final EAttribute REMOTE_CONTROL__REMOTE_CONTROLLED = eINSTANCE.getRemoteControl_RemoteControlled(); public static final EClass COMMUNICATION_LINK = eINSTANCE.getCommunicationLink(); public static final EReference COMMUNICATION_LINK__REMOTE_UNITS = eINSTANCE.getCommunicationLink_RemoteUnits(); public static final EEnum REMOTE_UNIT_TYPE = eINSTANCE.getRemoteUnitType(); public static final EEnum SOURCE = eINSTANCE.getSource(); }
/** * Sets the instance class on the given classifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
Sets the instance class on the given classifier.
fixInstanceClass
{ "repo_name": "SES-fortiss/SmartGridCoSimulation", "path": "core/cim15/src/CIM15/IEC61970/SCADA/SCADAPackage.java", "license": "apache-2.0", "size": 65525 }
[ "org.eclipse.emf.ecore.EAttribute", "org.eclipse.emf.ecore.EClass", "org.eclipse.emf.ecore.EClassifier", "org.eclipse.emf.ecore.EEnum", "org.eclipse.emf.ecore.EReference" ]
import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,092,983
public static List<String[]> getProfilesJsp(Set<CapProfile> selected) { selected = selected == null ? ImmutableSet.<CapProfile>of() : selected; List<String[]> ret = Lists.newArrayList(); for (CapProfile profile : CapProfiles.getProfiles()) { String checked = (selected.contains(profile) ? "checked" : ""); ret.add(new String[] {profile.getCode(), checked, profile.getDocumentationUrl(), profile.getName()}); } return ret; }
static List<String[]> function(Set<CapProfile> selected) { selected = selected == null ? ImmutableSet.<CapProfile>of() : selected; List<String[]> ret = Lists.newArrayList(); for (CapProfile profile : CapProfiles.getProfiles()) { String checked = (selected.contains(profile) ? STR : ""); ret.add(new String[] {profile.getCode(), checked, profile.getDocumentationUrl(), profile.getName()}); } return ret; }
/** * Returns the given set of selected cap profiles in a format * suitable for displaying in the validator JSPs. * * @param selected the selected CAP profiles, may be empty * @return the JSP-formatted profiles */
Returns the given set of selected cap profiles in a format suitable for displaying in the validator JSPs
getProfilesJsp
{ "repo_name": "google/cap-library", "path": "validator/src/com/google/publicalerts/cap/validator/ValidatorUtil.java", "license": "apache-2.0", "size": 4685 }
[ "com.google.common.collect.ImmutableSet", "com.google.common.collect.Lists", "com.google.publicalerts.cap.profile.CapProfile", "com.google.publicalerts.cap.profile.CapProfiles", "java.util.List", "java.util.Set" ]
import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.publicalerts.cap.profile.CapProfile; import com.google.publicalerts.cap.profile.CapProfiles; import java.util.List; import java.util.Set;
import com.google.common.collect.*; import com.google.publicalerts.cap.profile.*; import java.util.*;
[ "com.google.common", "com.google.publicalerts", "java.util" ]
com.google.common; com.google.publicalerts; java.util;
641,407
public void updateItem(FileDataObjectWrapper fdow) throws DAOException { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { FileDataObject fdo = fdow.getFileDataObject(); Long fdoId = Long.valueOf(fdow.getId()); Timestamp currentTime = new Timestamp(System.currentTimeMillis()); StringBuilder updateQuery = new StringBuilder(); updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_BEGIN); updateQuery.append(SQL_FIELD_LAST_UPDATE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_STATUS) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_UPLOAD_STATUS) .append(SQL_EQUALS_QUESTIONMARK_COMMA); String localName = fdow.getLocalName(); if (localName != null) { updateQuery.append(SQL_FIELD_LOCAL_NAME) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } else { // if the item was deleted and readded again with a sync // considering only the metadata, the local name must be set to // null, since the previous file was already deleted and the new // file would be uploaded later. updateQuery.append(SQL_FIELD_LOCAL_NAME) .append(SQL_EQUALS_NULL_COMMA); } Long crc = Long.valueOf(fdow.getFileDataObject().getCrc()); updateQuery.append(SQL_FIELD_CRC) .append(SQL_EQUALS_QUESTIONMARK_COMMA); String trueName = fdo.getName(); if (trueName != null) { updateQuery.append(SQL_FIELD_TRUE_NAME) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified()); Timestamp created = timestamp(fdo.getCreated()); if (created == null) { created = currentTime; } Timestamp modified = timestamp(fdo.getModified()); if (modified == null) { modified = currentTime; } updateQuery.append(SQL_FIELD_CREATED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_MODIFIED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); Timestamp accessed = timestamp(fdo.getAccessed()); if (accessed != null) { updateQuery.append(SQL_FIELD_ACCESSED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean hidden = fdo.getHidden(); if (hidden != null) { updateQuery.append(SQL_FIELD_H) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean system = fdo.getSystem(); if (system != null) { updateQuery.append(SQL_FIELD_S) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean archived = fdo.getArchived(); if (archived != null) { updateQuery.append(SQL_FIELD_A) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean deleted = fdo.getDeleted(); if (deleted != null) { updateQuery.append(SQL_FIELD_D) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean writable = fdo.getWritable(); if (writable != null) { updateQuery.append(SQL_FIELD_W) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean readable = fdo.getReadable(); if (readable != null) { updateQuery.append(SQL_FIELD_R) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean executable = fdo.getExecutable(); if (executable != null) { updateQuery.append(SQL_FIELD_X) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } String contentType = fdo.getContentType(); if (contentType != null) { updateQuery.append(SQL_FIELD_CTTYPE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Long size = fdo.getSize(); if (size != null) { updateQuery.append(SQL_FIELD_SIZE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Long sizeOnStorage = fdow.getSizeOnStorage(); if (sizeOnStorage != null) { updateQuery.append(SQL_FIELD_SIZE_ON_STORAGE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } if (updateQuery.charAt(updateQuery.length() - 2) == ','){ updateQuery.deleteCharAt(updateQuery.length() - 2); } updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_END); // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); ps = con.prepareStatement(updateQuery.toString()); int k = 1; Timestamp lastUpdate = (fdow.getLastUpdate() == null) ? currentTime : fdow.getLastUpdate(); ps.setLong(k++, lastUpdate.getTime()); ps.setString(k++, String.valueOf(Def.PIM_STATE_UPDATED)); ps.setString(k++, String.valueOf(fdo.getUploadStatus())); if (localName != null){ ps.setString(k++, StringUtils.left(localName, SQL_LOCAL_NAME_DIM)); } ps.setLong(k++, crc); if (trueName != null) { ps.setString(k++, StringUtils.left(trueName, SQL_TRUE_NAME_DIM)); } // cannot be null ps.setTimestamp(k++, created); ps.setTimestamp(k++, modified); if (accessed != null) { ps.setTimestamp(k++, accessed); } if (hidden != null) { ps.setString(k++, hidden ? ONE : NIL); } if (system != null) { ps.setString(k++, system ? ONE : NIL); } if (archived != null) { ps.setString(k++, archived ? ONE : NIL); } if (deleted != null) { ps.setString(k++, deleted ? ONE : NIL); } if (writable != null) { ps.setString(k++, writable ? ONE : NIL); } if (readable != null) { ps.setString(k++, readable ? ONE : NIL); } if (executable != null) { ps.setString(k++, executable ? ONE : NIL); } if (contentType != null) { ps.setString(k++, StringUtils.left(contentType, SQL_CTTYPE_DIM)); } if (size != null) { ps.setLong(k++, size); } if (sizeOnStorage != null) { ps.setLong(k++, sizeOnStorage); } ps.setLong(k++, fdoId); ps.setString(k++, userId); ps.setString(k++, sourceURI); ps.executeUpdate(); // delete and add the properties associated to the new FDO removeAllProperties(fdow.getId()); addProperties(fdow); } catch (Exception e) { throw new DAOException("Error updating file data object.", e); } finally { DBTools.close(con, ps, rs); } }
void function(FileDataObjectWrapper fdow) throws DAOException { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { FileDataObject fdo = fdow.getFileDataObject(); Long fdoId = Long.valueOf(fdow.getId()); Timestamp currentTime = new Timestamp(System.currentTimeMillis()); StringBuilder updateQuery = new StringBuilder(); updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_BEGIN); updateQuery.append(SQL_FIELD_LAST_UPDATE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_STATUS) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_UPLOAD_STATUS) .append(SQL_EQUALS_QUESTIONMARK_COMMA); String localName = fdow.getLocalName(); if (localName != null) { updateQuery.append(SQL_FIELD_LOCAL_NAME) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } else { updateQuery.append(SQL_FIELD_LOCAL_NAME) .append(SQL_EQUALS_NULL_COMMA); } Long crc = Long.valueOf(fdow.getFileDataObject().getCrc()); updateQuery.append(SQL_FIELD_CRC) .append(SQL_EQUALS_QUESTIONMARK_COMMA); String trueName = fdo.getName(); if (trueName != null) { updateQuery.append(SQL_FIELD_TRUE_NAME) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified()); Timestamp created = timestamp(fdo.getCreated()); if (created == null) { created = currentTime; } Timestamp modified = timestamp(fdo.getModified()); if (modified == null) { modified = currentTime; } updateQuery.append(SQL_FIELD_CREATED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); updateQuery.append(SQL_FIELD_MODIFIED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); Timestamp accessed = timestamp(fdo.getAccessed()); if (accessed != null) { updateQuery.append(SQL_FIELD_ACCESSED) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean hidden = fdo.getHidden(); if (hidden != null) { updateQuery.append(SQL_FIELD_H) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean system = fdo.getSystem(); if (system != null) { updateQuery.append(SQL_FIELD_S) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean archived = fdo.getArchived(); if (archived != null) { updateQuery.append(SQL_FIELD_A) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean deleted = fdo.getDeleted(); if (deleted != null) { updateQuery.append(SQL_FIELD_D) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean writable = fdo.getWritable(); if (writable != null) { updateQuery.append(SQL_FIELD_W) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean readable = fdo.getReadable(); if (readable != null) { updateQuery.append(SQL_FIELD_R) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Boolean executable = fdo.getExecutable(); if (executable != null) { updateQuery.append(SQL_FIELD_X) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } String contentType = fdo.getContentType(); if (contentType != null) { updateQuery.append(SQL_FIELD_CTTYPE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Long size = fdo.getSize(); if (size != null) { updateQuery.append(SQL_FIELD_SIZE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } Long sizeOnStorage = fdow.getSizeOnStorage(); if (sizeOnStorage != null) { updateQuery.append(SQL_FIELD_SIZE_ON_STORAGE) .append(SQL_EQUALS_QUESTIONMARK_COMMA); } if (updateQuery.charAt(updateQuery.length() - 2) == ','){ updateQuery.deleteCharAt(updateQuery.length() - 2); } updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_END); con = getUserDataSource().getRoutedConnection(userId); ps = con.prepareStatement(updateQuery.toString()); int k = 1; Timestamp lastUpdate = (fdow.getLastUpdate() == null) ? currentTime : fdow.getLastUpdate(); ps.setLong(k++, lastUpdate.getTime()); ps.setString(k++, String.valueOf(Def.PIM_STATE_UPDATED)); ps.setString(k++, String.valueOf(fdo.getUploadStatus())); if (localName != null){ ps.setString(k++, StringUtils.left(localName, SQL_LOCAL_NAME_DIM)); } ps.setLong(k++, crc); if (trueName != null) { ps.setString(k++, StringUtils.left(trueName, SQL_TRUE_NAME_DIM)); } ps.setTimestamp(k++, created); ps.setTimestamp(k++, modified); if (accessed != null) { ps.setTimestamp(k++, accessed); } if (hidden != null) { ps.setString(k++, hidden ? ONE : NIL); } if (system != null) { ps.setString(k++, system ? ONE : NIL); } if (archived != null) { ps.setString(k++, archived ? ONE : NIL); } if (deleted != null) { ps.setString(k++, deleted ? ONE : NIL); } if (writable != null) { ps.setString(k++, writable ? ONE : NIL); } if (readable != null) { ps.setString(k++, readable ? ONE : NIL); } if (executable != null) { ps.setString(k++, executable ? ONE : NIL); } if (contentType != null) { ps.setString(k++, StringUtils.left(contentType, SQL_CTTYPE_DIM)); } if (size != null) { ps.setLong(k++, size); } if (sizeOnStorage != null) { ps.setLong(k++, sizeOnStorage); } ps.setLong(k++, fdoId); ps.setString(k++, userId); ps.setString(k++, sourceURI); ps.executeUpdate(); removeAllProperties(fdow.getId()); addProperties(fdow); } catch (Exception e) { throw new DAOException(STR, e); } finally { DBTools.close(con, ps, rs); } }
/** * Updates file data object metadata. <code>content</code> is not used. * @param fdow * @throws com.funambol.foundation.exception.DAOException */
Updates file data object metadata. <code>content</code> is not used
updateItem
{ "repo_name": "accesstest3/cfunambol", "path": "modules/foundation/foundation-core/src/main/java/com/funambol/foundation/items/dao/DataBaseFileDataObjectMetadataDAO.java", "license": "agpl-3.0", "size": 52651 }
[ "com.funambol.common.media.file.FileDataObject", "com.funambol.foundation.exception.DAOException", "com.funambol.foundation.items.model.FileDataObjectWrapper", "com.funambol.foundation.util.Def", "com.funambol.foundation.util.MediaUtils", "com.funambol.framework.tools.DBTools", "java.sql.Connection", "java.sql.PreparedStatement", "java.sql.ResultSet", "java.sql.Timestamp", "org.apache.commons.lang.StringUtils" ]
import com.funambol.common.media.file.FileDataObject; import com.funambol.foundation.exception.DAOException; import com.funambol.foundation.items.model.FileDataObjectWrapper; import com.funambol.foundation.util.Def; import com.funambol.foundation.util.MediaUtils; import com.funambol.framework.tools.DBTools; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import org.apache.commons.lang.StringUtils;
import com.funambol.common.media.file.*; import com.funambol.foundation.exception.*; import com.funambol.foundation.items.model.*; import com.funambol.foundation.util.*; import com.funambol.framework.tools.*; import java.sql.*; import org.apache.commons.lang.*;
[ "com.funambol.common", "com.funambol.foundation", "com.funambol.framework", "java.sql", "org.apache.commons" ]
com.funambol.common; com.funambol.foundation; com.funambol.framework; java.sql; org.apache.commons;
2,785,411
private void resolveResult(Status status, int requestCode) { // We don't want to fire multiple resolutions at once since that can result // in stacked dialogs after rotation or another similar event. if (mIsResolving) { Log.w(TAG, "resolveResult: already resolving."); return; } Log.d(TAG, "Resolving: " + status); if (status.hasResolution()) { Log.d(TAG, "STATUS: RESOLVING"); try { status.startResolutionForResult(MainActivity.this, requestCode); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, "STATUS: Failed to send resolution.", e); hideProgress(); } } else { Log.e(TAG, "STATUS: FAIL"); showToast("Could Not Resolve Error"); hideProgress(); } }
void function(Status status, int requestCode) { if (mIsResolving) { Log.w(TAG, STR); return; } Log.d(TAG, STR + status); if (status.hasResolution()) { Log.d(TAG, STR); try { status.startResolutionForResult(MainActivity.this, requestCode); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, STR, e); hideProgress(); } } else { Log.e(TAG, STR); showToast(STR); hideProgress(); } }
/** * Attempt to resolve a non-successful Status from an asynchronous request. * @param status the Status to resolve. * @param requestCode the request code to use when starting an Activity for result, * this will be passed back to onActivityResult. */
Attempt to resolve a non-successful Status from an asynchronous request
resolveResult
{ "repo_name": "Pan-Gaj/GoogleSmartLock", "path": "app/src/main/java/com/shruthi/pangaj/googlesmartlock/MainActivity.java", "license": "apache-2.0", "size": 19222 }
[ "android.content.IntentSender", "android.util.Log", "com.google.android.gms.common.api.Status" ]
import android.content.IntentSender; import android.util.Log; import com.google.android.gms.common.api.Status;
import android.content.*; import android.util.*; import com.google.android.gms.common.api.*;
[ "android.content", "android.util", "com.google.android" ]
android.content; android.util; com.google.android;
1,002,520
public ClipData getPrimaryClip() { try { return getService().getPrimaryClip(mContext.getOpPackageName()); } catch (RemoteException e) { return null; } }
ClipData function() { try { return getService().getPrimaryClip(mContext.getOpPackageName()); } catch (RemoteException e) { return null; } }
/** * Returns the current primary clip on the clipboard. */
Returns the current primary clip on the clipboard
getPrimaryClip
{ "repo_name": "JSDemos/android-sdk-20", "path": "src/android/content/ClipboardManager.java", "license": "apache-2.0", "size": 7730 }
[ "android.os.RemoteException" ]
import android.os.RemoteException;
import android.os.*;
[ "android.os" ]
android.os;
978,050
@Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // return (new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) { // @Override // protected boolean accept(Field f) { // return super.accept(f) && !f.getName().equals("metadata"); // } // }).toString(); }
String function() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); }
/** * <p> * Uses <code>ReflectionToStringBuilder</code> to generate a <code>toString</code> for the specified object. * </p> * * @return the String result * @see ReflectionToStringBuilder#toString(Object) */
Uses <code>ReflectionToStringBuilder</code> to generate a <code>toString</code> for the specified object.
toString
{ "repo_name": "mlaggner/tinyMediaManager", "path": "src/org/tinymediamanager/scraper/MediaSearchResult.java", "license": "apache-2.0", "size": 5836 }
[ "org.apache.commons.lang3.builder.ToStringBuilder", "org.apache.commons.lang3.builder.ToStringStyle" ]
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.builder.*;
[ "org.apache.commons" ]
org.apache.commons;
168,865
public Journal create(Journal journal)throws Exception { HashMap<String, Object> requestBody = getQueryMap(); requestBody.put("JSONString", journal.toJSON().toString()); String response = ZohoHTTPClient.post(url, requestBody); return journalParser.getJournal(response); }
Journal function(Journal journal)throws Exception { HashMap<String, Object> requestBody = getQueryMap(); requestBody.put(STR, journal.toJSON().toString()); String response = ZohoHTTPClient.post(url, requestBody); return journalParser.getJournal(response); }
/** * Create a journal. * Pass the Journal object to create a journal. * The Journal object which contains journalDate, amount, and debitOrCredit are the mandatory parameters. * It returns the Journal object. * @param journal Journal object. * @return Returns the Journal object. */
Create a journal. Pass the Journal object to create a journal. The Journal object which contains journalDate, amount, and debitOrCredit are the mandatory parameters. It returns the Journal object
create
{ "repo_name": "zoho/books-java-wrappers", "path": "source/com/zoho/books/api/JournalsApi.java", "license": "mit", "size": 5195 }
[ "com.zoho.books.model.Journal", "com.zoho.books.util.ZohoHTTPClient", "java.util.HashMap" ]
import com.zoho.books.model.Journal; import com.zoho.books.util.ZohoHTTPClient; import java.util.HashMap;
import com.zoho.books.model.*; import com.zoho.books.util.*; import java.util.*;
[ "com.zoho.books", "java.util" ]
com.zoho.books; java.util;
1,279,846
@Generated @Selector("menuForIdentifier:") UIMenu menuForIdentifier(String identifier);
@Selector(STR) UIMenu menuForIdentifier(String identifier);
/** * Fetch the identified menu. * * @param identifier The identifier of the menu to fetch. * @return The menu with the given identifier, or `nil` if no such menu. */
Fetch the identified menu
menuForIdentifier
{ "repo_name": "multi-os-engine/moe-core", "path": "moe.apple/moe.platform.ios/src/main/java/apple/uikit/protocol/UIMenuBuilder.java", "license": "apache-2.0", "size": 5128 }
[ "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;
724,792
public JPanel getOrderPanel() { return orderPanel; }
JPanel function() { return orderPanel; }
/** * Gets the order window for the box. * * @return The order window. */
Gets the order window for the box
getOrderPanel
{ "repo_name": "tpunt/FlexBox", "path": "src/com/thomaspunt/flexbox/guibuilder/OrderingTabGUI.java", "license": "mit", "size": 30789 }
[ "javax.swing.JPanel" ]
import javax.swing.JPanel;
import javax.swing.*;
[ "javax.swing" ]
javax.swing;
2,505,862
public static void assertStringContains(String text, String containedText) { assertNotNull(text, "Text should not be null!"); assertTrue(text.contains(containedText), "Text: " + text + " does not contain: " + containedText); }
static void function(String text, String containedText) { assertNotNull(text, STR); assertTrue(text.contains(containedText), STR + text + STR + containedText); }
/** * Asserts that the text contains the given string * * @param text the text to compare * @param containedText the text which must be contained inside the other text parameter */
Asserts that the text contains the given string
assertStringContains
{ "repo_name": "nikhilvibhav/camel", "path": "core/camel-core/src/test/java/org/apache/camel/TestSupport.java", "license": "apache-2.0", "size": 24554 }
[ "org.junit.jupiter.api.Assertions" ]
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.*;
[ "org.junit.jupiter" ]
org.junit.jupiter;
1,168,962
public static String getSessionId(Object component) { StringBuilder sb = new StringBuilder(); if (component instanceof Handler) { sb.append(((Handler)component).getId()); } else if (component instanceof SessionCoordinator) { sb.append(((SessionCoordinator)component).getId()); } else if (component instanceof TcpClient) { sb.append(((TcpClient)component).getId()); } else if (component instanceof TcpServer) { sb.append(((TcpServer)component).getId()); } else if (component instanceof TcpWorker) { sb.append(((TcpWorker)component).getId()); } else if (component instanceof PriorityNamedTask) { sb.append(((PriorityNamedTask)component).getName()); } else { sb.append("Undefined"); } return sb.toString(); }
static String function(Object component) { StringBuilder sb = new StringBuilder(); if (component instanceof Handler) { sb.append(((Handler)component).getId()); } else if (component instanceof SessionCoordinator) { sb.append(((SessionCoordinator)component).getId()); } else if (component instanceof TcpClient) { sb.append(((TcpClient)component).getId()); } else if (component instanceof TcpServer) { sb.append(((TcpServer)component).getId()); } else if (component instanceof TcpWorker) { sb.append(((TcpWorker)component).getId()); } else if (component instanceof PriorityNamedTask) { sb.append(((PriorityNamedTask)component).getName()); } else { sb.append(STR); } return sb.toString(); }
/** * Retrieve the session id for a given component. * @param component component * @return session ID */
Retrieve the session id for a given component
getSessionId
{ "repo_name": "marvisan/HadesFIX", "path": "Engine/src/main/java/net/hades/fix/engine/util/PartyUtil.java", "license": "gpl-3.0", "size": 5503 }
[ "net.hades.fix.engine.handler.Handler", "net.hades.fix.engine.process.PriorityNamedTask", "net.hades.fix.engine.process.session.SessionCoordinator", "net.hades.fix.engine.process.transport.TcpClient", "net.hades.fix.engine.process.transport.TcpServer", "net.hades.fix.engine.process.transport.TcpWorker" ]
import net.hades.fix.engine.handler.Handler; import net.hades.fix.engine.process.PriorityNamedTask; import net.hades.fix.engine.process.session.SessionCoordinator; import net.hades.fix.engine.process.transport.TcpClient; import net.hades.fix.engine.process.transport.TcpServer; import net.hades.fix.engine.process.transport.TcpWorker;
import net.hades.fix.engine.handler.*; import net.hades.fix.engine.process.*; import net.hades.fix.engine.process.session.*; import net.hades.fix.engine.process.transport.*;
[ "net.hades.fix" ]
net.hades.fix;
1,633,661
private static List<ReplaceableItem> createSampleData() { List<ReplaceableItem> sampleData = new ArrayList<ReplaceableItem>(); sampleData.add(new ReplaceableItem("Item_01").withAttributes( new ReplaceableAttribute("Category", "Clothes", true), new ReplaceableAttribute("Subcategory", "Sweater", true), new ReplaceableAttribute("Name", "Cathair Sweater", true), new ReplaceableAttribute("Color", "Siamese", true), new ReplaceableAttribute("Size", "Small", true), new ReplaceableAttribute("Size", "Medium", true), new ReplaceableAttribute("Size", "Large", true))); sampleData.add(new ReplaceableItem("Item_02").withAttributes( new ReplaceableAttribute("Category", "Clothes", true), new ReplaceableAttribute("Subcategory","Pants", true), new ReplaceableAttribute("Name", "Designer Jeans", true), new ReplaceableAttribute("Color", "Paisley Acid Wash", true), new ReplaceableAttribute("Size", "30x32", true), new ReplaceableAttribute("Size", "32x32", true), new ReplaceableAttribute("Size", "32x34", true))); sampleData.add(new ReplaceableItem("Item_03").withAttributes( new ReplaceableAttribute("Category", "Clothes", true), new ReplaceableAttribute("Subcategory", "Pants", true), new ReplaceableAttribute("Name", "Sweatpants", true), new ReplaceableAttribute("Color", "Blue", true), new ReplaceableAttribute("Color", "Yellow", true), new ReplaceableAttribute("Color", "Pink", true), new ReplaceableAttribute("Size", "Large", true), new ReplaceableAttribute("Year", "2006", true), new ReplaceableAttribute("Year", "2007", true))); sampleData.add(new ReplaceableItem("Item_04").withAttributes( new ReplaceableAttribute("Category", "Car Parts", true), new ReplaceableAttribute("Subcategory", "Engine", true), new ReplaceableAttribute("Name", "Turbos", true), new ReplaceableAttribute("Make", "Audi", true), new ReplaceableAttribute("Model", "S4", true), new ReplaceableAttribute("Year", "2000", true), new ReplaceableAttribute("Year", "2001", true), new ReplaceableAttribute("Year", "2002", true))); sampleData.add(new ReplaceableItem("Item_05").withAttributes( new ReplaceableAttribute("Category", "Car Parts", true), new ReplaceableAttribute("Subcategory", "Emissions", true), new ReplaceableAttribute("Name", "O2 Sensor", true), new ReplaceableAttribute("Make", "Audi", true), new ReplaceableAttribute("Model", "S4", true), new ReplaceableAttribute("Year", "2000", true), new ReplaceableAttribute("Year", "2001", true), new ReplaceableAttribute("Year", "2002", true))); return sampleData; }
static List<ReplaceableItem> function() { List<ReplaceableItem> sampleData = new ArrayList<ReplaceableItem>(); sampleData.add(new ReplaceableItem(STR).withAttributes( new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute("Name", STR, true), new ReplaceableAttribute("Color", STR, true), new ReplaceableAttribute("Size", "Small", true), new ReplaceableAttribute("Size", STR, true), new ReplaceableAttribute("Size", "Large", true))); sampleData.add(new ReplaceableItem(STR).withAttributes( new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute(STR,"Pants", true), new ReplaceableAttribute("Name", STR, true), new ReplaceableAttribute("Color", STR, true), new ReplaceableAttribute("Size", "30x32", true), new ReplaceableAttribute("Size", "32x32", true), new ReplaceableAttribute("Size", "32x34", true))); sampleData.add(new ReplaceableItem(STR).withAttributes( new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute(STR, "Pants", true), new ReplaceableAttribute("Name", STR, true), new ReplaceableAttribute("Color", "Blue", true), new ReplaceableAttribute("Color", STR, true), new ReplaceableAttribute("Color", "Pink", true), new ReplaceableAttribute("Size", "Large", true), new ReplaceableAttribute("Year", "2006", true), new ReplaceableAttribute("Year", "2007", true))); sampleData.add(new ReplaceableItem(STR).withAttributes( new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute("Name", STR, true), new ReplaceableAttribute("Make", "Audi", true), new ReplaceableAttribute("Model", "S4", true), new ReplaceableAttribute("Year", "2000", true), new ReplaceableAttribute("Year", "2001", true), new ReplaceableAttribute("Year", "2002", true))); sampleData.add(new ReplaceableItem(STR).withAttributes( new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute(STR, STR, true), new ReplaceableAttribute("Name", STR, true), new ReplaceableAttribute("Make", "Audi", true), new ReplaceableAttribute("Model", "S4", true), new ReplaceableAttribute("Year", "2000", true), new ReplaceableAttribute("Year", "2001", true), new ReplaceableAttribute("Year", "2002", true))); return sampleData; }
/** * Creates an array of SimpleDB ReplaceableItems populated with sample data. * * @return An array of sample item data. */
Creates an array of SimpleDB ReplaceableItems populated with sample data
createSampleData
{ "repo_name": "hobinyoon/aws-java-sdk-1.4.7", "path": "samples/AmazonSimpleDB/SimpleDBSample.java", "license": "apache-2.0", "size": 10516 }
[ "com.amazonaws.services.simpledb.model.ReplaceableAttribute", "com.amazonaws.services.simpledb.model.ReplaceableItem", "java.util.ArrayList", "java.util.List" ]
import com.amazonaws.services.simpledb.model.ReplaceableAttribute; import com.amazonaws.services.simpledb.model.ReplaceableItem; import java.util.ArrayList; import java.util.List;
import com.amazonaws.services.simpledb.model.*; import java.util.*;
[ "com.amazonaws.services", "java.util" ]
com.amazonaws.services; java.util;
1,430,041
public void testParameterParsing() { String param1 = "Param1"; String param2 = "Param1"; // Check for correct behaviour if no params. CommandLineParser clp = new CommandLineParser(new String[]{"-klf", "--option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Check for correct behaviour if no params but option params. clp = new CommandLineParser(new String[]{"-klf", "--option1", "option1parameter"}, new String[]{"option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Simple param passing. clp = new CommandLineParser(new String[]{param1}); // See if args are detected. Assert.assertTrue(clp.hasArguments()); // We should have non-null, non-zerolength params array. String[] result = clp.getParameters(); Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // See how many params are found. Assert.assertTrue(result.length == 1); // Check the param. Assert.assertEquals(param1, result[0]); // Multiple params. clp = new CommandLineParser(new String[]{param1, param2}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference. clp = new CommandLineParser(new String[]{"--Option1", param1, "-klf", "-g", param2, "--Option2"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference & option parameters. clp = new CommandLineParser(new String[]{"--Option1", "optionparam1", param1, "-klf", "-g", param2, "--Option2"}, new String[]{"Option1"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); }
void function() { String param1 = STR; String param2 = STR; CommandLineParser clp = new CommandLineParser(new String[]{"-klf", STR}); Assert.assertTrue(clp.getParameters().length == 0); clp = new CommandLineParser(new String[]{"-klf", STR, STR}, new String[]{STR}); Assert.assertTrue(clp.getParameters().length == 0); clp = new CommandLineParser(new String[]{param1}); Assert.assertTrue(clp.hasArguments()); String[] result = clp.getParameters(); Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); Assert.assertTrue(result.length == 1); Assert.assertEquals(param1, result[0]); clp = new CommandLineParser(new String[]{param1, param2}); result = clp.getParameters(); Assert.assertTrue(result.length == 2); Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); clp = new CommandLineParser(new String[]{STR, param1, "-klf", "-g", param2, STR}); result = clp.getParameters(); Assert.assertTrue(result.length == 2); Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); clp = new CommandLineParser(new String[]{STR, STR, param1, "-klf", "-g", param2, STR}, new String[]{STR}); result = clp.getParameters(); Assert.assertTrue(result.length == 2); Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); }
/** * This method test the parsing of parameters. */
This method test the parsing of parameters
testParameterParsing
{ "repo_name": "compomics/compomics-utilities", "path": "src/test/java/com/compomics/util/test/general/TestCommandLineParser.java", "license": "apache-2.0", "size": 12721 }
[ "com.compomics.util.general.CommandLineParser", "org.junit.Assert" ]
import com.compomics.util.general.CommandLineParser; import org.junit.Assert;
import com.compomics.util.general.*; import org.junit.*;
[ "com.compomics.util", "org.junit" ]
com.compomics.util; org.junit;
341,012
@Override public void setCatalog(String catalog) throws SQLException { throw JdbcException.getUnsupportedException("setCatalog unsupported"); }
void function(String catalog) throws SQLException { throw JdbcException.getUnsupportedException(STR); }
/** * Set the default catalog name. This call is ignored. * * @param catalog * ignored * @throws java.sql.SQLException * if the connection is closed */
Set the default catalog name. This call is ignored
setCatalog
{ "repo_name": "fengshao0907/wasp", "path": "src/main/java/com/alibaba/wasp/jdbc/JdbcConnection.java", "license": "apache-2.0", "size": 28314 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
648,287
public INodeDirectory getSnapshottableAncestorDir(final INodesInPath iip) throws IOException { final String path = iip.getPath(); final INodeDirectory dir = INodeDirectory.valueOf(iip.getLastINode(), path); if (dir.isSnapshottable()) { return dir; } else { for (INodeDirectory snapRoot : this.snapshottables.values()) { if (dir.isAncestorDirectory(snapRoot)) { return snapRoot; } } throw new SnapshotException("Directory is neither snapshottable nor" + " under a snap root!"); } }
INodeDirectory function(final INodesInPath iip) throws IOException { final String path = iip.getPath(); final INodeDirectory dir = INodeDirectory.valueOf(iip.getLastINode(), path); if (dir.isSnapshottable()) { return dir; } else { for (INodeDirectory snapRoot : this.snapshottables.values()) { if (dir.isAncestorDirectory(snapRoot)) { return snapRoot; } } throw new SnapshotException(STR + STR); } }
/** * Get the snapshot root directory for the given directory. The given * directory must either be a snapshot root or a descendant of any * snapshot root directories. * @param iip INodesInPath for the directory to get snapshot root. * @return the snapshot root INodeDirectory */
Get the snapshot root directory for the given directory. The given directory must either be a snapshot root or a descendant of any snapshot root directories
getSnapshottableAncestorDir
{ "repo_name": "soumabrata-chakraborty/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/SnapshotManager.java", "license": "apache-2.0", "size": 19927 }
[ "java.io.IOException", "org.apache.hadoop.hdfs.protocol.SnapshotException", "org.apache.hadoop.hdfs.server.namenode.INodeDirectory", "org.apache.hadoop.hdfs.server.namenode.INodesInPath" ]
import java.io.IOException; import org.apache.hadoop.hdfs.protocol.SnapshotException; import org.apache.hadoop.hdfs.server.namenode.INodeDirectory; import org.apache.hadoop.hdfs.server.namenode.INodesInPath;
import java.io.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.namenode.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
1,607,901
public Factory<SSLContext> getSslContextFactory() { return sslCtxFactory; }
Factory<SSLContext> function() { return sslCtxFactory; }
/** * Returns SSL context factory that will be used for creating a secure socket layer. * * @return SSL connection factory. * @see SslContextFactory */
Returns SSL context factory that will be used for creating a secure socket layer
getSslContextFactory
{ "repo_name": "apacheignite/ignite", "path": "modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java", "license": "apache-2.0", "size": 83343 }
[ "javax.cache.configuration.Factory", "javax.net.ssl.SSLContext" ]
import javax.cache.configuration.Factory; import javax.net.ssl.SSLContext;
import javax.cache.configuration.*; import javax.net.ssl.*;
[ "javax.cache", "javax.net" ]
javax.cache; javax.net;
2,722,646
private void appendExtraAttributes(final Attributes attributes) { final Iterator iterator = extraAttributes.iterator(); while (iterator.hasNext()) { final ExtraAttribute attribute = (ExtraAttribute) iterator.next(); attributes.putValue(attribute.getName(), attribute.getValue()); } }
void function(final Attributes attributes) { final Iterator iterator = extraAttributes.iterator(); while (iterator.hasNext()) { final ExtraAttribute attribute = (ExtraAttribute) iterator.next(); attributes.putValue(attribute.getName(), attribute.getValue()); } }
/** * Add any extra attributes to the manifest. * * @param attributes the manifest section to write * attributes to */
Add any extra attributes to the manifest
appendExtraAttributes
{ "repo_name": "Mayo-WE01051879/mayosapp", "path": "Build/src/main/org/apache/tools/ant/taskdefs/optional/extension/JarLibManifestTask.java", "license": "mit", "size": 10320 }
[ "java.util.Iterator", "java.util.jar.Attributes" ]
import java.util.Iterator; import java.util.jar.Attributes;
import java.util.*; import java.util.jar.*;
[ "java.util" ]
java.util;
1,166,025
@DoesServiceRequest public void create() throws StorageException { this.create(null , null ); }
void function() throws StorageException { this.create(null , null ); }
/** * Creates the queue. * * @throws StorageException * If a storage service error occurred during the operation. */
Creates the queue
create
{ "repo_name": "horizon-institute/runspotrun-android-client", "path": "src/com/microsoft/azure/storage/queue/CloudQueue.java", "license": "agpl-3.0", "size": 84049 }
[ "com.microsoft.azure.storage.StorageException" ]
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.*;
[ "com.microsoft.azure" ]
com.microsoft.azure;
2,772,373
void setDataFormats(Map<String, DataFormatDefinition> dataFormats);
void setDataFormats(Map<String, DataFormatDefinition> dataFormats);
/** * Sets the data formats that can be referenced in the routes. * * @param dataFormats the data formats */
Sets the data formats that can be referenced in the routes
setDataFormats
{ "repo_name": "NickCis/camel", "path": "camel-core/src/main/java/org/apache/camel/CamelContext.java", "license": "apache-2.0", "size": 74001 }
[ "java.util.Map", "org.apache.camel.model.DataFormatDefinition" ]
import java.util.Map; import org.apache.camel.model.DataFormatDefinition;
import java.util.*; import org.apache.camel.model.*;
[ "java.util", "org.apache.camel" ]
java.util; org.apache.camel;
1,112,022
public static @Nullable PokeInfoCalculator getInstance() { return instance; } private PokeInfoCalculator(@NonNull GoIVSettings settings, @NonNull Resources res) { populatePokemon(settings, res); // create and cache the full pokemon display name list ArrayList<String> pokemonNamesArray = new ArrayList<>(); for (Pokemon poke : getPokedex()) { for (Pokemon pokemonForm : getForms(poke)) { pokemonNamesArray.add(pokemonForm.toString()); } } pokeNamesWithForm = pokemonNamesArray.toArray(new String[pokemonNamesArray.size()]); // create and cache the normalized pokemon type locale name for (int i = 0; i < res.getStringArray(R.array.typeName).length; i++) { normalizedTypeNames.put(Pokemon.Type.values()[i], StringUtils.normalize(res.getStringArray(R.array.typeName)[i])); } }
static @Nullable PokeInfoCalculator function() { return instance; } private PokeInfoCalculator(@NonNull GoIVSettings settings, @NonNull Resources res) { populatePokemon(settings, res); ArrayList<String> pokemonNamesArray = new ArrayList<>(); for (Pokemon poke : getPokedex()) { for (Pokemon pokemonForm : getForms(poke)) { pokemonNamesArray.add(pokemonForm.toString()); } } pokeNamesWithForm = pokemonNamesArray.toArray(new String[pokemonNamesArray.size()]); for (int i = 0; i < res.getStringArray(R.array.typeName).length; i++) { normalizedTypeNames.put(Pokemon.Type.values()[i], StringUtils.normalize(res.getStringArray(R.array.typeName)[i])); } }
/** * Get the instance of pokeInfoCalculator. Must have been initiated first! * * @return the already activated instance of PokeInfoCalculator. */
Get the instance of pokeInfoCalculator. Must have been initiated first
getInstance
{ "repo_name": "Remiscan/GoIV", "path": "app/src/main/java/com/kamron/pogoiv/scanlogic/PokeInfoCalculator.java", "license": "gpl-3.0", "size": 21360 }
[ "android.content.res.Resources", "android.support.annotation.NonNull", "android.support.annotation.Nullable", "com.kamron.pogoiv.GoIVSettings", "com.kamron.pogoiv.utils.StringUtils", "java.util.ArrayList" ]
import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.kamron.pogoiv.GoIVSettings; import com.kamron.pogoiv.utils.StringUtils; import java.util.ArrayList;
import android.content.res.*; import android.support.annotation.*; import com.kamron.pogoiv.*; import com.kamron.pogoiv.utils.*; import java.util.*;
[ "android.content", "android.support", "com.kamron.pogoiv", "java.util" ]
android.content; android.support; com.kamron.pogoiv; java.util;
608,597
private Block addStoredBlock(final BlockInfo block, final Block reportedBlock, DatanodeStorageInfo storageInfo, DatanodeDescriptor delNodeHint, boolean logEveryBlock) throws IOException { assert block != null && namesystem.hasWriteLock(); BlockInfo storedBlock; DatanodeDescriptor node = storageInfo.getDatanodeDescriptor(); if (!block.isComplete()) { //refresh our copy in case the block got completed in another thread storedBlock = getStoredBlock(block); } else { storedBlock = block; } if (storedBlock == null || storedBlock.isDeleted()) { // If this block does not belong to anyfile, then we are done. blockLog.debug("BLOCK* addStoredBlock: {} on {} size {} but it does not" + " belong to any file", block, node, block.getNumBytes()); // we could add this block to invalidate set of this datanode. // it will happen in next block report otherwise. return block; } // add block to the datanode AddBlockResult result = storageInfo.addBlock(storedBlock, reportedBlock); int curReplicaDelta; if (result == AddBlockResult.ADDED) { curReplicaDelta = (node.isDecommissioned()) ? 0 : 1; if (logEveryBlock) { blockLog.debug("BLOCK* addStoredBlock: {} is added to {} (size={})", node, storedBlock, storedBlock.getNumBytes()); } } else if (result == AddBlockResult.REPLACED) { curReplicaDelta = 0; blockLog.warn("BLOCK* addStoredBlock: block {} moved to storageType " + "{} on node {}", storedBlock, storageInfo.getStorageType(), node); } else { // if the same block is added again and the replica was corrupt // previously because of a wrong gen stamp, remove it from the // corrupt block list. corruptReplicas.removeFromCorruptReplicasMap(block, node, Reason.GENSTAMP_MISMATCH); curReplicaDelta = 0; blockLog.debug("BLOCK* addStoredBlock: Redundant addStoredBlock request" + " received for {} on node {} size {}", storedBlock, node, storedBlock.getNumBytes()); } // Now check for completion of blocks and safe block count NumberReplicas num = countNodes(storedBlock); int numLiveReplicas = num.liveReplicas(); int pendingNum = pendingReconstruction.getNumReplicas(storedBlock); int numCurrentReplica = numLiveReplicas + pendingNum; if(storedBlock.getBlockUCState() == BlockUCState.COMMITTED && hasMinStorage(storedBlock, numLiveReplicas)) { addExpectedReplicasToPending(storedBlock); completeBlock(storedBlock, null, false); } else if (storedBlock.isComplete() && result == AddBlockResult.ADDED) { // check whether safe replication is reached for the block // only complete blocks are counted towards that // Is no-op if not in safe mode. // In the case that the block just became complete above, completeBlock() // handles the safe block count maintenance. bmSafeMode.incrementSafeBlockCount(numCurrentReplica, storedBlock); } // if block is still under construction, then done for now if (!storedBlock.isCompleteOrCommitted()) { return storedBlock; } // do not try to handle extra/low redundancy blocks during first safe mode if (!isPopulatingReplQueues()) { return storedBlock; } // handle low redundancy/extra redundancy short fileRedundancy = getExpectedRedundancyNum(storedBlock); if (!isNeededReconstruction(storedBlock, num, pendingNum)) { neededReconstruction.remove(storedBlock, numCurrentReplica, num.readOnlyReplicas(), num.outOfServiceReplicas(), fileRedundancy); } else { updateNeededReconstructions(storedBlock, curReplicaDelta, 0); } if (shouldProcessExtraRedundancy(num, fileRedundancy)) { processExtraRedundancyBlock(storedBlock, fileRedundancy, node, delNodeHint); } // If the file redundancy has reached desired value // we can remove any corrupt replicas the block may have int corruptReplicasCount = corruptReplicas.numCorruptReplicas(storedBlock); int numCorruptNodes = num.corruptReplicas(); if (numCorruptNodes != corruptReplicasCount) { LOG.warn("Inconsistent number of corrupt replicas for {}" + ". blockMap has {} but corrupt replicas map has {}", storedBlock, numCorruptNodes, corruptReplicasCount); } if ((corruptReplicasCount > 0) && (numLiveReplicas >= fileRedundancy)) { invalidateCorruptReplicas(storedBlock, reportedBlock, num); } return storedBlock; }
Block function(final BlockInfo block, final Block reportedBlock, DatanodeStorageInfo storageInfo, DatanodeDescriptor delNodeHint, boolean logEveryBlock) throws IOException { assert block != null && namesystem.hasWriteLock(); BlockInfo storedBlock; DatanodeDescriptor node = storageInfo.getDatanodeDescriptor(); if (!block.isComplete()) { storedBlock = getStoredBlock(block); } else { storedBlock = block; } if (storedBlock == null storedBlock.isDeleted()) { blockLog.debug(STR + STR, block, node, block.getNumBytes()); return block; } AddBlockResult result = storageInfo.addBlock(storedBlock, reportedBlock); int curReplicaDelta; if (result == AddBlockResult.ADDED) { curReplicaDelta = (node.isDecommissioned()) ? 0 : 1; if (logEveryBlock) { blockLog.debug(STR, node, storedBlock, storedBlock.getNumBytes()); } } else if (result == AddBlockResult.REPLACED) { curReplicaDelta = 0; blockLog.warn(STR + STR, storedBlock, storageInfo.getStorageType(), node); } else { corruptReplicas.removeFromCorruptReplicasMap(block, node, Reason.GENSTAMP_MISMATCH); curReplicaDelta = 0; blockLog.debug(STR + STR, storedBlock, node, storedBlock.getNumBytes()); } NumberReplicas num = countNodes(storedBlock); int numLiveReplicas = num.liveReplicas(); int pendingNum = pendingReconstruction.getNumReplicas(storedBlock); int numCurrentReplica = numLiveReplicas + pendingNum; if(storedBlock.getBlockUCState() == BlockUCState.COMMITTED && hasMinStorage(storedBlock, numLiveReplicas)) { addExpectedReplicasToPending(storedBlock); completeBlock(storedBlock, null, false); } else if (storedBlock.isComplete() && result == AddBlockResult.ADDED) { bmSafeMode.incrementSafeBlockCount(numCurrentReplica, storedBlock); } if (!storedBlock.isCompleteOrCommitted()) { return storedBlock; } if (!isPopulatingReplQueues()) { return storedBlock; } short fileRedundancy = getExpectedRedundancyNum(storedBlock); if (!isNeededReconstruction(storedBlock, num, pendingNum)) { neededReconstruction.remove(storedBlock, numCurrentReplica, num.readOnlyReplicas(), num.outOfServiceReplicas(), fileRedundancy); } else { updateNeededReconstructions(storedBlock, curReplicaDelta, 0); } if (shouldProcessExtraRedundancy(num, fileRedundancy)) { processExtraRedundancyBlock(storedBlock, fileRedundancy, node, delNodeHint); } int corruptReplicasCount = corruptReplicas.numCorruptReplicas(storedBlock); int numCorruptNodes = num.corruptReplicas(); if (numCorruptNodes != corruptReplicasCount) { LOG.warn(STR + STR, storedBlock, numCorruptNodes, corruptReplicasCount); } if ((corruptReplicasCount > 0) && (numLiveReplicas >= fileRedundancy)) { invalidateCorruptReplicas(storedBlock, reportedBlock, num); } return storedBlock; }
/** * Modify (block-->datanode) map. Remove block from set of * needed reconstruction if this takes care of the problem. * @return the block that is stored in blocksMap. */
Modify (block-->datanode) map. Remove block from set of needed reconstruction if this takes care of the problem
addStoredBlock
{ "repo_name": "dennishuo/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java", "license": "apache-2.0", "size": 191685 }
[ "java.io.IOException", "org.apache.hadoop.hdfs.protocol.Block", "org.apache.hadoop.hdfs.server.blockmanagement.CorruptReplicasMap", "org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo", "org.apache.hadoop.hdfs.server.common.HdfsServerConstants" ]
import java.io.IOException; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.server.blockmanagement.CorruptReplicasMap; import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import java.io.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.blockmanagement.*; import org.apache.hadoop.hdfs.server.common.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
847,835
public static Option<?> fromString(String name, ClassLoader classLoader) throws IllegalArgumentException { final int lastDot = name.lastIndexOf('.'); if (lastDot == -1) { throw msg.invalidOptionName(name); } final String fieldName = name.substring(lastDot + 1); final String className = name.substring(0, lastDot); final Class<?> clazz; try { clazz = Class.forName(className, true, classLoader); } catch (ClassNotFoundException e) { throw msg.optionClassNotFound(className, classLoader); } final Field field; try { field = clazz.getField(fieldName); } catch (NoSuchFieldException e) { throw msg.noField(fieldName, clazz); } final int modifiers = field.getModifiers(); if (! Modifier.isPublic(modifiers)) { throw msg.fieldNotAccessible(fieldName, clazz); } if (! Modifier.isStatic(modifiers)) { throw msg.fieldNotStatic(fieldName, clazz); } final Option<?> option; try { option = (Option<?>) field.get(null); } catch (IllegalAccessException e) { throw msg.fieldNotAccessible(fieldName, clazz); } if (option == null) { throw msg.invalidNullOption(name); } return option; }
static Option<?> function(String name, ClassLoader classLoader) throws IllegalArgumentException { final int lastDot = name.lastIndexOf('.'); if (lastDot == -1) { throw msg.invalidOptionName(name); } final String fieldName = name.substring(lastDot + 1); final String className = name.substring(0, lastDot); final Class<?> clazz; try { clazz = Class.forName(className, true, classLoader); } catch (ClassNotFoundException e) { throw msg.optionClassNotFound(className, classLoader); } final Field field; try { field = clazz.getField(fieldName); } catch (NoSuchFieldException e) { throw msg.noField(fieldName, clazz); } final int modifiers = field.getModifiers(); if (! Modifier.isPublic(modifiers)) { throw msg.fieldNotAccessible(fieldName, clazz); } if (! Modifier.isStatic(modifiers)) { throw msg.fieldNotStatic(fieldName, clazz); } final Option<?> option; try { option = (Option<?>) field.get(null); } catch (IllegalAccessException e) { throw msg.fieldNotAccessible(fieldName, clazz); } if (option == null) { throw msg.invalidNullOption(name); } return option; }
/** * Get an option from a string name, using the given classloader. If the classloader is {@code null}, the bootstrap * classloader will be used. * * @param name the option string * @param classLoader the class loader * @return the option * @throws IllegalArgumentException if the given option name is not valid */
Get an option from a string name, using the given classloader. If the classloader is null, the bootstrap classloader will be used
fromString
{ "repo_name": "xnio/xnio", "path": "api/src/main/java/org/xnio/Option.java", "license": "apache-2.0", "size": 16599 }
[ "java.lang.reflect.Field", "java.lang.reflect.Modifier" ]
import java.lang.reflect.Field; import java.lang.reflect.Modifier;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
1,201,332
public static FakeExtractorOutput extractAllSamplesFromFile( Extractor extractor, Context context, String fileName) throws IOException { byte[] data = TestUtil.getByteArray(context, fileName); FakeExtractorOutput expectedOutput = new FakeExtractorOutput(); extractor.init(expectedOutput); FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build(); PositionHolder positionHolder = new PositionHolder(); int readResult = Extractor.RESULT_CONTINUE; while (readResult != Extractor.RESULT_END_OF_INPUT) { while (readResult == Extractor.RESULT_CONTINUE) { readResult = extractor.read(input, positionHolder); } if (readResult == Extractor.RESULT_SEEK) { input.setPosition((int) positionHolder.position); readResult = Extractor.RESULT_CONTINUE; } } return expectedOutput; }
static FakeExtractorOutput function( Extractor extractor, Context context, String fileName) throws IOException { byte[] data = TestUtil.getByteArray(context, fileName); FakeExtractorOutput expectedOutput = new FakeExtractorOutput(); extractor.init(expectedOutput); FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build(); PositionHolder positionHolder = new PositionHolder(); int readResult = Extractor.RESULT_CONTINUE; while (readResult != Extractor.RESULT_END_OF_INPUT) { while (readResult == Extractor.RESULT_CONTINUE) { readResult = extractor.read(input, positionHolder); } if (readResult == Extractor.RESULT_SEEK) { input.setPosition((int) positionHolder.position); readResult = Extractor.RESULT_CONTINUE; } } return expectedOutput; }
/** * Extracts all samples from the given file into a {@link FakeTrackOutput}. * * @param extractor The {@link Extractor} to extractor from input. * @param context A {@link Context}. * @param fileName The name of the input file. * @return The {@link FakeTrackOutput} containing the extracted samples. * @throws IOException If an error occurred reading from the input, or if the extractor finishes * reading from input without extracting any {@link SeekMap}. */
Extracts all samples from the given file into a <code>FakeTrackOutput</code>
extractAllSamplesFromFile
{ "repo_name": "androidx/media", "path": "libraries/test_utils/src/main/java/androidx/media3/test/utils/TestUtil.java", "license": "apache-2.0", "size": 18529 }
[ "android.content.Context", "androidx.media3.extractor.Extractor", "androidx.media3.extractor.PositionHolder", "java.io.IOException" ]
import android.content.Context; import androidx.media3.extractor.Extractor; import androidx.media3.extractor.PositionHolder; import java.io.IOException;
import android.content.*; import androidx.media3.extractor.*; import java.io.*;
[ "android.content", "androidx.media3", "java.io" ]
android.content; androidx.media3; java.io;
40,376
public int parseParameters(String[] args) { // check for action if (args.length < 1) { CliFrontendParser.printHelp(); System.out.println("Please specify an action."); return 1; } // get action String action = args[0]; // remove action from parameters final String[] params = Arrays.copyOfRange(args, 1, args.length); // do action switch (action) { case ACTION_RUN: return run(params); case ACTION_LIST: return list(params); case ACTION_INFO: return info(params); case ACTION_CANCEL: return cancel(params); case ACTION_STOP: return stop(params); case ACTION_SAVEPOINT: return savepoint(params); case "-h": case "--help": CliFrontendParser.printHelp(); return 0; case "-v": case "--version": String version = EnvironmentInformation.getVersion(); String commitID = EnvironmentInformation.getRevisionInformation().commitId; System.out.print("Version: " + version); System.out.println(!commitID.equals(EnvironmentInformation.UNKNOWN) ? ", Commit ID: " + commitID : ""); return 0; default: System.out.printf("\"%s\" is not a valid action.\n", action); System.out.println(); System.out.println("Valid actions are \"run\", \"list\", \"info\", \"savepoint\", \"stop\", or \"cancel\"."); System.out.println(); System.out.println("Specify the version option (-v or --version) to print Flink version."); System.out.println(); System.out.println("Specify the help option (-h or --help) to get help on the command."); return 1; } }
int function(String[] args) { if (args.length < 1) { CliFrontendParser.printHelp(); System.out.println(STR); return 1; } String action = args[0]; final String[] params = Arrays.copyOfRange(args, 1, args.length); switch (action) { case ACTION_RUN: return run(params); case ACTION_LIST: return list(params); case ACTION_INFO: return info(params); case ACTION_CANCEL: return cancel(params); case ACTION_STOP: return stop(params); case ACTION_SAVEPOINT: return savepoint(params); case "-h": case STR: CliFrontendParser.printHelp(); return 0; case "-v": case STR: String version = EnvironmentInformation.getVersion(); String commitID = EnvironmentInformation.getRevisionInformation().commitId; System.out.print(STR + version); System.out.println(!commitID.equals(EnvironmentInformation.UNKNOWN) ? STR + commitID : STR\"%s\" is not a valid action.\nSTRValid actions are \"run\", \"list\", \"info\", \STR, \"stop\", or \STR.STRSpecify the version option (-v or --version) to print Flink version.STRSpecify the help option (-h or --help) to get help on the command."); return 1; } }
/** * Parses the command line arguments and starts the requested action. * * @param args command line arguments of the client. * @return The return code of the program */
Parses the command line arguments and starts the requested action
parseParameters
{ "repo_name": "zohar-mizrahi/flink", "path": "flink-clients/src/main/java/org/apache/flink/client/CliFrontend.java", "license": "apache-2.0", "size": 40951 }
[ "java.util.Arrays", "org.apache.flink.client.cli.CliFrontendParser", "org.apache.flink.runtime.util.EnvironmentInformation" ]
import java.util.Arrays; import org.apache.flink.client.cli.CliFrontendParser; import org.apache.flink.runtime.util.EnvironmentInformation;
import java.util.*; import org.apache.flink.client.cli.*; import org.apache.flink.runtime.util.*;
[ "java.util", "org.apache.flink" ]
java.util; org.apache.flink;
1,944,893
public String exportAPIProductArtifacts(APIProduct apiProductToReturn, boolean isStatusPreserved, ExportFormat exportFormat) throws APIImportExportException { // Create temp location for storing API Product data File exportFolder = CommonUtil.createTempDirectory(apiProductToReturn.getId()); String exportAPIProductBasePath = exportFolder.toString(); // Retrieve the API Product and related artifacts and populate the api folder in the temp location APIProductExportUtil.retrieveApiProductToExport(exportAPIProductBasePath, apiProductToReturn, apiProvider, loggedInUsername, isStatusPreserved, exportFormat); return exportAPIProductBasePath; }
String function(APIProduct apiProductToReturn, boolean isStatusPreserved, ExportFormat exportFormat) throws APIImportExportException { File exportFolder = CommonUtil.createTempDirectory(apiProductToReturn.getId()); String exportAPIProductBasePath = exportFolder.toString(); APIProductExportUtil.retrieveApiProductToExport(exportAPIProductBasePath, apiProductToReturn, apiProvider, loggedInUsername, isStatusPreserved, exportFormat); return exportAPIProductBasePath; }
/** * This method is used to export the given API Product artifacts to the temp location. * * @param apiProductToReturn Requested API Product to export * @param isStatusPreserved Is API Product status preserved or not * @param exportFormat Export file format of the API Product * @return tmp location for the exported API Product artifacts * @throws APIImportExportException If an error occurs while exporting the API Product */
This method is used to export the given API Product artifacts to the temp location
exportAPIProductArtifacts
{ "repo_name": "nuwand/carbon-apimgt", "path": "components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/importexport/APIImportExportManager.java", "license": "apache-2.0", "size": 9732 }
[ "java.io.File", "org.wso2.carbon.apimgt.api.model.APIProduct", "org.wso2.carbon.apimgt.impl.importexport.utils.APIProductExportUtil", "org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil" ]
import java.io.File; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.impl.importexport.utils.APIProductExportUtil; import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil;
import java.io.*; import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.importexport.utils.*;
[ "java.io", "org.wso2.carbon" ]
java.io; org.wso2.carbon;
1,975,157
// 5.3 pg 28 public BigInteger[] generateSignature( byte[] message) { BigInteger n = key.getParameters().getN(); BigInteger e = calculateE(n, message); BigInteger r = null; BigInteger s = null; // 5.3.2 do // generate s { BigInteger k = null; int nBitLength = n.bitLength(); do // generate r { do { k = new BigInteger(nBitLength, random); } while (k.equals(ZERO) || k.compareTo(n) >= 0); ECPoint p = key.getParameters().getG().multiply(k); // 5.3.3 BigInteger x = p.getX().toBigInteger(); r = x.mod(n); } while (r.equals(ZERO)); BigInteger d = ((ECPrivateKeyParameters)key).getD(); s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); } while (s.equals(ZERO)); BigInteger[] res = new BigInteger[2]; res[0] = r; res[1] = s; return res; }
BigInteger[] function( byte[] message) { BigInteger n = key.getParameters().getN(); BigInteger e = calculateE(n, message); BigInteger r = null; BigInteger s = null; do { BigInteger k = null; int nBitLength = n.bitLength(); do { do { k = new BigInteger(nBitLength, random); } while (k.equals(ZERO) k.compareTo(n) >= 0); ECPoint p = key.getParameters().getG().multiply(k); BigInteger x = p.getX().toBigInteger(); r = x.mod(n); } while (r.equals(ZERO)); BigInteger d = ((ECPrivateKeyParameters)key).getD(); s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); } while (s.equals(ZERO)); BigInteger[] res = new BigInteger[2]; res[0] = r; res[1] = s; return res; }
/** * generate a signature for the given message using the key we were * initialised with. For conventional DSA the message should be a SHA-1 * hash of the message of interest. * * @param message the message that will be verified later. */
generate a signature for the given message using the key we were initialised with. For conventional DSA the message should be a SHA-1 hash of the message of interest
generateSignature
{ "repo_name": "bullda/DroidText", "path": "src/bouncycastle/repack/org/bouncycastle/crypto/signers/ECDSASigner.java", "license": "lgpl-3.0", "size": 4539 }
[ "java.math.BigInteger" ]
import java.math.BigInteger;
import java.math.*;
[ "java.math" ]
java.math;
379,867
public void addRecognizedParamsAndSetDefaults(XMLComponent component) { // register component's recognized features final String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties final String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values setFeatureDefaults(component, recognizedFeatures); setPropertyDefaults(component, recognizedProperties); }
void function(XMLComponent component) { final String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); final String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); setFeatureDefaults(component, recognizedFeatures); setPropertyDefaults(component, recognizedProperties); }
/** * Adds all of the component's recognized features and properties * to the list of default recognized features and properties, and * sets default values on the configuration for features and * properties which were previously absent from the configuration. * * @param component The component whose recognized features * and properties will be added to the configuration */
Adds all of the component's recognized features and properties to the list of default recognized features and properties, and sets default values on the configuration for features and properties which were previously absent from the configuration
addRecognizedParamsAndSetDefaults
{ "repo_name": "BIORIMP/biorimp", "path": "BIO-RIMP/test_data/code/xerces/src/org/apache/xerces/jaxp/validation/XMLSchemaValidatorComponentManager.java", "license": "gpl-2.0", "size": 17371 }
[ "org.apache.xerces.xni.parser.XMLComponent" ]
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.*;
[ "org.apache.xerces" ]
org.apache.xerces;
2,750,439
public SelectablePublishers getSelectablePublishers() { return _selectablePublishers; }
SelectablePublishers function() { return _selectablePublishers; }
/** * Gets list of selectable publishers. * @return the list of selectable publishers */
Gets list of selectable publishers
getSelectablePublishers
{ "repo_name": "usgin/usgin-geoportal", "path": "src/com/esri/gpt/control/publication/ManageMetadataController.java", "license": "apache-2.0", "size": 23664 }
[ "com.esri.gpt.control.view.SelectablePublishers" ]
import com.esri.gpt.control.view.SelectablePublishers;
import com.esri.gpt.control.view.*;
[ "com.esri.gpt" ]
com.esri.gpt;
2,473,342
private void setArtifactRoots(PackageRoots packageRoots) { getArtifactFactory().setPackageRoots(packageRoots.getPackageRootLookup()); }
void function(PackageRoots packageRoots) { getArtifactFactory().setPackageRoots(packageRoots.getPackageRootLookup()); }
/** * Sets the possible artifact roots in the artifact factory. This allows the factory to resolve * paths with unknown roots to artifacts. */
Sets the possible artifact roots in the artifact factory. This allows the factory to resolve paths with unknown roots to artifacts
setArtifactRoots
{ "repo_name": "cushon/bazel", "path": "src/main/java/com/google/devtools/build/lib/analysis/BuildView.java", "license": "apache-2.0", "size": 37283 }
[ "com.google.devtools.build.lib.actions.PackageRoots" ]
import com.google.devtools.build.lib.actions.PackageRoots;
import com.google.devtools.build.lib.actions.*;
[ "com.google.devtools" ]
com.google.devtools;
734,090
public Object readObject( final ObjectInputStream in ) throws IOException, ClassNotFoundException { final int winding = in.readInt(); final GeneralPath gp = new GeneralPath( winding ); // type will be -1 at the end of the GPath .. int type = in.readInt(); while ( type >= 0 ) { switch( type ) { case PathIterator.SEG_MOVETO: { final float x = in.readFloat(); final float y = in.readFloat(); gp.moveTo( x, y ); break; } case PathIterator.SEG_LINETO: { final float x = in.readFloat(); final float y = in.readFloat(); gp.lineTo( x, y ); break; } case PathIterator.SEG_QUADTO: { final float x1 = in.readFloat(); final float y1 = in.readFloat(); final float x2 = in.readFloat(); final float y2 = in.readFloat(); gp.quadTo( x1, y1, x2, y2 ); break; } case PathIterator.SEG_CUBICTO: { final float x1 = in.readFloat(); final float y1 = in.readFloat(); final float x2 = in.readFloat(); final float y2 = in.readFloat(); final float x3 = in.readFloat(); final float y3 = in.readFloat(); gp.curveTo( x1, y1, x2, y2, x3, y3 ); break; } case PathIterator.SEG_CLOSE: { break; } default: throw new IOException( "Unexpected type encountered: " + type ); } type = in.readInt(); } return gp; }
Object function( final ObjectInputStream in ) throws IOException, ClassNotFoundException { final int winding = in.readInt(); final GeneralPath gp = new GeneralPath( winding ); int type = in.readInt(); while ( type >= 0 ) { switch( type ) { case PathIterator.SEG_MOVETO: { final float x = in.readFloat(); final float y = in.readFloat(); gp.moveTo( x, y ); break; } case PathIterator.SEG_LINETO: { final float x = in.readFloat(); final float y = in.readFloat(); gp.lineTo( x, y ); break; } case PathIterator.SEG_QUADTO: { final float x1 = in.readFloat(); final float y1 = in.readFloat(); final float x2 = in.readFloat(); final float y2 = in.readFloat(); gp.quadTo( x1, y1, x2, y2 ); break; } case PathIterator.SEG_CUBICTO: { final float x1 = in.readFloat(); final float y1 = in.readFloat(); final float x2 = in.readFloat(); final float y2 = in.readFloat(); final float x3 = in.readFloat(); final float y3 = in.readFloat(); gp.curveTo( x1, y1, x2, y2, x3, y3 ); break; } case PathIterator.SEG_CLOSE: { break; } default: throw new IOException( STR + type ); } type = in.readInt(); } return gp; }
/** * Reads the object from the object input stream. * * @param in the object input stream from where to read the serialized data. * @return the generated object. * @throws java.io.IOException if reading the stream failed. * @throws ClassNotFoundException if serialized object class cannot be found. */
Reads the object from the object input stream
readObject
{ "repo_name": "EgorZhuk/pentaho-reporting", "path": "libraries/libserializer/src/main/java/org/pentaho/reporting/libraries/serializer/methods/GeneralPathSerializer.java", "license": "lgpl-2.1", "size": 5322 }
[ "java.awt.geom.GeneralPath", "java.awt.geom.PathIterator", "java.io.IOException", "java.io.ObjectInputStream" ]
import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.io.IOException; import java.io.ObjectInputStream;
import java.awt.geom.*; import java.io.*;
[ "java.awt", "java.io" ]
java.awt; java.io;
1,820,284
boolean isSystemGroup(long id, String key) { return MetadataViewerAgent.getRegistry().getAdminService().isSecuritySystemGroup(id, key); } /** * Returns the {@link ImportType}
boolean isSystemGroup(long id, String key) { return MetadataViewerAgent.getRegistry().getAdminService().isSecuritySystemGroup(id, key); } /** * Returns the {@link ImportType}
/** * Returns <code>true</code> if the group is a system group e.g. System * <code>false</code> otherwise. * * @param id The identifier of the group. * @param key The type of group to check. * @return See above. */
Returns <code>true</code> if the group is a system group e.g. System <code>false</code> otherwise
isSystemGroup
{ "repo_name": "dpwrussell/openmicroscopy", "path": "components/insight/SRC/org/openmicroscopy/shoola/agents/metadata/editor/EditorModel.java", "license": "gpl-2.0", "size": 130987 }
[ "org.openmicroscopy.shoola.agents.metadata.MetadataViewerAgent" ]
import org.openmicroscopy.shoola.agents.metadata.MetadataViewerAgent;
import org.openmicroscopy.shoola.agents.metadata.*;
[ "org.openmicroscopy.shoola" ]
org.openmicroscopy.shoola;
2,735,816
protected Mono<AmqpLink> createProducer(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot create send link '%s' from a closed session. entityPath[%s]", linkName, entityPath)))); } final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName); if (existing != null) { logger.verbose("linkName[{}]: Returning existing send link.", linkName); return Mono.just(existing.getLink()); } final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath); return RetryUtil.withRetry( getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE), timeout, retry).then(tokenManager.authorize()).then(Mono.create(sink -> { try { // We have to invoke this in the same thread or else proton-j will not properly link up the created // sender because the link names are not unique. Link name == entity path. provider.getReactorDispatcher().invoke(() -> { final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName, (linkNameKey, existingLink) -> { if (existingLink != null) { logger.info("linkName[{}]: Another send link exists. Disposing of new one.", linkName); tokenManager.close(); return existingLink; } logger.info("Creating a new sender link with linkName {}", linkName); return getSubscription(linkName, entityPath, linkProperties, timeout, retry, tokenManager); }); sink.success(computed.getLink()); }); } catch (IOException e) { sink.error(e); } })); }
Mono<AmqpLink> function(String linkName, String entityPath, Duration timeout, AmqpRetryPolicy retry, Map<Symbol, Object> linkProperties) { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( STR, linkName, entityPath)))); } final LinkSubscription<AmqpSendLink> existing = openSendLinks.get(linkName); if (existing != null) { logger.verbose(STR, linkName); return Mono.just(existing.getLink()); } final TokenManager tokenManager = tokenManagerProvider.getTokenManager(cbsNodeSupplier, entityPath); return RetryUtil.withRetry( getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE), timeout, retry).then(tokenManager.authorize()).then(Mono.create(sink -> { try { provider.getReactorDispatcher().invoke(() -> { final LinkSubscription<AmqpSendLink> computed = openSendLinks.compute(linkName, (linkNameKey, existingLink) -> { if (existingLink != null) { logger.info(STR, linkName); tokenManager.close(); return existingLink; } logger.info(STR, linkName); return getSubscription(linkName, entityPath, linkProperties, timeout, retry, tokenManager); }); sink.success(computed.getLink()); }); } catch (IOException e) { sink.error(e); } })); }
/** * Creates an {@link AmqpLink} that has AMQP specific capabilities set. * * @param linkName Name of the receive link. * @param entityPath Address in the message broker for the link. * @param linkProperties The properties needed to be set on the link. * @param timeout Operation timeout when creating the link. * @param retry Retry policy to apply when link creation times out. * * @return A new instance of an {@link AmqpLink} with the correct properties set. */
Creates an <code>AmqpLink</code> that has AMQP specific capabilities set
createProducer
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSession.java", "license": "mit", "size": 25813 }
[ "com.azure.core.amqp.AmqpEndpointState", "com.azure.core.amqp.AmqpLink", "com.azure.core.amqp.AmqpRetryPolicy", "java.io.IOException", "java.time.Duration", "java.util.Map", "org.apache.qpid.proton.amqp.Symbol" ]
import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpLink; import com.azure.core.amqp.AmqpRetryPolicy; import java.io.IOException; import java.time.Duration; import java.util.Map; import org.apache.qpid.proton.amqp.Symbol;
import com.azure.core.amqp.*; import java.io.*; import java.time.*; import java.util.*; import org.apache.qpid.proton.amqp.*;
[ "com.azure.core", "java.io", "java.time", "java.util", "org.apache.qpid" ]
com.azure.core; java.io; java.time; java.util; org.apache.qpid;
2,902,422
public void testUnsupportedSetObjectWithScale() throws SQLException { PreparedStatement ps = prepare(); try { ps.setObject(1, null, typeInfo.type, 0); fail("No exception thrown."); } catch (SQLFeatureNotSupportedException e) { // expected exception } ps.close(); }
void function() throws SQLException { PreparedStatement ps = prepare(); try { ps.setObject(1, null, typeInfo.type, 0); fail(STR); } catch (SQLFeatureNotSupportedException e) { } ps.close(); }
/** * Test that <code>setObject()</code> with the specified * <code>sqlTargetType</code> throws * <code>SQLFeatureNotSupportedException</code>. * * @exception SQLException if a database error occurs */
Test that <code>setObject()</code> with the specified <code>sqlTargetType</code> throws <code>SQLFeatureNotSupportedException</code>
testUnsupportedSetObjectWithScale
{ "repo_name": "lpxz/grail-derby104", "path": "java/testing/org/apache/derbyTesting/functionTests/tests/jdbc4/SetObjectUnsupportedTest.java", "license": "apache-2.0", "size": 7792 }
[ "java.sql.PreparedStatement", "java.sql.SQLException", "java.sql.SQLFeatureNotSupportedException" ]
import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException;
import java.sql.*;
[ "java.sql" ]
java.sql;
646,255
private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; String watermarkText; StringTokenizer st; Vector<String> tokens = new Vector<String>(); try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get the PDF pages and position String pages = (String)options.get(PARAM_WATERMARK_PAGES); String position = (String)options.get(PARAM_POSITION); String depth = (String)options.get(PARAM_WATERMARK_DEPTH); // create the base font for the text stamp BaseFont bf = BaseFont.createFont((String)options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250, BaseFont.EMBEDDED); // get watermark text and process template with model String templateText = (String)options.get(PARAM_WATERMARK_TEXT); Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef); StringWriter watermarkWriter = new StringWriter(); freemarkerProcessor.processString(templateText, model, watermarkWriter); watermarkText = watermarkWriter.getBuffer().toString(); // tokenize watermark text to support multiple lines and copy tokens // to vector for re-use st = new StringTokenizer(watermarkText, "\r\n", false); while (st.hasMoreTokens()) { tokens.add(st.nextToken()); } // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, use getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // set the font and size float size = Float.parseFloat((String)options.get(PARAM_WATERMARK_SIZE)); pcb.setFontAndSize(bf, size); // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { writeAlignedText(pcb, r, tokens, size, position); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef)ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
void function(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; String watermarkText; StringTokenizer st; Vector<String> tokens = new Vector<String>(); try { File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; String pages = (String)options.get(PARAM_WATERMARK_PAGES); String position = (String)options.get(PARAM_POSITION); String depth = (String)options.get(PARAM_WATERMARK_DEPTH); BaseFont bf = BaseFont.createFont((String)options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250, BaseFont.EMBEDDED); String templateText = (String)options.get(PARAM_WATERMARK_TEXT); Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef); StringWriter watermarkWriter = new StringWriter(); freemarkerProcessor.processString(templateText, model, watermarkWriter); watermarkText = watermarkWriter.getBuffer().toString(); st = new StringTokenizer(watermarkText, "\r\n", false); while (st.hasMoreTokens()) { tokens.add(st.nextToken()); } int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } float size = Float.parseFloat((String)options.get(PARAM_WATERMARK_SIZE)); pcb.setFontAndSize(bf, size); if (checkPage(pages, i, numpages)) { writeAlignedText(pcb, r, tokens, size, position); } } stamp.close(); NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef)ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
/** * Applies a text watermark (current date, user name, etc, depending on * options) * * @param reader * @param writer * @param options */
Applies a text watermark (current date, user name, etc, depending on options)
textAction
{ "repo_name": "teqnology/alfresco-pdf-toolkit", "path": "alfresco-pdf-toolkit-repo/src/main/java/org/alfresco/extension/pdftoolkit/repo/action/executer/PDFWatermarkActionExecuter.java", "license": "apache-2.0", "size": 24411 }
[ "com.itextpdf.text.DocumentException", "com.itextpdf.text.Rectangle", "com.itextpdf.text.pdf.BaseFont", "com.itextpdf.text.pdf.PdfContentByte", "com.itextpdf.text.pdf.PdfReader", "com.itextpdf.text.pdf.PdfStamper", "java.io.File", "java.io.FileOutputStream", "java.io.IOException", "java.io.StringWriter", "java.util.Map", "java.util.StringTokenizer", "java.util.Vector", "org.alfresco.error.AlfrescoRuntimeException", "org.alfresco.model.ContentModel", "org.alfresco.service.cmr.action.Action", "org.alfresco.service.cmr.repository.ContentReader", "org.alfresco.service.cmr.repository.ContentWriter", "org.alfresco.service.cmr.repository.NodeRef", "org.alfresco.util.TempFileProvider" ]
import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.model.ContentModel; import org.alfresco.service.cmr.action.Action; import org.alfresco.service.cmr.repository.ContentReader; import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.util.TempFileProvider;
import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import java.io.*; import java.util.*; import org.alfresco.error.*; import org.alfresco.model.*; import org.alfresco.service.cmr.action.*; import org.alfresco.service.cmr.repository.*; import org.alfresco.util.*;
[ "com.itextpdf.text", "java.io", "java.util", "org.alfresco.error", "org.alfresco.model", "org.alfresco.service", "org.alfresco.util" ]
com.itextpdf.text; java.io; java.util; org.alfresco.error; org.alfresco.model; org.alfresco.service; org.alfresco.util;
1,118,631
@SuppressWarnings("unchecked") public List<JuristischePerson> getPersonByName(String name) { EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT p FROM JuristischePerson p WHERE p.name = ?1"); q.setParameter(1, name); List<JuristischePerson> result = (List<JuristischePerson>) q.getResultList(); return result; }
@SuppressWarnings(STR) List<JuristischePerson> function(String name) { EntityManager em = getEntityManager(); Query q = em.createQuery(STR); q.setParameter(1, name); List<JuristischePerson> result = (List<JuristischePerson>) q.getResultList(); return result; }
/** * Liefert alle Personen zu einem Nachnamen. * * @param name Name * @return siehe Beschreibung * * @throws NoResultException */
Liefert alle Personen zu einem Nachnamen
getPersonByName
{ "repo_name": "steffen-foerster/mgh", "path": "src/ch/giesserei/service/JuristischePersonService.java", "license": "mit", "size": 5587 }
[ "ch.giesserei.model.JuristischePerson", "java.util.List", "javax.persistence.EntityManager", "javax.persistence.Query" ]
import ch.giesserei.model.JuristischePerson; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query;
import ch.giesserei.model.*; import java.util.*; import javax.persistence.*;
[ "ch.giesserei.model", "java.util", "javax.persistence" ]
ch.giesserei.model; java.util; javax.persistence;
1,764,229
public static SamzaSqlRelRecord createSamzaSqlCompositeKey(SamzaSqlRelMessage message, List<Integer> keyValueIdx, List<String> keyPartNames) { Validate.isTrue(keyValueIdx.size() == keyPartNames.size(), "Key part name and value list sizes are different"); ArrayList<Object> keyPartValues = new ArrayList<>(); for (int idx : keyValueIdx) { keyPartValues.add(message.getSamzaSqlRelRecord().getFieldValues().get(idx)); } return new SamzaSqlRelRecord(keyPartNames, keyPartValues); }
static SamzaSqlRelRecord function(SamzaSqlRelMessage message, List<Integer> keyValueIdx, List<String> keyPartNames) { Validate.isTrue(keyValueIdx.size() == keyPartNames.size(), STR); ArrayList<Object> keyPartValues = new ArrayList<>(); for (int idx : keyValueIdx) { keyPartValues.add(message.getSamzaSqlRelRecord().getFieldValues().get(idx)); } return new SamzaSqlRelRecord(keyPartNames, keyPartValues); }
/** * Create composite key from the rel message. * @param message Represents the samza sql rel message to extract the key values from. * @param keyValueIdx list of key values in the form of field indices within the rel message. * @param keyPartNames Represents the key field names. * @return the composite key of the rel message */
Create composite key from the rel message
createSamzaSqlCompositeKey
{ "repo_name": "Swrrt/Samza", "path": "samza-sql/src/main/java/org/apache/samza/sql/data/SamzaSqlRelMessage.java", "license": "apache-2.0", "size": 8293 }
[ "java.util.ArrayList", "java.util.List", "org.apache.commons.lang.Validate", "org.apache.samza.sql.SamzaSqlRelRecord" ]
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.Validate; import org.apache.samza.sql.SamzaSqlRelRecord;
import java.util.*; import org.apache.commons.lang.*; import org.apache.samza.sql.*;
[ "java.util", "org.apache.commons", "org.apache.samza" ]
java.util; org.apache.commons; org.apache.samza;
2,724,637
public Observable<ServiceResponse<DdosProtectionPlanInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String ddosProtectionPlanName, Map<String, String> tags) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (ddosProtectionPlanName == null) { throw new IllegalArgumentException("Parameter ddosProtectionPlanName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } Validator.validate(tags); final String apiVersion = "2019-04-01"; TagsObject parameters = new TagsObject(); parameters.withTags(tags); Observable<Response<ResponseBody>> observable = service.updateTags(resourceGroupName, ddosProtectionPlanName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent()); return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<DdosProtectionPlanInner>() { }.getType()); }
Observable<ServiceResponse<DdosProtectionPlanInner>> function(String resourceGroupName, String ddosProtectionPlanName, Map<String, String> tags) { if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (ddosProtectionPlanName == null) { throw new IllegalArgumentException(STR); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } Validator.validate(tags); final String apiVersion = STR; TagsObject parameters = new TagsObject(); parameters.withTags(tags); Observable<Response<ResponseBody>> observable = service.updateTags(resourceGroupName, ddosProtectionPlanName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent()); return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<DdosProtectionPlanInner>() { }.getType()); }
/** * Update a DDoS protection plan tags. * * @param resourceGroupName The name of the resource group. * @param ddosProtectionPlanName The name of the DDoS protection plan. * @param tags Resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */
Update a DDoS protection plan tags
updateTagsWithServiceResponseAsync
{ "repo_name": "navalev/azure-sdk-for-java", "path": "sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/implementation/DdosProtectionPlansInner.java", "license": "mit", "size": 75189 }
[ "com.google.common.reflect.TypeToken", "com.microsoft.azure.management.network.v2019_04_01.TagsObject", "com.microsoft.rest.ServiceResponse", "com.microsoft.rest.Validator", "java.util.Map" ]
import com.google.common.reflect.TypeToken; import com.microsoft.azure.management.network.v2019_04_01.TagsObject; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.util.Map;
import com.google.common.reflect.*; import com.microsoft.azure.management.network.v2019_04_01.*; import com.microsoft.rest.*; import java.util.*;
[ "com.google.common", "com.microsoft.azure", "com.microsoft.rest", "java.util" ]
com.google.common; com.microsoft.azure; com.microsoft.rest; java.util;
1,941,050
@Override public ItemStack getCraftingResult(InventoryCrafting grid) { ItemStack pureCore = ItemStack.EMPTY; ItemStack outStack = ItemStack.EMPTY; for(int i = 0; i < grid.getSizeInventory(); i++) { if(grid.getStackInSlot(i).getItem() instanceof EnderItemPureCore) { pureCore = grid.getStackInSlot(i).copy(); } else if(!grid.getStackInSlot(i).isEmpty()) { outStack = grid.getStackInSlot(i).copy(); } } outStack.setCount(outStack.getCount() * 2 <= (pureCore.getMaxDamage() - pureCore.getItemDamage()) ? outStack.getCount() * 2 : (pureCore.getMaxDamage() - pureCore.getItemDamage()) * 2); //MaxDamage - ItemDamage = remaining uses return outStack; }
ItemStack function(InventoryCrafting grid) { ItemStack pureCore = ItemStack.EMPTY; ItemStack outStack = ItemStack.EMPTY; for(int i = 0; i < grid.getSizeInventory(); i++) { if(grid.getStackInSlot(i).getItem() instanceof EnderItemPureCore) { pureCore = grid.getStackInSlot(i).copy(); } else if(!grid.getStackInSlot(i).isEmpty()) { outStack = grid.getStackInSlot(i).copy(); } } outStack.setCount(outStack.getCount() * 2 <= (pureCore.getMaxDamage() - pureCore.getItemDamage()) ? outStack.getCount() * 2 : (pureCore.getMaxDamage() - pureCore.getItemDamage()) * 2); return outStack; }
/** * Get the duplicated stack output * @param grid crafting grid containing the already-known-to-be-corrrect items * @return a stack that is equal to double to duplicating stack */
Get the duplicated stack output
getCraftingResult
{ "repo_name": "wundrweapon/Ender-Advancement", "path": "src/main/java/wundr/endadvance/recipes/ItemDupeRecipe.java", "license": "mit", "size": 6652 }
[ "net.minecraft.inventory.InventoryCrafting", "net.minecraft.item.ItemStack" ]
import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack;
import net.minecraft.inventory.*; import net.minecraft.item.*;
[ "net.minecraft.inventory", "net.minecraft.item" ]
net.minecraft.inventory; net.minecraft.item;
1,622,693
private void add(String destName, String busName) { if (tc.isEntryEnabled()) SibTr.entry(tc, "add", new Object[] { destName, busName }); collector.put( CompoundName.compound(destName, busName), new CompoundName(destName, busName)); if (tc.isEntryEnabled()) SibTr.exit(tc, "add"); }
void function(String destName, String busName) { if (tc.isEntryEnabled()) SibTr.entry(tc, "add", new Object[] { destName, busName }); collector.put( CompoundName.compound(destName, busName), new CompoundName(destName, busName)); if (tc.isEntryEnabled()) SibTr.exit(tc, "add"); }
/** * Add a destination to the chain. * * @param destName * @param busName */
Add a destination to the chain
add
{ "repo_name": "OpenLiberty/open-liberty", "path": "dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/utils/AliasChainValidator.java", "license": "epl-1.0", "size": 8594 }
[ "com.ibm.ws.sib.utils.ras.SibTr" ]
import com.ibm.ws.sib.utils.ras.SibTr;
import com.ibm.ws.sib.utils.ras.*;
[ "com.ibm.ws" ]
com.ibm.ws;
808,365
@NotNull protected String buildMetadataManagerKey() { return DatabaseMetaDataRetrievalHandler.METADATA_MANAGER; }
String function() { return DatabaseMetaDataRetrievalHandler.METADATA_MANAGER; }
/** * Builds the metadata manager key. * @return such key. */
Builds the metadata manager key
buildMetadataManagerKey
{ "repo_name": "rydnr/queryj-rt", "path": "queryj-core/src/main/java/org/acmsl/queryj/api/AbstractQueryJTemplateContext.java", "license": "gpl-2.0", "size": 10634 }
[ "org.acmsl.queryj.tools.handlers.DatabaseMetaDataRetrievalHandler" ]
import org.acmsl.queryj.tools.handlers.DatabaseMetaDataRetrievalHandler;
import org.acmsl.queryj.tools.handlers.*;
[ "org.acmsl.queryj" ]
org.acmsl.queryj;
1,602,643
@Test public void simplePrimitiveNumericList() { List<Integer> numbers = createJsonMapper().toJavaList(jsonFromClasspath("numbers"), Integer.class); assertTrue(numbers.size() == 3); assertTrue(numbers.get(0).equals(1234)); assertTrue(numbers.get(1).equals(5678)); assertTrue(numbers.get(2).equals(9012)); }
void function() { List<Integer> numbers = createJsonMapper().toJavaList(jsonFromClasspath(STR), Integer.class); assertTrue(numbers.size() == 3); assertTrue(numbers.get(0).equals(1234)); assertTrue(numbers.get(1).equals(5678)); assertTrue(numbers.get(2).equals(9012)); }
/** * Can we handle simple primitive numeric list mapping? */
Can we handle simple primitive numeric list mapping
simplePrimitiveNumericList
{ "repo_name": "oleke/Gender-Mining", "path": "restfb/source/test/com/restfb/JsonMapperToJavaTest.java", "license": "apache-2.0", "size": 14600 }
[ "java.util.List", "org.junit.Assert" ]
import java.util.List; import org.junit.Assert;
import java.util.*; import org.junit.*;
[ "java.util", "org.junit" ]
java.util; org.junit;
2,855,350
protected ObjectInputStream createObjectInputStream(InputStream is) throws IOException { return new CodebaseAwareObjectInputStream(is, getBeanClassLoader(), isAcceptProxyClasses()); }
ObjectInputStream function(InputStream is) throws IOException { return new CodebaseAwareObjectInputStream(is, getBeanClassLoader(), isAcceptProxyClasses()); }
/** * Create an ObjectInputStream for the given InputStream. * <p>The default implementation creates a Spring {@link CodebaseAwareObjectInputStream}. * @param is the InputStream to read from * @return the new ObjectInputStream instance to use * @throws java.io.IOException if creation of the ObjectInputStream failed */
Create an ObjectInputStream for the given InputStream. The default implementation creates a Spring <code>CodebaseAwareObjectInputStream</code>
createObjectInputStream
{ "repo_name": "sunpy1106/SpringBeanLifeCycle", "path": "src/main/java/org/springframework/remoting/rmi/RemoteInvocationSerializingExporter.java", "license": "apache-2.0", "size": 6094 }
[ "java.io.IOException", "java.io.InputStream", "java.io.ObjectInputStream" ]
import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream;
import java.io.*;
[ "java.io" ]
java.io;
1,941,594
@Override public boolean filterJoinCandidate(final Tuple tuple1, final Tuple tuple2, final byte[] customData) { final String geoJsonString1 = new String(tuple1.getDataBytes()); final String geoJsonString2 = new String(tuple2.getDataBytes()); final JSONObject jsonObject1 = new JSONObject(geoJsonString1); final JSONObject jsonObject2 = new JSONObject(geoJsonString2); // Full text search on string (if provided) if(customData != null && customData.length > 1) { final String customDataString = new String(customData); final String[] customParts = customDataString.split(":"); if(customParts.length != 2) { logger.error("Unable to split {} into two parts", customDataString); return false; } final String key = customParts[0]; final String value = customParts[1]; if(! containsProperty(jsonObject1, key, value) && ! containsProperty(jsonObject2, key, value)) { return false; } } final OGCGeometry geometry1 = extractGeometry(jsonObject1); final OGCGeometry geometry2 = extractGeometry(jsonObject2); return performIntersectionTest(geometry1, geometry2); }
boolean function(final Tuple tuple1, final Tuple tuple2, final byte[] customData) { final String geoJsonString1 = new String(tuple1.getDataBytes()); final String geoJsonString2 = new String(tuple2.getDataBytes()); final JSONObject jsonObject1 = new JSONObject(geoJsonString1); final JSONObject jsonObject2 = new JSONObject(geoJsonString2); if(customData != null && customData.length > 1) { final String customDataString = new String(customData); final String[] customParts = customDataString.split(":"); if(customParts.length != 2) { logger.error(STR, customDataString); return false; } final String key = customParts[0]; final String value = customParts[1]; if(! containsProperty(jsonObject1, key, value) && ! containsProperty(jsonObject2, key, value)) { return false; } } final OGCGeometry geometry1 = extractGeometry(jsonObject1); final OGCGeometry geometry2 = extractGeometry(jsonObject2); return performIntersectionTest(geometry1, geometry2); }
/** * Perform a real join based on the geometry of the data */
Perform a real join based on the geometry of the data
filterJoinCandidate
{ "repo_name": "jnidzwetzki/bboxdb", "path": "bboxdb-server/src/main/java/org/bboxdb/query/filter/UserDefinedGeoJsonSpatialFilter.java", "license": "apache-2.0", "size": 7270 }
[ "com.esri.core.geometry.ogc.OGCGeometry", "org.bboxdb.storage.entity.Tuple", "org.json.JSONObject" ]
import com.esri.core.geometry.ogc.OGCGeometry; import org.bboxdb.storage.entity.Tuple; import org.json.JSONObject;
import com.esri.core.geometry.ogc.*; import org.bboxdb.storage.entity.*; import org.json.*;
[ "com.esri.core", "org.bboxdb.storage", "org.json" ]
com.esri.core; org.bboxdb.storage; org.json;
2,724,945
private Set<AlertTargetEntity> getMockTargets() throws Exception { AlertTargetEntity entity = new AlertTargetEntity(); entity.setTargetId(ALERT_TARGET_ID); entity.setDescription(ALERT_TARGET_DESC); entity.setTargetName(ALERT_TARGET_NAME); entity.setNotificationType(ALERT_TARGET_TYPE); Set<AlertTargetEntity> targets = new HashSet<AlertTargetEntity>(); targets.add(entity); return targets; }
Set<AlertTargetEntity> function() throws Exception { AlertTargetEntity entity = new AlertTargetEntity(); entity.setTargetId(ALERT_TARGET_ID); entity.setDescription(ALERT_TARGET_DESC); entity.setTargetName(ALERT_TARGET_NAME); entity.setNotificationType(ALERT_TARGET_TYPE); Set<AlertTargetEntity> targets = new HashSet<AlertTargetEntity>(); targets.add(entity); return targets; }
/** * Gets some mock {@link AlertTargetEntity} instances. * * @return */
Gets some mock <code>AlertTargetEntity</code> instances
getMockTargets
{ "repo_name": "arenadata/ambari", "path": "ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AlertGroupResourceProviderTest.java", "license": "apache-2.0", "size": 35410 }
[ "java.util.HashSet", "java.util.Set", "org.apache.ambari.server.orm.entities.AlertTargetEntity" ]
import java.util.HashSet; import java.util.Set; import org.apache.ambari.server.orm.entities.AlertTargetEntity;
import java.util.*; import org.apache.ambari.server.orm.entities.*;
[ "java.util", "org.apache.ambari" ]
java.util; org.apache.ambari;
548,368
protected Object convertToDate(final Class<?> type, final Object value, final String pattern) { final DateFormat df = new SimpleDateFormat(pattern); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } final Date date = df.parse((String) value); if (type.equals(Timestamp.class)) { return new Timestamp(date.getTime()); } return date; } catch (final Exception e) { throw new ConversionException("Error converting String to Date", e); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
Object function(final Class<?> type, final Object value, final String pattern) { final DateFormat df = new SimpleDateFormat(pattern); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } final Date date = df.parse((String) value); if (type.equals(Timestamp.class)) { return new Timestamp(date.getTime()); } return date; } catch (final Exception e) { throw new ConversionException(STR, e); } } throw new ConversionException(STR + value.getClass().getName() + STR + type.getName()); }
/** * Convert a String to a Date with the specified pattern. * @param type String * @param value value of String * @param pattern date pattern to parse with * @return Converted value for property population */
Convert a String to a Date with the specified pattern
convertToDate
{ "repo_name": "yyitsz/myjavastudio", "path": "studyappfuse2/core/src/main/java/org/yy/util/DateConverter.java", "license": "apache-2.0", "size": 3236 }
[ "java.sql.Timestamp", "java.text.DateFormat", "java.text.SimpleDateFormat", "java.util.Date", "org.apache.commons.beanutils.ConversionException", "org.apache.commons.lang.StringUtils" ]
import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.lang.StringUtils;
import java.sql.*; import java.text.*; import java.util.*; import org.apache.commons.beanutils.*; import org.apache.commons.lang.*;
[ "java.sql", "java.text", "java.util", "org.apache.commons" ]
java.sql; java.text; java.util; org.apache.commons;
1,155,879
@SuppressWarnings("unchecked") public String serialize() { Map map = new LinkedHashMap(); map.put("path", path.toString()); map.put("headHash", headHash); map.put("headLen", headLen); map.put("inode", iNode); try { JsonMapper objectMapper = DataCollectorServices.instance().get(JsonMapper.SERVICE_KEY); return objectMapper.writeValueAsString(map); } catch (Exception ex) { throw new RuntimeException(Utils.format("Unexpected exception: {}", ex.toString()), ex); } }
@SuppressWarnings(STR) String function() { Map map = new LinkedHashMap(); map.put("path", path.toString()); map.put(STR, headHash); map.put(STR, headLen); map.put("inode", iNode); try { JsonMapper objectMapper = DataCollectorServices.instance().get(JsonMapper.SERVICE_KEY); return objectMapper.writeValueAsString(map); } catch (Exception ex) { throw new RuntimeException(Utils.format(STR, ex.toString()), ex); } }
/** * Serializes the <code>LiveFile</code> as a string. * * @return the serialized string representation of the <code>LiveFile</code>. */
Serializes the <code>LiveFile</code> as a string
serialize
{ "repo_name": "z123/datacollector", "path": "commonlib/src/main/java/com/streamsets/pipeline/lib/io/LiveFile.java", "license": "apache-2.0", "size": 8354 }
[ "com.streamsets.pipeline.api.ext.DataCollectorServices", "com.streamsets.pipeline.api.ext.json.JsonMapper", "com.streamsets.pipeline.api.impl.Utils", "java.util.LinkedHashMap", "java.util.Map" ]
import com.streamsets.pipeline.api.ext.DataCollectorServices; import com.streamsets.pipeline.api.ext.json.JsonMapper; import com.streamsets.pipeline.api.impl.Utils; import java.util.LinkedHashMap; import java.util.Map;
import com.streamsets.pipeline.api.ext.*; import com.streamsets.pipeline.api.ext.json.*; import com.streamsets.pipeline.api.impl.*; import java.util.*;
[ "com.streamsets.pipeline", "java.util" ]
com.streamsets.pipeline; java.util;
1,185,608
public static Color toCMYKGrayColor(final float black) { // Calculated color components final float[] cmyk = new float[] { 0f, 0f, 0f, 1.0f - black }; // Create native color return DeviceCMYKColorSpace.createCMYKColor(cmyk); }
static Color function(final float black) { final float[] cmyk = new float[] { 0f, 0f, 0f, 1.0f - black }; return DeviceCMYKColorSpace.createCMYKColor(cmyk); }
/** * Creates an uncalibrated CMYK color with the given gray value. * * @param black * the gray component (0 - 1) * @return the CMYK color */
Creates an uncalibrated CMYK color with the given gray value
toCMYKGrayColor
{ "repo_name": "Guronzan/Apache-XmlGraphics", "path": "src/main/java/org/apache/xmlgraphics/java2d/color/ColorUtil.java", "license": "apache-2.0", "size": 6348 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
2,208,364
public Color getTextColor() { checkWidget(); return textColor; }
Color function() { checkWidget(); return textColor; }
/** * Returns the color of the text when the button is enabled and not selected. * * @return the receiver's text color * * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */
Returns the color of the text when the button is enabled and not selected
getTextColor
{ "repo_name": "Haixing-Hu/swt-widgets", "path": "src/main/java/com/github/haixing_hu/swt/toolbar/RoundedToolItem.java", "license": "epl-1.0", "size": 29275 }
[ "org.eclipse.swt.graphics.Color" ]
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
2,454,771
public int writeArray(String toArray, int toOffset, float[] fromArray, int fromOffset, int n) { return PdBase.writeArray(toArray, toOffset, fromArray, fromOffset, n); }
int function(String toArray, int toOffset, float[] fromArray, int fromOffset, int n) { return PdBase.writeArray(toArray, toOffset, fromArray, fromOffset, n); }
/** * Delegates to the corresponding method in {@link PdBase}. */
Delegates to the corresponding method in <code>PdBase</code>
writeArray
{ "repo_name": "rvega/morphasynth", "path": "vendors/pd-for-ios/libpd/java/org/puredata/processing/PureDataP5Base.java", "license": "gpl-3.0", "size": 6445 }
[ "org.puredata.core.PdBase" ]
import org.puredata.core.PdBase;
import org.puredata.core.*;
[ "org.puredata.core" ]
org.puredata.core;
2,109,561
protected DoublyIndexedTable getTraitInformationTable() { return xmlTraitInformation; }
DoublyIndexedTable function() { return xmlTraitInformation; }
/** * Returns the table of TraitInformation objects for this element. */
Returns the table of TraitInformation objects for this element
getTraitInformationTable
{ "repo_name": "shyamalschandra/flex-sdk", "path": "modules/thirdparty/batik/sources/org/apache/flex/forks/batik/dom/svg/SVGOMFEColorMatrixElement.java", "license": "apache-2.0", "size": 4863 }
[ "org.apache.flex.forks.batik.util.DoublyIndexedTable" ]
import org.apache.flex.forks.batik.util.DoublyIndexedTable;
import org.apache.flex.forks.batik.util.*;
[ "org.apache.flex" ]
org.apache.flex;
1,695,514
@Test public void testIntToHex() { assertEquals("", Conversion.intToHex(0x00000000, 0, "", 0, 0)); assertEquals("", Conversion.intToHex(0x00000000, 100, "", 0, 0)); assertEquals("", Conversion.intToHex(0x00000000, 0, "", 100, 0)); assertEquals( "ffffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 0)); assertEquals( "3fffffffffffffffffffffff", Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 0, 1)); assertEquals( "feffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 2)); assertEquals( "fedcffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 4)); assertEquals( "fedcba0fffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 7)); assertEquals( "fedcba09ffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 8)); assertEquals( "fff3ffffffffffffffffffff", Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 3, 1)); assertEquals( "ffffefffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 2)); assertEquals( "ffffedcfffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 4)); assertEquals( "ffffedcba0ffffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 7)); assertEquals( "ffffedcba09fffffffffffff", Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 8)); assertEquals( "7fffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 1, "ffffffffffffffffffffffff", 0, 1)); assertEquals( "bfffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF, 2, "ffffffffffffffffffffffff", 0, 1)); assertEquals( "fffdb97512ffffffffffffff", Conversion.intToHex(0x90ABCDEF, 3, "ffffffffffffffffffffffff", 3, 8)); // assertEquals("ffffffffffffffffffffffff",Conversion.intToHex(0x90ABCDEF, // 4,"ffffffffffffffffffffffff",3,8));//rejected by assertion assertEquals( "fffedcba09ffffffffffffff", Conversion.intToHex(0x90ABCDEF, 4, "ffffffffffffffffffffffff", 3, 7)); assertEquals("fedcba09", Conversion.intToHex(0x90ABCDEF, 0, "", 0, 8)); try { Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8); fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected"); } catch (final StringIndexOutOfBoundsException e) { // OK } }
void function() { assertEquals(STRSTRSTR", 0, 0)); assertEquals(STRSTRffffffffffffffffffffffffSTRffffffffffffffffffffffffSTR3fffffffffffffffffffffffSTRffffffffffffffffffffffffSTRfeffffffffffffffffffffffSTRffffffffffffffffffffffffSTRfedcffffffffffffffffffffSTRffffffffffffffffffffffffSTRfedcba0fffffffffffffffffSTRffffffffffffffffffffffffSTRfedcba09ffffffffffffffffSTRffffffffffffffffffffffffSTRfff3ffffffffffffffffffffSTRffffffffffffffffffffffffSTRffffefffffffffffffffffffSTRffffffffffffffffffffffffSTRffffedcfffffffffffffffffSTRffffffffffffffffffffffffSTRffffedcba0ffffffffffffffSTRffffffffffffffffffffffffSTRffffedcba09fffffffffffffSTRffffffffffffffffffffffffSTR7fffffffffffffffffffffffSTRffffffffffffffffffffffffSTRbfffffffffffffffffffffffSTRffffffffffffffffffffffffSTRfffdb97512ffffffffffffffSTRffffffffffffffffffffffffSTRfffedcba09ffffffffffffffSTRffffffffffffffffffffffffSTRfedcba09STRSTRSTRThrown STR expected"); } catch (final StringIndexOutOfBoundsException e) { } }
/** * Tests {@link Conversion#intToHex(int, int, String, int, int)}. */
Tests <code>Conversion#intToHex(int, int, String, int, int)</code>
testIntToHex
{ "repo_name": "martingwhite/astor", "path": "examples/lang_7/src/test/java/org/apache/commons/lang3/ConversionTest.java", "license": "gpl-2.0", "size": 100416 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
2,267,095
void checkCanDropTable(Identity identity, SchemaTableName tableName);
void checkCanDropTable(Identity identity, SchemaTableName tableName);
/** * Check if identity is allowed to drop the specified table in this catalog. * @throws AccessDeniedException if not allowed */
Check if identity is allowed to drop the specified table in this catalog
checkCanDropTable
{ "repo_name": "lingochamp/presto", "path": "presto-spi/src/main/java/com/facebook/presto/spi/security/ConnectorAccessControl.java", "license": "apache-2.0", "size": 4126 }
[ "com.facebook.presto.spi.SchemaTableName" ]
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.*;
[ "com.facebook.presto" ]
com.facebook.presto;
2,850,716
@Override protected Hashtable<String, FeaturePainter> getFeatureHash() { final Hashtable<String, FeaturePainter> res = new Hashtable<String, FeaturePainter>(); res.put(_featureType, _myFeature); return res; }
Hashtable<String, FeaturePainter> function() { final Hashtable<String, FeaturePainter> res = new Hashtable<String, FeaturePainter>(); res.put(_featureType, _myFeature); return res; }
/** * accessor to get the list of features we want to plot */
accessor to get the list of features we want to plot
getFeatureHash
{ "repo_name": "debrief/debrief", "path": "org.mwc.cmap.legacy/src/MWC/GUI/VPF/CoverageLayer.java", "license": "epl-1.0", "size": 12975 }
[ "java.util.Hashtable" ]
import java.util.Hashtable;
import java.util.*;
[ "java.util" ]
java.util;
1,691,036
public SessionShortVoCollection listSession(Date startDate, Date endDate, ActivityVo activity, ServiceRefVo service, LocationRefVo location, HcpLiteVo listOwner, ServiceFunctionRefVo clinicType, LocationRefVoCollection locationList) { // all params must be set if (startDate == null || endDate == null || activity == null) throw new DomainRuntimeException("Not all mandatory search params set in method listGenericSession"); ArrayList<String> markers = new ArrayList<String>(); ArrayList<Serializable> values = new ArrayList<Serializable>(); String serviceCriteria = ""; String locationCriteria = ""; String clinicTypeCriteria = ""; String clinicTypeJoin = ""; String listOwnerJoin = ""; String listOwnerCriteria = ""; // mandatory fields markers.add("activityId"); markers.add("open"); markers.add("startDate"); markers.add("endDate"); values.add(activity.getID_Activity()); values.add(getDomLookup(Session_Status_and_Reason.OPEN)); values.add(startDate.getDate()); values.add(endDate.getDate()); if (service != null) { markers.add("idService"); values.add(service.getID_Service()); serviceCriteria = " and session.service.id = :idService"; } if (clinicType != null) { markers.add("idClinicType"); values.add(clinicType.getID_ServiceFunction()); clinicTypeJoin = " join slot.functions as func "; clinicTypeCriteria = " and func.id = :idClinicType "; } if (listOwner != null) { markers.add("idListOwner"); values.add(listOwner.getID_Hcp()); listOwnerJoin = " left join session.listOwners as lowners left join lowners.hcp shcp "; listOwnerCriteria = " and shcp.id = :idListOwner "; } if (location != null) { markers.add("idLocation"); values.add(location.getID_Location()); locationCriteria = " and session.schLocation.id = :idLocation"; } else if(locationList != null) { List<String> locationIds = new ArrayList<String>(); for(LocationRefVo voRef : locationList) locationIds.add(voRef.getID_Location().toString()); locationCriteria = " and session.schLocation.id in (" + getIdString(locationIds) + ")"; } DomainFactory factory = getDomainFactory(); List<?> sessions = factory.find(" Select distinct session from Sch_Session as session " + " left join session.sessionSlots as slot " + clinicTypeJoin + listOwnerJoin + " where ( slot.activity.id = :activityId) " + " and session.sessionDate >= :startDate and session.sessionDate <= :endDate " + serviceCriteria + locationCriteria + clinicTypeCriteria + listOwnerCriteria + " and session.sessionStatus = :open and (session.isTheatreSession = FALSE or session.isTheatreSession is null) and session.isRIE is null ", markers, values, 1000); if (sessions == null || sessions.size() == 0) return SessionShortVoAssembler.createSessionShortVoCollectionFromSch_Session(sessions); SessionShortVoCollection voCollSessionShort = new SessionShortVoCollection(); for (int i = 0; i < sessions.size(); i++) { if (sessions.get(i) instanceof Sch_Session) { Sch_Session session = (Sch_Session) sessions.get(i); SessionShortVo sessionShort = SessionShortVoAssembler.create(session); if (session.getSessionSlots() != null) { sessionShort.setCalendarSlots(new SessionSlotWithStatusOnlyVoCollection()); Iterator<?> slotIterator = session.getSessionSlots().iterator(); while (slotIterator.hasNext()) { Session_Slot slot = (Session_Slot) slotIterator.next(); SessionSlotWithStatusOnlyVo sessionSlot = SessionSlotWithStatusOnlyVoAssembler.create(slot); if (sessionSlot.getActivity().equals(activity)) { sessionShort.getCalendarSlots().add(sessionSlot); } } } voCollSessionShort.add(sessionShort); } } return voCollSessionShort.sort(); }
SessionShortVoCollection function(Date startDate, Date endDate, ActivityVo activity, ServiceRefVo service, LocationRefVo location, HcpLiteVo listOwner, ServiceFunctionRefVo clinicType, LocationRefVoCollection locationList) { if (startDate == null endDate == null activity == null) throw new DomainRuntimeException(STR); ArrayList<String> markers = new ArrayList<String>(); ArrayList<Serializable> values = new ArrayList<Serializable>(); String serviceCriteria = STRSTRSTRSTRSTRSTRactivityIdSTRopenSTRstartDateSTRendDateSTRidServiceSTR and session.service.id = :idServiceSTRidClinicTypeSTR join slot.functions as func STR and func.id = :idClinicType STRidListOwnerSTR left join session.listOwners as lowners left join lowners.hcp shcp STR and shcp.id = :idListOwner STRidLocationSTR and session.schLocation.id = :idLocationSTR and session.schLocation.id in (STR)STR Select distinct session from Sch_Session as session STR left join session.sessionSlots as slot STR where ( slot.activity.id = :activityId) STR and session.sessionDate >= :startDate and session.sessionDate <= :endDate STR and session.sessionStatus = :open and (session.isTheatreSession = FALSE or session.isTheatreSession is null) and session.isRIE is null ", markers, values, 1000); if (sessions == null sessions.size() == 0) return SessionShortVoAssembler.createSessionShortVoCollectionFromSch_Session(sessions); SessionShortVoCollection voCollSessionShort = new SessionShortVoCollection(); for (int i = 0; i < sessions.size(); i++) { if (sessions.get(i) instanceof Sch_Session) { Sch_Session session = (Sch_Session) sessions.get(i); SessionShortVo sessionShort = SessionShortVoAssembler.create(session); if (session.getSessionSlots() != null) { sessionShort.setCalendarSlots(new SessionSlotWithStatusOnlyVoCollection()); Iterator<?> slotIterator = session.getSessionSlots().iterator(); while (slotIterator.hasNext()) { Session_Slot slot = (Session_Slot) slotIterator.next(); SessionSlotWithStatusOnlyVo sessionSlot = SessionSlotWithStatusOnlyVoAssembler.create(slot); if (sessionSlot.getActivity().equals(activity)) { sessionShort.getCalendarSlots().add(sessionSlot); } } } voCollSessionShort.add(sessionShort); } } return voCollSessionShort.sort(); }
/** * list sessions for scheduling */
list sessions for scheduling
listSession
{ "repo_name": "open-health-hub/openMAXIMS", "path": "openmaxims_workspace/RefMan/src/ims/RefMan/domain/impl/BookAppointmentImpl.java", "license": "agpl-3.0", "size": 82928 }
[ "java.io.Serializable", "java.util.ArrayList", "java.util.Iterator" ]
import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,270,763
public void refreshPlayers(Player[] players, Player currentPlayer) { otherPlayer = new ArrayList<Player>(); for (Player player : players) { if (player != currentPlayer && player != null) { otherPlayer.add(player); } } playerListPosition = 0; playerLabel.setText(otherPlayer.get(0).getCollege().getName()); setTradePrice(0); }
void function(Player[] players, Player currentPlayer) { otherPlayer = new ArrayList<Player>(); for (Player player : players) { if (player != currentPlayer && player != null) { otherPlayer.add(player); } } playerListPosition = 0; playerLabel.setText(otherPlayer.get(0).getCollege().getName()); setTradePrice(0); }
/** * Refreshes the list of potential trade-offer recipients that can be examined in the auction-house's interface * * @param players The list of players who are currently playing the game * @param currentPlayer The player that is currently undertaking their turn */
Refreshes the list of potential trade-offer recipients that can be examined in the auction-house's interface
refreshPlayers
{ "repo_name": "NicoPinedo/SEPR4", "path": "core/src/main/drtn/game/screens/tables/MarketInterfaceTable.java", "license": "gpl-3.0", "size": 38722 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
773,919
public AbstractSession getParentIdentityMapSession(DatabaseQuery query) { ClassDescriptor descriptor = null; if (query != null){ descriptor = query.getDescriptor(); } return getParentIdentityMapSession(descriptor, false, false); }
AbstractSession function(DatabaseQuery query) { ClassDescriptor descriptor = null; if (query != null){ descriptor = query.getDescriptor(); } return getParentIdentityMapSession(descriptor, false, false); }
/** * INTERNAL: * Gets the next link in the chain of sessions followed by a query's check * early return, the chain of sessions with identity maps all the way up to * the root session. */
Gets the next link in the chain of sessions followed by a query's check early return, the chain of sessions with identity maps all the way up to the root session
getParentIdentityMapSession
{ "repo_name": "gameduell/eclipselink.runtime", "path": "foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/AbstractSession.java", "license": "epl-1.0", "size": 198170 }
[ "org.eclipse.persistence.descriptors.ClassDescriptor", "org.eclipse.persistence.queries.DatabaseQuery" ]
import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.descriptors.*; import org.eclipse.persistence.queries.*;
[ "org.eclipse.persistence" ]
org.eclipse.persistence;
1,015,688
public ActionProvider getSupportActionProvider(); /** * Expand the action view associated with this menu item. The menu item must have an action view * set, as well as the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a * listener has been set using {@link #setSupportOnActionExpandListener(android.support.v4.view.MenuItemCompat.OnActionExpandListener)}
ActionProvider function(); /** * Expand the action view associated with this menu item. The menu item must have an action view * set, as well as the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a * listener has been set using {@link #setSupportOnActionExpandListener(android.support.v4.view.MenuItemCompat.OnActionExpandListener)}
/** * Gets the {@link ActionProvider}. * * @return The action provider. * @see ActionProvider * @see #setSupportActionProvider(ActionProvider) */
Gets the <code>ActionProvider</code>
getSupportActionProvider
{ "repo_name": "masconsult/android-recipes-app", "path": "vendors/android-support-v7-appcompat/libs-src/android-support-v4/android/support/v4/internal/view/SupportMenuItem.java", "license": "apache-2.0", "size": 9213 }
[ "android.support.v4.view.ActionProvider", "android.support.v4.view.MenuItemCompat" ]
import android.support.v4.view.ActionProvider; import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.*;
[ "android.support" ]
android.support;
2,470,124
void setPipelineInConstruction(LocatedBlock lastBlock) throws IOException{ // setup pipeline to append to the last block XXX retries?? setPipeline(lastBlock); if (nodes.length < 1) { throw new IOException("Unable to retrieve blocks locations " + " for last block " + block + " of file " + src); } }
void setPipelineInConstruction(LocatedBlock lastBlock) throws IOException{ setPipeline(lastBlock); if (nodes.length < 1) { throw new IOException(STR + STR + block + STR + src); } }
/** * Set pipeline in construction * * @param lastBlock the last block of a file * @throws IOException */
Set pipeline in construction
setPipelineInConstruction
{ "repo_name": "JingchengDu/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DataStreamer.java", "license": "apache-2.0", "size": 77567 }
[ "java.io.IOException", "org.apache.hadoop.hdfs.protocol.LocatedBlock" ]
import java.io.IOException; import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import java.io.*; import org.apache.hadoop.hdfs.protocol.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
1,601,058
private void createPicker() { if (isSimple()) { pickerPanel = panel; setContent(panel.getComposite()); } else if (isDropDown()) { disposePicker(); Shell shell = getContentShell(); int style = (isSimple() ? SWT.NONE : SWT.BORDER) | SWT.DOUBLE_BUFFERED; VCanvas canvas = new VCanvas(shell, style); pickerPanel = canvas.getPanel(); pickerPanel.setWidget(canvas); VGridLayout layout = new VGridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 1; pickerPanel.setLayout(layout); setContent(pickerPanel.getComposite());
void function() { if (isSimple()) { pickerPanel = panel; setContent(panel.getComposite()); } else if (isDropDown()) { disposePicker(); Shell shell = getContentShell(); int style = (isSimple() ? SWT.NONE : SWT.BORDER) SWT.DOUBLE_BUFFERED; VCanvas canvas = new VCanvas(shell, style); pickerPanel = canvas.getPanel(); pickerPanel.setWidget(canvas); VGridLayout layout = new VGridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 1; pickerPanel.setLayout(layout); setContent(pickerPanel.getComposite());
/** * If style is neither SIMPLE or DROP_DOWN, then this method simply returns, * otherwise it creates the picker. */
If style is neither SIMPLE or DROP_DOWN, then this method simply returns, otherwise it creates the picker
createPicker
{ "repo_name": "debrief/debrief", "path": "org.eclipse.nebula.widgets.cdatetime/src/org/eclipse/nebula/widgets/cdatetime/CDateTime.java", "license": "epl-1.0", "size": 61447 }
[ "org.eclipse.nebula.cwt.v.VCanvas", "org.eclipse.nebula.cwt.v.VGridLayout", "org.eclipse.swt.widgets.Shell" ]
import org.eclipse.nebula.cwt.v.VCanvas; import org.eclipse.nebula.cwt.v.VGridLayout; import org.eclipse.swt.widgets.Shell;
import org.eclipse.nebula.cwt.v.*; import org.eclipse.swt.widgets.*;
[ "org.eclipse.nebula", "org.eclipse.swt" ]
org.eclipse.nebula; org.eclipse.swt;
2,070,579
@Override public void toBytes(ByteBuf buf) { PacketBuffer buffer = new PacketBuffer(buf); try { buffer.writeInt(this.keyBindCode.length()); buffer.writeStringToBuffer(this.keyBindCode); buffer.writeInt(this.keyBindValue); } catch (IOException e) { ProjectZuluLog.severe("There was a problem encoding the packet in PZPacketKeyBind : " + buffer + ".", this); e.printStackTrace(); } }
void function(ByteBuf buf) { PacketBuffer buffer = new PacketBuffer(buf); try { buffer.writeInt(this.keyBindCode.length()); buffer.writeStringToBuffer(this.keyBindCode); buffer.writeInt(this.keyBindValue); } catch (IOException e) { ProjectZuluLog.severe(STR + buffer + ".", this); e.printStackTrace(); } }
/** * Writes the message into bytes. */
Writes the message into bytes
toBytes
{ "repo_name": "soultek101/projectzulu1.7.10", "path": "src/main/java/com/stek101/projectzulu/common/mobs/packets/PZPacketKeyBind.java", "license": "lgpl-2.1", "size": 3181 }
[ "com.stek101.projectzulu.common.core.ProjectZuluLog", "io.netty.buffer.ByteBuf", "java.io.IOException", "net.minecraft.network.PacketBuffer" ]
import com.stek101.projectzulu.common.core.ProjectZuluLog; import io.netty.buffer.ByteBuf; import java.io.IOException; import net.minecraft.network.PacketBuffer;
import com.stek101.projectzulu.common.core.*; import io.netty.buffer.*; import java.io.*; import net.minecraft.network.*;
[ "com.stek101.projectzulu", "io.netty.buffer", "java.io", "net.minecraft.network" ]
com.stek101.projectzulu; io.netty.buffer; java.io; net.minecraft.network;
1,783,269
public static Cursor getUpcomingEpisodes(boolean isOnlyUnwatched, Context context) { String[][] args = buildActivityQuery(context, ActivityType.UPCOMING, isOnlyUnwatched, -1); return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, ActivityFragment.ActivityQuery.PROJECTION, args[0][0], args[1], args[2][0]); }
static Cursor function(boolean isOnlyUnwatched, Context context) { String[][] args = buildActivityQuery(context, ActivityType.UPCOMING, isOnlyUnwatched, -1); return context.getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, ActivityFragment.ActivityQuery.PROJECTION, args[0][0], args[1], args[2][0]); }
/** * Returns all episodes that air today or later. Using Pacific Time to determine today. Excludes * shows that are hidden. * * @return Cursor using the projection of {@link com.battlelancer.seriesguide.ui.ActivityFragment.ActivityQuery}. */
Returns all episodes that air today or later. Using Pacific Time to determine today. Excludes shows that are hidden
getUpcomingEpisodes
{ "repo_name": "fr0609/SeriesGuide", "path": "SeriesGuide/src/main/java/com/battlelancer/seriesguide/util/DBUtils.java", "license": "apache-2.0", "size": 33982 }
[ "android.content.Context", "android.database.Cursor", "com.battlelancer.seriesguide.provider.SeriesGuideContract", "com.battlelancer.seriesguide.ui.ActivityFragment" ]
import android.content.Context; import android.database.Cursor; import com.battlelancer.seriesguide.provider.SeriesGuideContract; import com.battlelancer.seriesguide.ui.ActivityFragment;
import android.content.*; import android.database.*; import com.battlelancer.seriesguide.provider.*; import com.battlelancer.seriesguide.ui.*;
[ "android.content", "android.database", "com.battlelancer.seriesguide" ]
android.content; android.database; com.battlelancer.seriesguide;
121,970
public static String getChildText(Node node) { // is there anything to do? if (node == null) { return null; } // concatenate children text StringBuffer str = new StringBuffer(); Node child = node.getFirstChild(); while (child != null) { short type = child.getNodeType(); if (type == Node.TEXT_NODE) { str.append(child.getNodeValue()); } else if (type == Node.CDATA_SECTION_NODE) { str.append(getChildText(child)); } child = child.getNextSibling(); } // return text value return str.toString(); } // getChildText(Node):String
static String function(Node node) { if (node == null) { return null; } StringBuffer str = new StringBuffer(); Node child = node.getFirstChild(); while (child != null) { short type = child.getNodeType(); if (type == Node.TEXT_NODE) { str.append(child.getNodeValue()); } else if (type == Node.CDATA_SECTION_NODE) { str.append(getChildText(child)); } child = child.getNextSibling(); } return str.toString(); }
/** * Returns the concatenated child text of the specified node. * This method only looks at the immediate children of type * <code>Node.TEXT_NODE</code> or the children of any child * node that is of type <code>Node.CDATA_SECTION_NODE</code> * for the concatenation. * * @param node The node to look at. */
Returns the concatenated child text of the specified node. This method only looks at the immediate children of type <code>Node.TEXT_NODE</code> or the children of any child node that is of type <code>Node.CDATA_SECTION_NODE</code> for the concatenation
getChildText
{ "repo_name": "lostdj/Jaklin-OpenJDK-JAXP", "path": "src/java.xml/share/classes/com/sun/org/apache/xerces/internal/util/DOMUtil.java", "license": "gpl-2.0", "size": 31144 }
[ "org.w3c.dom.Node" ]
import org.w3c.dom.Node;
import org.w3c.dom.*;
[ "org.w3c.dom" ]
org.w3c.dom;
10,615
protected void tearDown() throws Exception { FileUtilities.killDirectory(m_TestRoot); }
void function() throws Exception { FileUtilities.killDirectory(m_TestRoot); }
/** * Tears down the fixture, for example, close a network connection. This * method is called after a test is executed. */
Tears down the fixture, for example, close a network connection. This method is called after a test is executed
tearDown
{ "repo_name": "janekdb/ntropa", "path": "presentation/wps/src/tests/org/ntropa/build/mapper/LinkFileTest.java", "license": "apache-2.0", "size": 3413 }
[ "org.ntropa.utility.FileUtilities" ]
import org.ntropa.utility.FileUtilities;
import org.ntropa.utility.*;
[ "org.ntropa.utility" ]
org.ntropa.utility;
2,511,537
PcepLspaObject build() throws PcepParseException;
PcepLspaObject build() throws PcepParseException;
/** * Builds LSPA Object. * * @return LSPA Object * @throws PcepParseException while building LSPA object. */
Builds LSPA Object
build
{ "repo_name": "maheshraju-Huawei/actn", "path": "apps/pcep-api/src/main/java/org/onosproject/pcep/pcepio/protocol/PcepLspaObject.java", "license": "apache-2.0", "size": 7719 }
[ "org.onosproject.pcep.pcepio.exceptions.PcepParseException" ]
import org.onosproject.pcep.pcepio.exceptions.PcepParseException;
import org.onosproject.pcep.pcepio.exceptions.*;
[ "org.onosproject.pcep" ]
org.onosproject.pcep;
814,453
public ClusterServer findServer(int index) { for (ClusterServer server : getServerList()) { if (server != null && server.getIndex() == index) return server; } return null; } // // configuration //
ClusterServer function(int index) { for (ClusterServer server : getServerList()) { if (server != null && server.getIndex() == index) return server; } return null; } //
/** * Finds the matching server. */
Finds the matching server
findServer
{ "repo_name": "mdaniel/svn-caucho-com-resin", "path": "modules/resin/src/com/caucho/server/cluster/ClusterPod.java", "license": "gpl-2.0", "size": 12392 }
[ "com.caucho.cloud.network.ClusterServer" ]
import com.caucho.cloud.network.ClusterServer;
import com.caucho.cloud.network.*;
[ "com.caucho.cloud" ]
com.caucho.cloud;
22,715
public static TransverseMercator latLongToTransverseMercator(LatLong latLong) { CoordinatesConverter<LatLong, TransverseMercator> latLongToTM = LatLong.CRS.getConverterTo(DEFAULT_CRS); return latLongToTM.convert(latLong); }
static TransverseMercator function(LatLong latLong) { CoordinatesConverter<LatLong, TransverseMercator> latLongToTM = LatLong.CRS.getConverterTo(DEFAULT_CRS); return latLongToTM.convert(latLong); }
/** * Convenience method that converts geodetic (LatLong) coordinates to * Transverse Mercator projection according to current ellipsoid and default * Transverse Mercator projection parameters. * * @param latLong * @return */
Convenience method that converts geodetic (LatLong) coordinates to Transverse Mercator projection according to current ellipsoid and default Transverse Mercator projection parameters
latLongToTransverseMercator
{ "repo_name": "GEOINT/jeotrans", "path": "src/main/java/org/geoint/jeotrans/coordinate/TransverseMercator.java", "license": "mit", "size": 11464 }
[ "org.jscience.geography.coordinates.LatLong", "org.jscience.geography.coordinates.crs.CoordinatesConverter" ]
import org.jscience.geography.coordinates.LatLong; import org.jscience.geography.coordinates.crs.CoordinatesConverter;
import org.jscience.geography.coordinates.*; import org.jscience.geography.coordinates.crs.*;
[ "org.jscience.geography" ]
org.jscience.geography;
1,533,534