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
public static ims.clinical.domain.objects.MDTMeeting extractMDTMeeting(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.MDTMeetingVo valueObject) { return extractMDTMeeting(domainFactory, valueObject, new HashMap()); }
static ims.clinical.domain.objects.MDTMeeting function(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.MDTMeetingVo valueObject) { return extractMDTMeeting(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
extractMDTMeeting
{ "repo_name": "open-health-hub/openmaxims-linux", "path": "openmaxims_workspace/ValueObjects/src/ims/clinical/vo/domain/MDTMeetingVoAssembler.java", "license": "agpl-3.0", "size": 19472 }
[ "java.util.HashMap" ]
import java.util.HashMap;
import java.util.*;
[ "java.util" ]
java.util;
1,459,150
protected IndexColorModel createIndexColorModelWithTransparency() { int[] cmap = new int[256]; // First color is transparent. cmap[0] = 0; // Create a 6x6x6 color cube. int i = 1; for (int r = 0; r < 256; r += 51) { for (int g = 0; g < 256; g += 51) { for (int b = 0; b < 256; b += 51) { cmap[i++] = (r << 16) | (g << 8) | b; } } } // Populate the rest of the cmap with gray values. int grayIncr = 256 / (256 - i); // Gray ramp will be between 18 and 246. int gray = grayIncr * 3; for (; i < 256; i++) { cmap[i] = (gray << 16) | (gray << 8) | gray; gray += grayIncr; } return new IndexColorModel(8, 256, cmap, 0, true, 0, DataBuffer.TYPE_BYTE); }
IndexColorModel function() { int[] cmap = new int[256]; cmap[0] = 0; int i = 1; for (int r = 0; r < 256; r += 51) { for (int g = 0; g < 256; g += 51) { for (int b = 0; b < 256; b += 51) { cmap[i++] = (r << 16) (g << 8) b; } } } int grayIncr = 256 / (256 - i); int gray = grayIncr * 3; for (; i < 256; i++) { cmap[i] = (gray << 16) (gray << 8) gray; gray += grayIncr; } return new IndexColorModel(8, 256, cmap, 0, true, 0, DataBuffer.TYPE_BYTE); }
/** * Creates an index color model for gif images that supports transparency. * This method does exactly what BufferedImage does when TYPE_BYTE_INDEXED * type is specified, except the first color is transparent and the gray * ramp is between 18 and 246. * * @return an instance of index color model. */
Creates an index color model for gif images that supports transparency. This method does exactly what BufferedImage does when TYPE_BYTE_INDEXED type is specified, except the first color is transparent and the gray ramp is between 18 and 246
createIndexColorModelWithTransparency
{ "repo_name": "mbykovskyy/spritey", "path": "spritey.core/src/spritey/core/io/ImageWriter.java", "license": "gpl-3.0", "size": 5426 }
[ "java.awt.image.DataBuffer", "java.awt.image.IndexColorModel" ]
import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel;
import java.awt.image.*;
[ "java.awt" ]
java.awt;
126,484
public static <T> ArrayList<T> alist(Iterable<T> vals) { ArrayList<T> ret = new ArrayList<>(); for (T v : vals) ret.add(v); return ret; }
static <T> ArrayList<T> function(Iterable<T> vals) { ArrayList<T> ret = new ArrayList<>(); for (T v : vals) ret.add(v); return ret; }
/** * Creates a new {@link ArrayList} with the inferred type * using the given elements. */
Creates a new <code>ArrayList</code> with the inferred type using the given elements
alist
{ "repo_name": "Xenoage/Zong", "path": "utils/utils-base/src/com/xenoage/utils/collections/CollectionUtils.java", "license": "agpl-3.0", "size": 8145 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
1,713,301
public List<Service> getServices() { return m_services; }
List<Service> function() { return m_services; }
/** * Return the services * * @return Services to be set. */
Return the services
getServices
{ "repo_name": "tharindum/opennms_dashboard", "path": "features/reporting/availability/src/main/java/org/opennms/reporting/datablock/Interface.java", "license": "gpl-2.0", "size": 10885 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,305,072
public String getDisplayName() { String s = this.getItem().getItemStackDisplayName(this); if (this.stackTagCompound != null && this.stackTagCompound.hasKey("display", 10)) { NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); if (nbttagcompound.hasKey("Name", 8)) { s = nbttagcompound.getString("Name"); } } return s; }
String function() { String s = this.getItem().getItemStackDisplayName(this); if (this.stackTagCompound != null && this.stackTagCompound.hasKey(STR, 10)) { NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag(STR); if (nbttagcompound.hasKey("Name", 8)) { s = nbttagcompound.getString("Name"); } } return s; }
/** * returns the display name of the itemstack */
returns the display name of the itemstack
getDisplayName
{ "repo_name": "boredherobrine13/morefuelsmod-1.10", "path": "build/tmp/recompileMc/sources/net/minecraft/item/ItemStack.java", "license": "lgpl-2.1", "size": 40541 }
[ "net.minecraft.nbt.NBTTagCompound" ]
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.*;
[ "net.minecraft.nbt" ]
net.minecraft.nbt;
1,699,952
@Override public float[] getRainfall(float[] par1ArrayOfFloat, int par2, int par3, int par4, int par5) { if (par1ArrayOfFloat == null || par1ArrayOfFloat.length < par4 * par5) par1ArrayOfFloat = new float[par4 * par5]; Arrays.fill(par1ArrayOfFloat, 0, par4 * par5, this.rainfall); return par1ArrayOfFloat; }
float[] function(float[] par1ArrayOfFloat, int par2, int par3, int par4, int par5) { if (par1ArrayOfFloat == null par1ArrayOfFloat.length < par4 * par5) par1ArrayOfFloat = new float[par4 * par5]; Arrays.fill(par1ArrayOfFloat, 0, par4 * par5, this.rainfall); return par1ArrayOfFloat; }
/** * Returns a list of rainfall values for the specified blocks. Args: listToReuse, x, z, width, length. */
Returns a list of rainfall values for the specified blocks. Args: listToReuse, x, z, width, length
getRainfall
{ "repo_name": "bsun0000/TerraFirmaCraft", "path": "src/Common/com/bioxx/tfc/WorldGen/TFCWorldChunkManagerHell.java", "license": "gpl-3.0", "size": 3666 }
[ "java.util.Arrays" ]
import java.util.Arrays;
import java.util.*;
[ "java.util" ]
java.util;
976,595
public static InputSource getInputSourceFromFilename(String filename) { final File inputFile = new File(filename); return getInputSourceFromFilename(inputFile); }
static InputSource function(String filename) { final File inputFile = new File(filename); return getInputSourceFromFilename(inputFile); }
/** * Gets the inputsource from filename. * * @param filename * the filename * @return the input */
Gets the inputsource from filename
getInputSourceFromFilename
{ "repo_name": "popikyardo/movsim-extended", "path": "common/src/main/java/org/movsim/utilities/FileUtils.java", "license": "gpl-3.0", "size": 12404 }
[ "java.io.File", "org.xml.sax.InputSource" ]
import java.io.File; import org.xml.sax.InputSource;
import java.io.*; import org.xml.sax.*;
[ "java.io", "org.xml.sax" ]
java.io; org.xml.sax;
380,592
@Test(expectedExceptions = IllegalStateException.class) public void testEndOfMonthConventionIsSet() { VanillaOisGenerator.builder() .withBusinessDayConvention(BDC) .withCalendar(CALENDAR) .withPaymentLag(PAYMENT_LAG) .withPaymentTenor(PAYMENT_TENOR) .withSpotLag(SPOT_LAG) .withStubType(STUB_TYPE) .withUnderlyingIndex(INDEX) .build(); }
@Test(expectedExceptions = IllegalStateException.class) void function() { VanillaOisGenerator.builder() .withBusinessDayConvention(BDC) .withCalendar(CALENDAR) .withPaymentLag(PAYMENT_LAG) .withPaymentTenor(PAYMENT_TENOR) .withSpotLag(SPOT_LAG) .withStubType(STUB_TYPE) .withUnderlyingIndex(INDEX) .build(); }
/** * Tests that the end of month convention must be set. */
Tests that the end of month convention must be set
testEndOfMonthConventionIsSet
{ "repo_name": "McLeodMoores/starling", "path": "projects/analytics/src/test/java/com/mcleodmoores/analytics/financial/generator/interestrate/VanillaOisGeneratorTest.java", "license": "apache-2.0", "size": 17799 }
[ "com.mcleodmoores.analytics.financial.generator.interestrate.VanillaOisGenerator", "org.testng.annotations.Test" ]
import com.mcleodmoores.analytics.financial.generator.interestrate.VanillaOisGenerator; import org.testng.annotations.Test;
import com.mcleodmoores.analytics.financial.generator.interestrate.*; import org.testng.annotations.*;
[ "com.mcleodmoores.analytics", "org.testng.annotations" ]
com.mcleodmoores.analytics; org.testng.annotations;
1,904,554
public Logger getLogger() { return logger; }
Logger function() { return logger; }
/** * Returns the common (thread-safe) logger. * * @return A log4j logger. Never null. */
Returns the common (thread-safe) logger
getLogger
{ "repo_name": "titokone/titotrainer", "path": "WEB-INF/src/fi/helsinki/cs/titotrainer/framework/RequestContext.java", "license": "gpl-2.0", "size": 1848 }
[ "org.apache.log4j.Logger" ]
import org.apache.log4j.Logger;
import org.apache.log4j.*;
[ "org.apache.log4j" ]
org.apache.log4j;
1,332,102
Map<String, String> getKEKMaterialsDescription() { return this.kekMaterialsDescription; }
Map<String, String> getKEKMaterialsDescription() { return this.kekMaterialsDescription; }
/** * Returns the description of the kek materials that were used to encrypt * the cek. */
Returns the description of the kek materials that were used to encrypt the cek
getKEKMaterialsDescription
{ "repo_name": "sheofir/aws-sdk-java", "path": "aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/ContentCryptoMaterial.java", "license": "apache-2.0", "size": 37877 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,563,104
@Test void autoRenewSessionLockErrorEmptyString() { // Arrange final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String sessionId = ""; when(managementNode.renewSessionLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); // Act & Assert StepVerifier.create(sessionReceiver.renewSessionLock(sessionId, maxDuration)) .expectError(IllegalArgumentException.class) .verify(); verify(managementNode, never()).renewSessionLock(anyString(), isNull()); }
void autoRenewSessionLockErrorEmptyString() { final Duration maxDuration = Duration.ofSeconds(8); final Duration renewalPeriod = Duration.ofSeconds(3); final String sessionId = ""; when(managementNode.renewSessionLock(anyString(), isNull())) .thenReturn(Mono.fromCallable(() -> OffsetDateTime.now().plus(renewalPeriod))); StepVerifier.create(sessionReceiver.renewSessionLock(sessionId, maxDuration)) .expectError(IllegalArgumentException.class) .verify(); verify(managementNode, never()).renewSessionLock(anyString(), isNull()); }
/** * Verifies that it errors when we try an empty string session id */
Verifies that it errors when we try an empty string session id
autoRenewSessionLockErrorEmptyString
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusReceiverAsyncClientTest.java", "license": "mit", "size": 54277 }
[ "java.time.Duration", "java.time.OffsetDateTime", "org.mockito.ArgumentMatchers", "org.mockito.Mockito" ]
import java.time.Duration; import java.time.OffsetDateTime; import org.mockito.ArgumentMatchers; import org.mockito.Mockito;
import java.time.*; import org.mockito.*;
[ "java.time", "org.mockito" ]
java.time; org.mockito;
183,208
public void delete(com.floreantpos.model.VoidTransaction voidTransaction, Session s) throws org.hibernate.HibernateException { delete((Object) voidTransaction, s); }
void function(com.floreantpos.model.VoidTransaction voidTransaction, Session s) throws org.hibernate.HibernateException { delete((Object) voidTransaction, s); }
/** * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving * Session or a transient instance with an identifier associated with existing persistent state. * Use the Session given. * @param voidTransaction the instance to be removed * @param s the Session */
Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state. Use the Session given
delete
{ "repo_name": "meyerdg/floreant", "path": "src/com/floreantpos/model/dao/BaseVoidTransactionDAO.java", "license": "gpl-2.0", "size": 8529 }
[ "org.hibernate.Session" ]
import org.hibernate.Session;
import org.hibernate.*;
[ "org.hibernate" ]
org.hibernate;
280,653
List<TableMetaData> actualTableMetaDataList = load(getDataNodeGroups(logicTableName, shardingRule), shardingRule.getShardingDataSourceNames()); checkUniformed(logicTableName, actualTableMetaDataList); return actualTableMetaDataList.iterator().next(); }
List<TableMetaData> actualTableMetaDataList = load(getDataNodeGroups(logicTableName, shardingRule), shardingRule.getShardingDataSourceNames()); checkUniformed(logicTableName, actualTableMetaDataList); return actualTableMetaDataList.iterator().next(); }
/** * Load table meta data. * * @param logicTableName logic table name * @param shardingRule sharding rule * @return table meta data * @throws SQLException SQL exception */
Load table meta data
load
{ "repo_name": "dangdangdotcom/sharding-jdbc", "path": "sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java", "license": "apache-2.0", "size": 7866 }
[ "io.shardingsphere.core.metadata.table.TableMetaData", "java.util.List" ]
import io.shardingsphere.core.metadata.table.TableMetaData; import java.util.List;
import io.shardingsphere.core.metadata.table.*; import java.util.*;
[ "io.shardingsphere.core", "java.util" ]
io.shardingsphere.core; java.util;
141,601
public static Test suite() { final TestSuite suite = new TestSuite("bop utils"); // counting variables, etc. suite.addTestSuite(TestBOpUtility.class); // unit tests for shared variables. suite.addTestSuite(TestBOpUtility_sharedVariables.class); return suite; }
static Test function() { final TestSuite suite = new TestSuite(STR); suite.addTestSuite(TestBOpUtility.class); suite.addTestSuite(TestBOpUtility_sharedVariables.class); return suite; }
/** * Returns a test that will run each of the implementation specific test * suites in turn. */
Returns a test that will run each of the implementation specific test suites in turn
suite
{ "repo_name": "smalyshev/blazegraph", "path": "bigdata/src/test/com/bigdata/bop/util/TestAll.java", "license": "gpl-2.0", "size": 2001 }
[ "junit.framework.Test", "junit.framework.TestSuite" ]
import junit.framework.Test; import junit.framework.TestSuite;
import junit.framework.*;
[ "junit.framework" ]
junit.framework;
1,712,060
@Test(dataProvider = "privilege elevation test cases") public void testAdminEditsAdminPrivilegesViaUpdate(boolean isHasSudo, boolean isGrantsSudo, boolean isEditsAdmin) throws Exception { final boolean isExpectSuccess = isHasSudo || !isGrantsSudo || !isEditsAdmin; final EventContext actor = loginNewAdmin(true, isHasSudo ? null : AdminPrivilegeSudo.value); Experimenter newUser = createExperimenterI(UUID.randomUUID().toString(), getClass().getSimpleName(), "Test"); final long newUserId; if (isEditsAdmin) { newUserId = iAdmin.createRestrictedSystemUser(newUser, Collections.<AdminPrivilege>emptyList()); } else { final String groupName = newUserAndGroup("rwr---", false).groupName; loginUser(actor); newUserId = iAdmin.createUser(newUser, groupName); } newUser = (Experimenter) iQuery.get("Experimenter", newUserId); final String sudoConfigName = AdminPrivilege.class.getSimpleName() + ':' + AdminPrivilegeSudo.value; if (isGrantsSudo) { newUser.setConfig(Collections.singletonList(new NamedValue(sudoConfigName, Boolean.toString(true)))); } try { iUpdate.saveObject(newUser); Assert.assertTrue(isExpectSuccess); boolean newUserHasSudo = false; for (final AdminPrivilege privilege : iAdmin.getAdminPrivileges(new ExperimenterI(newUserId, false))) { if (AdminPrivilegeSudo.value.equals(privilege.getValue().getValue())) { newUserHasSudo = true; break; } } Assert.assertEquals(newUserHasSudo, isGrantsSudo && isEditsAdmin); } catch (ServerError se) { Assert.assertFalse(isExpectSuccess); } }
@Test(dataProvider = STR) void function(boolean isHasSudo, boolean isGrantsSudo, boolean isEditsAdmin) throws Exception { final boolean isExpectSuccess = isHasSudo !isGrantsSudo !isEditsAdmin; final EventContext actor = loginNewAdmin(true, isHasSudo ? null : AdminPrivilegeSudo.value); Experimenter newUser = createExperimenterI(UUID.randomUUID().toString(), getClass().getSimpleName(), "Test"); final long newUserId; if (isEditsAdmin) { newUserId = iAdmin.createRestrictedSystemUser(newUser, Collections.<AdminPrivilege>emptyList()); } else { final String groupName = newUserAndGroup(STR, false).groupName; loginUser(actor); newUserId = iAdmin.createUser(newUser, groupName); } newUser = (Experimenter) iQuery.get(STR, newUserId); final String sudoConfigName = AdminPrivilege.class.getSimpleName() + ':' + AdminPrivilegeSudo.value; if (isGrantsSudo) { newUser.setConfig(Collections.singletonList(new NamedValue(sudoConfigName, Boolean.toString(true)))); } try { iUpdate.saveObject(newUser); Assert.assertTrue(isExpectSuccess); boolean newUserHasSudo = false; for (final AdminPrivilege privilege : iAdmin.getAdminPrivileges(new ExperimenterI(newUserId, false))) { if (AdminPrivilegeSudo.value.equals(privilege.getValue().getValue())) { newUserHasSudo = true; break; } } Assert.assertEquals(newUserHasSudo, isGrantsSudo && isEditsAdmin); } catch (ServerError se) { Assert.assertFalse(isExpectSuccess); } }
/** * Test that administrators may give users only privileges that they themselves have. * Attempts editing privileges via {@link omero.api.IUpdatePrx}. * @param isHasSudo if the administrator has the <tt>Sudo</tt> privilege * @param isGrantsSudo if the target user should be given the <tt>Sudo</tt> privilege * @param isEditsAdmin if the target user should be an administrator * @throws Exception unexpected */
Test that administrators may give users only privileges that they themselves have. Attempts editing privileges via <code>omero.api.IUpdatePrx</code>
testAdminEditsAdminPrivilegesViaUpdate
{ "repo_name": "MontpellierRessourcesImagerie/openmicroscopy", "path": "components/tools/OmeroJava/test/integration/LightAdminPrivilegesTest.java", "license": "gpl-2.0", "size": 169987 }
[ "java.util.Collections", "java.util.UUID", "org.testng.Assert", "org.testng.annotations.Test" ]
import java.util.Collections; import java.util.UUID; import org.testng.Assert; import org.testng.annotations.Test;
import java.util.*; import org.testng.*; import org.testng.annotations.*;
[ "java.util", "org.testng", "org.testng.annotations" ]
java.util; org.testng; org.testng.annotations;
2,448,277
public void setAddResponseHeaderOnSeverity(ResultSeverityEnum theSeverity) { myAddResponseIssueHeaderOnSeverity = theSeverity != null ? theSeverity.ordinal() : null; }
void function(ResultSeverityEnum theSeverity) { myAddResponseIssueHeaderOnSeverity = theSeverity != null ? theSeverity.ordinal() : null; }
/** * Sets the minimum severity at which an issue detected by the validator will result in a header being added to the * response. Default is {@link ResultSeverityEnum#INFORMATION}. Set to <code>null</code> to disable this behaviour. * * @see #setResponseHeaderName(String) * @see #setResponseHeaderValue(String) */
Sets the minimum severity at which an issue detected by the validator will result in a header being added to the response. Default is <code>ResultSeverityEnum#INFORMATION</code>. Set to <code>null</code> to disable this behaviour
setAddResponseHeaderOnSeverity
{ "repo_name": "botunge/hapi-fhir", "path": "hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/BaseValidatingInterceptor.java", "license": "apache-2.0", "size": 13932 }
[ "ca.uhn.fhir.validation.ResultSeverityEnum" ]
import ca.uhn.fhir.validation.ResultSeverityEnum;
import ca.uhn.fhir.validation.*;
[ "ca.uhn.fhir" ]
ca.uhn.fhir;
1,011,844
@Test public void testAdHocData() { FastSineTransformer transformer; transformer = new FastSineTransformer(DstNormalization.STANDARD_DST_I); double result[], tolerance = 1E-12; double x[] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; double y[] = { 0.0, 20.1093579685034, -9.65685424949238, 5.98642305066196, -4.0, 2.67271455167720, -1.65685424949238, 0.795649469518633 }; result = transformer.transform(x, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i], result[i], tolerance); } result = transformer.transform(y, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i], tolerance); } TransformUtils.scaleArray(x, FastMath.sqrt(x.length / 2.0)); transformer = new FastSineTransformer(DstNormalization.ORTHOGONAL_DST_I); result = transformer.transform(y, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i], tolerance); } result = transformer.transform(x, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i], result[i], tolerance); } }
void function() { FastSineTransformer transformer; transformer = new FastSineTransformer(DstNormalization.STANDARD_DST_I); double result[], tolerance = 1E-12; double x[] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; double y[] = { 0.0, 20.1093579685034, -9.65685424949238, 5.98642305066196, -4.0, 2.67271455167720, -1.65685424949238, 0.795649469518633 }; result = transformer.transform(x, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i], result[i], tolerance); } result = transformer.transform(y, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i], tolerance); } TransformUtils.scaleArray(x, FastMath.sqrt(x.length / 2.0)); transformer = new FastSineTransformer(DstNormalization.ORTHOGONAL_DST_I); result = transformer.transform(y, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i], tolerance); } result = transformer.transform(x, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i], result[i], tolerance); } }
/** * Test of transformer for the ad hoc data. */
Test of transformer for the ad hoc data
testAdHocData
{ "repo_name": "tknandu/CommonsMath_Modifed", "path": "math (trunk)/src/test/java/org/apache/commons/math3/transform/FastSineTransformerTest.java", "license": "apache-2.0", "size": 9977 }
[ "org.apache.commons.math3.util.FastMath", "org.junit.Assert" ]
import org.apache.commons.math3.util.FastMath; import org.junit.Assert;
import org.apache.commons.math3.util.*; import org.junit.*;
[ "org.apache.commons", "org.junit" ]
org.apache.commons; org.junit;
2,226,741
private void incrNextAddressMask() { BigInteger tmpMask = incrAddressMask(nextAddressMask, BigInteger.ONE); if(tmpMask.compareTo(lastAddressMask) > 0) { throw new IllegalStateException("New address not in address range of this network"); } nextAddressMask = tmpMask; }
void function() { BigInteger tmpMask = incrAddressMask(nextAddressMask, BigInteger.ONE); if(tmpMask.compareTo(lastAddressMask) > 0) { throw new IllegalStateException(STR); } nextAddressMask = tmpMask; }
/** * Increment the next free address pointer by 1. If the pointer leaves the * address range of this network an exception will be thrown. * * @throws IllegalStateException if the pointer leaves the address range of * this network */
Increment the next free address pointer by 1. If the pointer leaves the address range of this network an exception will be thrown
incrNextAddressMask
{ "repo_name": "decoit/Visa-Topologie-Editor", "path": "backend/src/de/decoit/visa/net/IPNetwork.java", "license": "gpl-3.0", "size": 7814 }
[ "java.math.BigInteger" ]
import java.math.BigInteger;
import java.math.*;
[ "java.math" ]
java.math;
2,076,194
private static boolean isWatchApplicationNode(TargetNode<?> targetNode) { if (targetNode.getDescription() instanceof AppleBundleDescription) { AppleBundleDescriptionArg arg = (AppleBundleDescriptionArg) targetNode.getConstructorArg(); return arg.getXcodeProductType() .equals(Optional.of(ProductTypes.WATCH_APPLICATION.getIdentifier())); } return false; }
static boolean function(TargetNode<?> targetNode) { if (targetNode.getDescription() instanceof AppleBundleDescription) { AppleBundleDescriptionArg arg = (AppleBundleDescriptionArg) targetNode.getConstructorArg(); return arg.getXcodeProductType() .equals(Optional.of(ProductTypes.WATCH_APPLICATION.getIdentifier())); } return false; }
/** * Determines if a target node is for watchOS2 application * * @param targetNode A target node * @return If the given target node is for an watchOS2 application */
Determines if a target node is for watchOS2 application
isWatchApplicationNode
{ "repo_name": "SeleniumHQ/buck", "path": "src/com/facebook/buck/features/apple/project/ProjectGenerator.java", "license": "apache-2.0", "size": 216000 }
[ "com.facebook.buck.apple.AppleBundleDescription", "com.facebook.buck.apple.AppleBundleDescriptionArg", "com.facebook.buck.apple.xcode.xcodeproj.ProductTypes", "com.facebook.buck.core.model.targetgraph.TargetNode", "java.util.Optional" ]
import com.facebook.buck.apple.AppleBundleDescription; import com.facebook.buck.apple.AppleBundleDescriptionArg; import com.facebook.buck.apple.xcode.xcodeproj.ProductTypes; import com.facebook.buck.core.model.targetgraph.TargetNode; import java.util.Optional;
import com.facebook.buck.apple.*; import com.facebook.buck.apple.xcode.xcodeproj.*; import com.facebook.buck.core.model.targetgraph.*; import java.util.*;
[ "com.facebook.buck", "java.util" ]
com.facebook.buck; java.util;
1,309,309
public static void addMetadata(final HttpURLConnection request, final HashMap<String, String> metadata, final OperationContext opContext) { BaseRequest.addMetadata(request, metadata, opContext); }
static void function(final HttpURLConnection request, final HashMap<String, String> metadata, final OperationContext opContext) { BaseRequest.addMetadata(request, metadata, opContext); }
/** * Adds user-defined metadata to the web request as one or more name-value * pairs. * * @param request * The <code>HttpURLConnection</code> web request to add the * metadata to. * @param metadata * A <code>HashMap</code> containing the user-defined metadata to * add. * @param opContext * An {@link OperationContext} object that represents the context * for the current operation. This object is used to track * requests to the storage service, and to provide additional * runtime information about the operation. */
Adds user-defined metadata to the web request as one or more name-value pairs
addMetadata
{ "repo_name": "horizon-institute/runspotrun-android-client", "path": "src/com/microsoft/azure/storage/queue/QueueRequest.java", "license": "agpl-3.0", "size": 29973 }
[ "com.microsoft.azure.storage.OperationContext", "com.microsoft.azure.storage.core.BaseRequest", "java.net.HttpURLConnection", "java.util.HashMap" ]
import com.microsoft.azure.storage.OperationContext; import com.microsoft.azure.storage.core.BaseRequest; import java.net.HttpURLConnection; import java.util.HashMap;
import com.microsoft.azure.storage.*; import com.microsoft.azure.storage.core.*; import java.net.*; import java.util.*;
[ "com.microsoft.azure", "java.net", "java.util" ]
com.microsoft.azure; java.net; java.util;
639,619
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException { Provider[] provs = Security.getProviders(); for (int i = 0; i < provs.length; i++) { try { return getInstance(algorithm, provs[i]); } catch (NoSuchAlgorithmException nsae) { } } throw new NoSuchAlgorithmException(algorithm); }
static final SecretKeyFactory function(String algorithm) throws NoSuchAlgorithmException { Provider[] provs = Security.getProviders(); for (int i = 0; i < provs.length; i++) { try { return getInstance(algorithm, provs[i]); } catch (NoSuchAlgorithmException nsae) { } } throw new NoSuchAlgorithmException(algorithm); }
/** * Create a new secret key factory from the first appropriate * instance. * * @param algorithm The algorithm name. * @return The appropriate key factory, if found. * @throws java.security.NoSuchAlgorithmException If no provider * implements the specified algorithm. */
Create a new secret key factory from the first appropriate instance
getInstance
{ "repo_name": "aosm/gcc_40", "path": "libjava/javax/crypto/SecretKeyFactory.java", "license": "gpl-2.0", "size": 7933 }
[ "java.security.NoSuchAlgorithmException", "java.security.Provider", "java.security.Security" ]
import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security;
import java.security.*;
[ "java.security" ]
java.security;
1,977,545
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); getSupportActionBar().setDisplayShowHomeEnabled(true); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); MapsInitializer.initialize(this); mGoogleApiClient.connect(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); if (mapFragment == null) { mapFragment = SupportMapFragment.newInstance(); getSupportFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit(); } map = mapFragment.getMap(); mAdapter = new PlaceAutoCompleteAdapter(this, android.R.layout.simple_list_item_1, mGoogleApiClient, BOUNDS_JAMAICA, null);
void function(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); getSupportActionBar().setDisplayShowHomeEnabled(true); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); MapsInitializer.initialize(this); mGoogleApiClient.connect(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); if (mapFragment == null) { mapFragment = SupportMapFragment.newInstance(); getSupportFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit(); } map = mapFragment.getMap(); mAdapter = new PlaceAutoCompleteAdapter(this, android.R.layout.simple_list_item_1, mGoogleApiClient, BOUNDS_JAMAICA, null);
/** * This activity loads a map and then displays the route and pushpins on it. */
This activity loads a map and then displays the route and pushpins on it
onCreate
{ "repo_name": "deepankarb/Google-Directions-Android", "path": "sample/src/main/java/com/directions/sample/MainActivity.java", "license": "mit", "size": 14657 }
[ "android.os.Bundle", "com.google.android.gms.common.api.GoogleApiClient", "com.google.android.gms.location.places.Places", "com.google.android.gms.maps.MapsInitializer", "com.google.android.gms.maps.SupportMapFragment" ]
import android.os.Bundle; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.SupportMapFragment;
import android.os.*; import com.google.android.gms.common.api.*; import com.google.android.gms.location.places.*; import com.google.android.gms.maps.*;
[ "android.os", "com.google.android" ]
android.os; com.google.android;
2,308,164
private void convertToDisplayData(Collection<TreeImageDisplay> treeNodes) { projects.clear(); datasets.clear(); screens.clear(); DataNode defaultProject = new DataNode(DataNode.createDefaultProject()); List<DataNode> orphanDatasets = new ArrayList<DataNode>(); List<DataNode> lp = new ArrayList<DataNode>(); List<DataNode> ls = new ArrayList<DataNode>(); if (treeNodes != null) { for (TreeImageDisplay treeNode : treeNodes) { Object userObject = treeNode.getUserObject(); if (userObject instanceof ProjectData) { DataNode project = new DataNode((ProjectData) userObject); lp.add(project); List<DataNode> projectDatasets = new ArrayList<DataNode>(); List children = treeNode.getChildrenDisplay(); TreeImageDisplay n; for (Object child : children) { n = (TreeImageDisplay) child; projectDatasets.add(new DataNode( (DatasetData) n.getUserObject())); } List<DataNode> list = new ArrayList<DataNode>(); list.add(new DataNode(DataNode.createDefaultDataset())); list.addAll(sort(projectDatasets)); datasets.put(project, list); } else if (userObject instanceof ScreenData) { DataNode screen = new DataNode((ScreenData) userObject); ls.add(screen); } else if(userObject instanceof DatasetData) { DataNode dataset = new DataNode((DatasetData) userObject); orphanDatasets.add(dataset); } } } List<DataNode> l = new ArrayList<DataNode>(); l.add(new DataNode(DataNode.createDefaultDataset())); l.add(new DataNode(DataNode.createNoDataset())); l.addAll(sort(orphanDatasets)); datasets.put(defaultProject, l); projects.add(defaultProject); projects.addAll(sort(lp)); screens.add(new DataNode(DataNode.createDefaultScreen())); screens.addAll(sort(ls)); }
void function(Collection<TreeImageDisplay> treeNodes) { projects.clear(); datasets.clear(); screens.clear(); DataNode defaultProject = new DataNode(DataNode.createDefaultProject()); List<DataNode> orphanDatasets = new ArrayList<DataNode>(); List<DataNode> lp = new ArrayList<DataNode>(); List<DataNode> ls = new ArrayList<DataNode>(); if (treeNodes != null) { for (TreeImageDisplay treeNode : treeNodes) { Object userObject = treeNode.getUserObject(); if (userObject instanceof ProjectData) { DataNode project = new DataNode((ProjectData) userObject); lp.add(project); List<DataNode> projectDatasets = new ArrayList<DataNode>(); List children = treeNode.getChildrenDisplay(); TreeImageDisplay n; for (Object child : children) { n = (TreeImageDisplay) child; projectDatasets.add(new DataNode( (DatasetData) n.getUserObject())); } List<DataNode> list = new ArrayList<DataNode>(); list.add(new DataNode(DataNode.createDefaultDataset())); list.addAll(sort(projectDatasets)); datasets.put(project, list); } else if (userObject instanceof ScreenData) { DataNode screen = new DataNode((ScreenData) userObject); ls.add(screen); } else if(userObject instanceof DatasetData) { DataNode dataset = new DataNode((DatasetData) userObject); orphanDatasets.add(dataset); } } } List<DataNode> l = new ArrayList<DataNode>(); l.add(new DataNode(DataNode.createDefaultDataset())); l.add(new DataNode(DataNode.createNoDataset())); l.addAll(sort(orphanDatasets)); datasets.put(defaultProject, l); projects.add(defaultProject); projects.addAll(sort(lp)); screens.add(new DataNode(DataNode.createDefaultScreen())); screens.addAll(sort(ls)); }
/** * Converts the treeNodes in to DataNdoes used to hold display data for the * location combo boxes. * @param treeNodes The nodes to convert for import target options. */
Converts the treeNodes in to DataNdoes used to hold display data for the location combo boxes
convertToDisplayData
{ "repo_name": "stelfrich/openmicroscopy", "path": "components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/chooser/LocationDialog.java", "license": "gpl-2.0", "size": 56281 }
[ "java.util.ArrayList", "java.util.Collection", "java.util.List", "org.openmicroscopy.shoola.agents.util.browser.DataNode", "org.openmicroscopy.shoola.agents.util.browser.TreeImageDisplay" ]
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.openmicroscopy.shoola.agents.util.browser.DataNode; import org.openmicroscopy.shoola.agents.util.browser.TreeImageDisplay;
import java.util.*; import org.openmicroscopy.shoola.agents.util.browser.*;
[ "java.util", "org.openmicroscopy.shoola" ]
java.util; org.openmicroscopy.shoola;
1,965,305
public static BigInteger[] encrypt(FHEParams fheparams, GHKeyGen key, int[] b) { int i, num = b.length; long n = 1<<(fheparams.logn); // the dimension double p = ((double)fheparams.noise)/n; // # of expected nonzero coefficients if (p>0.5) p = 0.5; // Evaluate all the polynomials together at root mod det BigInteger[] vals = evalRandPoly(num, n, p, key.root, key.det); BigInteger[] out = new BigInteger[num]; for (i = 0; i < num; i++) { out[i] = vals[i+1]; } // Set out[i] = 2*out[i] + b[i] for (i=0; i<num; i++) { out[i] = out[i].shiftLeft(1); out[i] = out[i].add(new BigInteger(Integer.toString(b[i]))); if (out[i].compareTo(key.det) >= 0) out[i] = out[i].subtract(key.det); } return out; }
static BigInteger[] function(FHEParams fheparams, GHKeyGen key, int[] b) { int i, num = b.length; long n = 1<<(fheparams.logn); double p = ((double)fheparams.noise)/n; if (p>0.5) p = 0.5; BigInteger[] vals = evalRandPoly(num, n, p, key.root, key.det); BigInteger[] out = new BigInteger[num]; for (i = 0; i < num; i++) { out[i] = vals[i+1]; } for (i=0; i<num; i++) { out[i] = out[i].shiftLeft(1); out[i] = out[i].add(new BigInteger(Integer.toString(b[i]))); if (out[i].compareTo(key.det) >= 0) out[i] = out[i].subtract(key.det); } return out; }
/** * Encrypts a bit array * @param fheparams the scheme parameters * @param key the key * @param b the bit array * @return An array containing the elementwise encryption of b */
Encrypts a bit array
encrypt
{ "repo_name": "jcryptool/crypto", "path": "org.jcryptool.visual.he/src/org/jcryptool/visual/he/algo/GHEncrypt.java", "license": "epl-1.0", "size": 8777 }
[ "java.math.BigInteger" ]
import java.math.BigInteger;
import java.math.*;
[ "java.math" ]
java.math;
657,468
@Override public W writeStateAddress(W window) { Set<W> stateAddressWindows = activeWindowToStateAddressWindows.get(window); checkState(stateAddressWindows != null, "Window %s is not ACTIVE", window); W result = Iterables.getFirst(stateAddressWindows, null); checkState(result != null, "Window %s is still NEW", window); return result; }
W function(W window) { Set<W> stateAddressWindows = activeWindowToStateAddressWindows.get(window); checkState(stateAddressWindows != null, STR, window); W result = Iterables.getFirst(stateAddressWindows, null); checkState(result != null, STR, window); return result; }
/** * Return the state address window of ACTIVE {@code window} into which all new state should be * written. */
Return the state address window of ACTIVE window into which all new state should be written
writeStateAddress
{ "repo_name": "joshualitt/incubator-beam", "path": "runners/core-java/src/main/java/org/apache/beam/runners/core/MergingActiveWindowSet.java", "license": "apache-2.0", "size": 15597 }
[ "com.google.common.base.Preconditions", "com.google.common.collect.Iterables", "java.util.Set" ]
import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.util.Set;
import com.google.common.base.*; import com.google.common.collect.*; import java.util.*;
[ "com.google.common", "java.util" ]
com.google.common; java.util;
1,315,769
public void testRepositorySettingsS3OverloadedByRepository() { Settings nodeSettings = buildSettings(AWS, S3); RepositorySettings repositorySettings = new RepositorySettings(nodeSettings, REPOSITORY); assertThat(getValue(repositorySettings, Repository.KEY_SETTING, Repositories.KEY_SETTING), is("repository-key")); assertThat(getValue(repositorySettings, Repository.SECRET_SETTING, Repositories.SECRET_SETTING), is("repository-secret")); assertThat(getValue(repositorySettings, Repository.BUCKET_SETTING, Repositories.BUCKET_SETTING), is("repository-bucket")); assertThat(getValue(repositorySettings, Repository.PROTOCOL_SETTING, Repositories.PROTOCOL_SETTING), is(Protocol.HTTPS)); assertThat(getValue(repositorySettings, Repository.REGION_SETTING, Repositories.REGION_SETTING), is("repository-region")); assertThat(getValue(repositorySettings, Repository.ENDPOINT_SETTING, Repositories.ENDPOINT_SETTING), is("repository-endpoint")); assertThat(AwsS3Service.CLOUD_S3.PROXY_HOST_SETTING.get(nodeSettings), is("s3-proxy-host")); assertThat(AwsS3Service.CLOUD_S3.PROXY_PORT_SETTING.get(nodeSettings), is(20000)); assertThat(AwsS3Service.CLOUD_S3.PROXY_USERNAME_SETTING.get(nodeSettings), is("s3-proxy-username")); assertThat(AwsS3Service.CLOUD_S3.PROXY_PASSWORD_SETTING.get(nodeSettings), is("s3-proxy-password")); assertThat(AwsS3Service.CLOUD_S3.SIGNER_SETTING.get(nodeSettings), is("s3-signer")); assertThat(getValue(repositorySettings, Repository.SERVER_SIDE_ENCRYPTION_SETTING, Repositories.SERVER_SIDE_ENCRYPTION_SETTING), is(false)); assertThat(getValue(repositorySettings, Repository.BUFFER_SIZE_SETTING, Repositories.BUFFER_SIZE_SETTING).getMb(), is(7L)); assertThat(getValue(repositorySettings, Repository.MAX_RETRIES_SETTING, Repositories.MAX_RETRIES_SETTING), is(5)); assertThat(getValue(repositorySettings, Repository.CHUNK_SIZE_SETTING, Repositories.CHUNK_SIZE_SETTING).getMb(), is(120L)); assertThat(getValue(repositorySettings, Repository.COMPRESS_SETTING, Repositories.COMPRESS_SETTING), is(false)); assertThat(getValue(repositorySettings, Repository.STORAGE_CLASS_SETTING, Repositories.STORAGE_CLASS_SETTING), is("repository-class")); assertThat(getValue(repositorySettings, Repository.CANNED_ACL_SETTING, Repositories.CANNED_ACL_SETTING), is("repository-acl")); assertThat(getValue(repositorySettings, Repository.BASE_PATH_SETTING, Repositories.BASE_PATH_SETTING), is("repository-basepath")); }
void function() { Settings nodeSettings = buildSettings(AWS, S3); RepositorySettings repositorySettings = new RepositorySettings(nodeSettings, REPOSITORY); assertThat(getValue(repositorySettings, Repository.KEY_SETTING, Repositories.KEY_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.SECRET_SETTING, Repositories.SECRET_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.BUCKET_SETTING, Repositories.BUCKET_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.PROTOCOL_SETTING, Repositories.PROTOCOL_SETTING), is(Protocol.HTTPS)); assertThat(getValue(repositorySettings, Repository.REGION_SETTING, Repositories.REGION_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.ENDPOINT_SETTING, Repositories.ENDPOINT_SETTING), is(STR)); assertThat(AwsS3Service.CLOUD_S3.PROXY_HOST_SETTING.get(nodeSettings), is(STR)); assertThat(AwsS3Service.CLOUD_S3.PROXY_PORT_SETTING.get(nodeSettings), is(20000)); assertThat(AwsS3Service.CLOUD_S3.PROXY_USERNAME_SETTING.get(nodeSettings), is(STR)); assertThat(AwsS3Service.CLOUD_S3.PROXY_PASSWORD_SETTING.get(nodeSettings), is(STR)); assertThat(AwsS3Service.CLOUD_S3.SIGNER_SETTING.get(nodeSettings), is(STR)); assertThat(getValue(repositorySettings, Repository.SERVER_SIDE_ENCRYPTION_SETTING, Repositories.SERVER_SIDE_ENCRYPTION_SETTING), is(false)); assertThat(getValue(repositorySettings, Repository.BUFFER_SIZE_SETTING, Repositories.BUFFER_SIZE_SETTING).getMb(), is(7L)); assertThat(getValue(repositorySettings, Repository.MAX_RETRIES_SETTING, Repositories.MAX_RETRIES_SETTING), is(5)); assertThat(getValue(repositorySettings, Repository.CHUNK_SIZE_SETTING, Repositories.CHUNK_SIZE_SETTING).getMb(), is(120L)); assertThat(getValue(repositorySettings, Repository.COMPRESS_SETTING, Repositories.COMPRESS_SETTING), is(false)); assertThat(getValue(repositorySettings, Repository.STORAGE_CLASS_SETTING, Repositories.STORAGE_CLASS_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.CANNED_ACL_SETTING, Repositories.CANNED_ACL_SETTING), is(STR)); assertThat(getValue(repositorySettings, Repository.BASE_PATH_SETTING, Repositories.BASE_PATH_SETTING), is(STR)); }
/** * We test when cloud.aws.s3 settings are overloaded by single repository settings */
We test when cloud.aws.s3 settings are overloaded by single repository settings
testRepositorySettingsS3OverloadedByRepository
{ "repo_name": "camilojd/elasticsearch", "path": "plugins/repository-s3/src/test/java/org/elasticsearch/cloud/aws/RepositoryS3SettingsTests.java", "license": "apache-2.0", "size": 27092 }
[ "com.amazonaws.Protocol", "org.elasticsearch.common.settings.Settings", "org.elasticsearch.repositories.RepositorySettings", "org.elasticsearch.repositories.s3.S3Repository", "org.hamcrest.Matchers" ]
import com.amazonaws.Protocol; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.repositories.RepositorySettings; import org.elasticsearch.repositories.s3.S3Repository; import org.hamcrest.Matchers;
import com.amazonaws.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.repositories.*; import org.elasticsearch.repositories.s3.*; import org.hamcrest.*;
[ "com.amazonaws", "org.elasticsearch.common", "org.elasticsearch.repositories", "org.hamcrest" ]
com.amazonaws; org.elasticsearch.common; org.elasticsearch.repositories; org.hamcrest;
2,524,819
public void error(Marker marker, String msg, Throwable t) { if (!logger.isErrorEnabled(marker)) return; if (instanceofLAL) { ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); } else { logger.error(marker, msg, t); } }
void function(Marker marker, String msg, Throwable t) { if (!logger.isErrorEnabled(marker)) return; if (instanceofLAL) { ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); } else { logger.error(marker, msg, t); } }
/** * Delegate to the appropriate method of the underlying logger. */
Delegate to the appropriate method of the underlying logger
error
{ "repo_name": "PRECISE/ROSLab", "path": "lib/slf4j-1.7.10/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java", "license": "apache-2.0", "size": 28131 }
[ "org.slf4j.Marker", "org.slf4j.spi.LocationAwareLogger" ]
import org.slf4j.Marker; import org.slf4j.spi.LocationAwareLogger;
import org.slf4j.*; import org.slf4j.spi.*;
[ "org.slf4j", "org.slf4j.spi" ]
org.slf4j; org.slf4j.spi;
719,054
@Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addBaseTableCatalogNamePropertyDescriptor(object); addBaseTableNamePropertyDescriptor(object); addBaseTableSchemaNamePropertyDescriptor(object); } return itemPropertyDescriptors; }
List<IItemPropertyDescriptor> function(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addBaseTableCatalogNamePropertyDescriptor(object); addBaseTableNamePropertyDescriptor(object); addBaseTableSchemaNamePropertyDescriptor(object); } return itemPropertyDescriptors; }
/** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This returns the property descriptors for the adapted class.
getPropertyDescriptors
{ "repo_name": "dzonekl/LiquibaseEditor", "path": "plugins/org.liquidbase.model.edit/src/org/liquibase/xml/ns/dbchangelog/provider/DropAllForeignKeyConstraintsTypeItemProvider.java", "license": "mit", "size": 7024 }
[ "java.util.List", "org.eclipse.emf.edit.provider.IItemPropertyDescriptor" ]
import java.util.List; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import java.util.*; import org.eclipse.emf.edit.provider.*;
[ "java.util", "org.eclipse.emf" ]
java.util; org.eclipse.emf;
196,940
@Nullable protected <T> IgniteInternalFuture<T> asyncOpAcquire(boolean retry) { try { if (!retry && asyncOpsSem != null) asyncOpsSem.acquire(); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new GridFinishedFuture<>(new IgniteInterruptedCheckedException("Failed to wait for asynchronous " + "operation permit (thread got interrupted).", e)); } }
@Nullable <T> IgniteInternalFuture<T> function(boolean retry) { try { if (!retry && asyncOpsSem != null) asyncOpsSem.acquire(); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new GridFinishedFuture<>(new IgniteInterruptedCheckedException(STR + STR, e)); } }
/** * Tries to acquire asynchronous operations permit, if limited. * * @param retry Retry flag. * @return Failed future if waiting was interrupted. */
Tries to acquire asynchronous operations permit, if limited
asyncOpAcquire
{ "repo_name": "ptupitsyn/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java", "license": "apache-2.0", "size": 228325 }
[ "org.apache.ignite.internal.IgniteInternalFuture", "org.apache.ignite.internal.IgniteInterruptedCheckedException", "org.apache.ignite.internal.util.future.GridFinishedFuture", "org.jetbrains.annotations.Nullable" ]
import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.jetbrains.annotations.Nullable;
import org.apache.ignite.internal.*; import org.apache.ignite.internal.util.future.*; import org.jetbrains.annotations.*;
[ "org.apache.ignite", "org.jetbrains.annotations" ]
org.apache.ignite; org.jetbrains.annotations;
2,146,041
@Test(timeout=60000) public void testJoinWithChangedTuple1() throws StorageManagerException, RejectedException { storageRegistry.deleteTable(TABLE_1); storageRegistry.createTable(TABLE_1, new TupleStoreConfiguration()); storageRegistry.deleteTable(TABLE_2); storageRegistry.createTable(TABLE_2, new TupleStoreConfiguration()); final TupleStoreManager storageManager1 = storageRegistry.getTupleStoreManager(TABLE_1); final TupleStoreManager storageManager2 = storageRegistry.getTupleStoreManager(TABLE_2); final Tuple tuple1 = new Tuple("1a", new Hyperrectangle(1.0, 2.0, 1.0, 2.0), "value1".getBytes()); final Tuple tuple2 = new Tuple("2a", new Hyperrectangle(4.0, 5.0, 4.0, 5.0), "value2".getBytes()); // Tuple 3 and tuple 4 have the same key final Tuple tuple3 = new Tuple("1b", new Hyperrectangle(1.5, 2.5, 1.5, 2.5), "value3".getBytes()); final Tuple tuple4 = new Tuple("1b", new Hyperrectangle(2.5, 5.5, 2.5, 5.5), "value4".getBytes()); // Table1 storageManager1.put(tuple1); storageManager1.put(tuple2); // Table2 storageManager2.put(tuple3); storageManager2.put(tuple4); final SpatialIndexReadOperator operator1 = new SpatialIndexReadOperator(storageManager1, Hyperrectangle.FULL_SPACE); final SpatialIndexReadOperator operator2 = new SpatialIndexReadOperator(storageManager2, Hyperrectangle.FULL_SPACE); final IndexedSpatialJoinOperator joinQueryProcessor1 = new IndexedSpatialJoinOperator(operator1, operator2); final Iterator<MultiTuple> iterator = joinQueryProcessor1.iterator(); final List<MultiTuple> resultList = Lists.newArrayList(iterator); joinQueryProcessor1.close(); Assert.assertEquals(1, resultList.size()); Assert.assertEquals(2, resultList.get(0).getNumberOfTuples()); Assert.assertEquals(2, resultList.get(0).getBoundingBox().getDimension()); Assert.assertEquals(new Hyperrectangle(2.5d, 5.5d, 2.5d, 5.5d), resultList.get(0).getBoundingBox()); }
@Test(timeout=60000) void function() throws StorageManagerException, RejectedException { storageRegistry.deleteTable(TABLE_1); storageRegistry.createTable(TABLE_1, new TupleStoreConfiguration()); storageRegistry.deleteTable(TABLE_2); storageRegistry.createTable(TABLE_2, new TupleStoreConfiguration()); final TupleStoreManager storageManager1 = storageRegistry.getTupleStoreManager(TABLE_1); final TupleStoreManager storageManager2 = storageRegistry.getTupleStoreManager(TABLE_2); final Tuple tuple1 = new Tuple("1a", new Hyperrectangle(1.0, 2.0, 1.0, 2.0), STR.getBytes()); final Tuple tuple2 = new Tuple("2a", new Hyperrectangle(4.0, 5.0, 4.0, 5.0), STR.getBytes()); final Tuple tuple3 = new Tuple("1b", new Hyperrectangle(1.5, 2.5, 1.5, 2.5), STR.getBytes()); final Tuple tuple4 = new Tuple("1b", new Hyperrectangle(2.5, 5.5, 2.5, 5.5), STR.getBytes()); storageManager1.put(tuple1); storageManager1.put(tuple2); storageManager2.put(tuple3); storageManager2.put(tuple4); final SpatialIndexReadOperator operator1 = new SpatialIndexReadOperator(storageManager1, Hyperrectangle.FULL_SPACE); final SpatialIndexReadOperator operator2 = new SpatialIndexReadOperator(storageManager2, Hyperrectangle.FULL_SPACE); final IndexedSpatialJoinOperator joinQueryProcessor1 = new IndexedSpatialJoinOperator(operator1, operator2); final Iterator<MultiTuple> iterator = joinQueryProcessor1.iterator(); final List<MultiTuple> resultList = Lists.newArrayList(iterator); joinQueryProcessor1.close(); Assert.assertEquals(1, resultList.size()); Assert.assertEquals(2, resultList.get(0).getNumberOfTuples()); Assert.assertEquals(2, resultList.get(0).getBoundingBox().getDimension()); Assert.assertEquals(new Hyperrectangle(2.5d, 5.5d, 2.5d, 5.5d), resultList.get(0).getBoundingBox()); }
/** * Simple Join * @throws StorageManagerException * @throws RejectedException */
Simple Join
testJoinWithChangedTuple1
{ "repo_name": "jnidzwetzki/scalephant", "path": "bboxdb-server/src/test/java/org/bboxdb/test/storage/TestQueryProcessing.java", "license": "apache-2.0", "size": 25654 }
[ "com.google.common.collect.Lists", "java.util.Iterator", "java.util.List", "org.bboxdb.commons.RejectedException", "org.bboxdb.commons.math.Hyperrectangle", "org.bboxdb.storage.StorageManagerException", "org.bboxdb.storage.entity.MultiTuple", "org.bboxdb.storage.entity.Tuple", "org.bboxdb.storage.entity.TupleStoreConfiguration", "org.bboxdb.storage.queryprocessor.operator.SpatialIndexReadOperator", "org.bboxdb.storage.queryprocessor.operator.join.IndexedSpatialJoinOperator", "org.bboxdb.storage.tuplestore.manager.TupleStoreManager", "org.junit.Assert", "org.junit.Test" ]
import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; import org.bboxdb.commons.RejectedException; import org.bboxdb.commons.math.Hyperrectangle; import org.bboxdb.storage.StorageManagerException; import org.bboxdb.storage.entity.MultiTuple; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.storage.entity.TupleStoreConfiguration; import org.bboxdb.storage.queryprocessor.operator.SpatialIndexReadOperator; import org.bboxdb.storage.queryprocessor.operator.join.IndexedSpatialJoinOperator; import org.bboxdb.storage.tuplestore.manager.TupleStoreManager; import org.junit.Assert; import org.junit.Test;
import com.google.common.collect.*; import java.util.*; import org.bboxdb.commons.*; import org.bboxdb.commons.math.*; import org.bboxdb.storage.*; import org.bboxdb.storage.entity.*; import org.bboxdb.storage.queryprocessor.operator.*; import org.bboxdb.storage.queryprocessor.operator.join.*; import org.bboxdb.storage.tuplestore.manager.*; import org.junit.*;
[ "com.google.common", "java.util", "org.bboxdb.commons", "org.bboxdb.storage", "org.junit" ]
com.google.common; java.util; org.bboxdb.commons; org.bboxdb.storage; org.junit;
492,138
public static String digest(final String alg, final String data) { return digest(alg, data.getBytes(StandardCharsets.UTF_8)); }
static String function(final String alg, final String data) { return digest(alg, data.getBytes(StandardCharsets.UTF_8)); }
/** * Computes hex encoded digest. * * @param alg Digest algorithm to use * @param data data to be hashed * @return hex encoded hash */
Computes hex encoded digest
digest
{ "repo_name": "robertoschwald/cas", "path": "core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/DigestUtils.java", "license": "apache-2.0", "size": 5510 }
[ "java.nio.charset.StandardCharsets" ]
import java.nio.charset.StandardCharsets;
import java.nio.charset.*;
[ "java.nio" ]
java.nio;
2,144,589
@ServiceMethod(returns = ReturnType.SINGLE) public RulesEngineInner createOrUpdate( String resourceGroupName, String frontDoorName, String rulesEngineName, RulesEngineInner rulesEngineParameters, Context context) { return createOrUpdateAsync(resourceGroupName, frontDoorName, rulesEngineName, rulesEngineParameters, context) .block(); }
@ServiceMethod(returns = ReturnType.SINGLE) RulesEngineInner function( String resourceGroupName, String frontDoorName, String rulesEngineName, RulesEngineInner rulesEngineParameters, Context context) { return createOrUpdateAsync(resourceGroupName, frontDoorName, rulesEngineName, rulesEngineParameters, context) .block(); }
/** * Creates a new Rules Engine Configuration with the specified name within the specified Front Door. * * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param frontDoorName Name of the Front Door which is globally unique. * @param rulesEngineName Name of the Rules Engine which is unique within the Front Door. * @param rulesEngineParameters Rules Engine Configuration properties needed to create a new Rules Engine * Configuration. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a rules engine configuration containing a list of rules that will run to modify the runtime behavior of * the request and response. */
Creates a new Rules Engine Configuration with the specified name within the specified Front Door
createOrUpdate
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/frontdoor/azure-resourcemanager-frontdoor/src/main/java/com/azure/resourcemanager/frontdoor/implementation/RulesEnginesClientImpl.java", "license": "mit", "size": 60120 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.util.Context", "com.azure.resourcemanager.frontdoor.fluent.models.RulesEngineInner" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.util.Context; import com.azure.resourcemanager.frontdoor.fluent.models.RulesEngineInner;
import com.azure.core.annotation.*; import com.azure.core.util.*; import com.azure.resourcemanager.frontdoor.fluent.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
1,145,428
public Builder priv() { headers.add(CacheControl.HEADER, "private"); return this; }
Builder function() { headers.add(CacheControl.HEADER, STR); return this; }
/** * Sets the cache control header to private. * @return this */
Sets the cache control header to private
priv
{ "repo_name": "programingjd/okserver", "path": "src/main/java/info/jdavid/ok/server/Response.java", "license": "apache-2.0", "size": 31412 }
[ "info.jdavid.ok.server.header.CacheControl" ]
import info.jdavid.ok.server.header.CacheControl;
import info.jdavid.ok.server.header.*;
[ "info.jdavid.ok" ]
info.jdavid.ok;
1,326,301
public static FastDateFormat getInstance(final String pattern, final Locale locale) { return cache.getInstance(pattern, null, locale); } /** * <p>Gets a formatter instance using the specified pattern, time zone * and locale.</p> * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid * or {@code null}
static FastDateFormat function(final String pattern, final Locale locale) { return cache.getInstance(pattern, null, locale); } /** * <p>Gets a formatter instance using the specified pattern, time zone * and locale.</p> * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid * or {@code null}
/** * <p>Gets a formatter instance using the specified pattern and * locale.</p> * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */
Gets a formatter instance using the specified pattern and locale
getInstance
{ "repo_name": "angelLYK/sqlite-jdbc", "path": "src/main/java/org/sqlite/date/FastDateFormat.java", "license": "apache-2.0", "size": 21993 }
[ "java.util.Locale" ]
import java.util.Locale;
import java.util.*;
[ "java.util" ]
java.util;
1,662,126
public void setWritingModeTraits(WritingModeTraitsGetter wmtg) { if (regionReference != null) { regionReference.setWritingModeTraits(wmtg); } }
void function(WritingModeTraitsGetter wmtg) { if (regionReference != null) { regionReference.setWritingModeTraits(wmtg); } }
/** * Sets the writing mode traits for the region reference of * this region viewport * @param wmtg a WM traits getter */
Sets the writing mode traits for the region reference of this region viewport
setWritingModeTraits
{ "repo_name": "Distrotech/fop", "path": "src/java/org/apache/fop/area/RegionViewport.java", "license": "apache-2.0", "size": 4388 }
[ "org.apache.fop.traits.WritingModeTraitsGetter" ]
import org.apache.fop.traits.WritingModeTraitsGetter;
import org.apache.fop.traits.*;
[ "org.apache.fop" ]
org.apache.fop;
1,089,806
static Predicate<Method> excludedDeclaredClass(Class<?> declaredClass) { return method -> !Objects.equals(declaredClass, method.getDeclaringClass()); } /** * Get all {@link Method methods} of the declared class * * @param declaringClass the declared class * @param includeInheritedTypes include the inherited types, e,g. super classes or interfaces * @param publicOnly only public method * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List}
static Predicate<Method> excludedDeclaredClass(Class<?> declaredClass) { return method -> !Objects.equals(declaredClass, method.getDeclaringClass()); } /** * Get all {@link Method methods} of the declared class * * @param declaringClass the declared class * @param includeInheritedTypes include the inherited types, e,g. super classes or interfaces * @param publicOnly only public method * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List}
/** * Create an instance of {@link Predicate} for {@link Method} to exclude the specified declared class * * @param declaredClass the declared class to exclude * @return non-null * @since 2.7.6 */
Create an instance of <code>Predicate</code> for <code>Method</code> to exclude the specified declared class
excludedDeclaredClass
{ "repo_name": "lovepoem/dubbo", "path": "dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java", "license": "apache-2.0", "size": 14931 }
[ "java.lang.reflect.Method", "java.util.List", "java.util.Objects", "java.util.function.Predicate" ]
import java.lang.reflect.Method; import java.util.List; import java.util.Objects; import java.util.function.Predicate;
import java.lang.reflect.*; import java.util.*; import java.util.function.*;
[ "java.lang", "java.util" ]
java.lang; java.util;
1,925,493
protected Node exitNumber(Production node) throws ParseException { return node; }
Node function(Production node) throws ParseException { return node; }
/** * Called when exiting a parse tree node. * * @param node the node being exited * * @return the node to add to the parse tree, or * null if no parse tree should be created * * @throws ParseException if the node analysis discovered errors */
Called when exiting a parse tree node
exitNumber
{ "repo_name": "richb-hanover/mibble-2.9.2", "path": "src/java/net/percederberg/mibble/asn1/Asn1Analyzer.java", "license": "gpl-2.0", "size": 275483 }
[ "net.percederberg.grammatica.parser.Node", "net.percederberg.grammatica.parser.ParseException", "net.percederberg.grammatica.parser.Production" ]
import net.percederberg.grammatica.parser.Node; import net.percederberg.grammatica.parser.ParseException; import net.percederberg.grammatica.parser.Production;
import net.percederberg.grammatica.parser.*;
[ "net.percederberg.grammatica" ]
net.percederberg.grammatica;
447,655
public void setProgressable(Progressable reporter);
void function(Progressable reporter);
/** Pass the Progressable object so that sort can call progress while it is sorting * @param reporter the Progressable object reference */
Pass the Progressable object so that sort can call progress while it is sorting
setProgressable
{ "repo_name": "gndpig/hadoop", "path": "src/mapred/org/apache/hadoop/mapred/BufferSorter.java", "license": "apache-2.0", "size": 3303 }
[ "org.apache.hadoop.util.Progressable" ]
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
1,343,473
public void initPullToRefreshListView() { mLvDisplay_display = (PullToRefreshListView) mDisplay_display .findViewById(R.id.display_display); mSADisplay_dislpay = new SimpleInfoAdapter(this, mDSDisplay_Display); mVfooterDisplay_Display = mLayoutInflator.inflate( R.layout.listviewfooter, null); mVfooter_progressDisplay_Display = (ProgressBar) mVfooterDisplay_Display .findViewById(R.id.listview_foot_progress); mVfooter_moreDisplay_Display = (TextView) mVfooterDisplay_Display .findViewById(R.id.listview_foot_more); mVfooter_progressDisplay_Display.setVisibility(View.GONE); mLvDisplay_display.addFooterView(mVfooterDisplay_Display); mLvDisplay_display.setAdapter(mSADisplay_dislpay); this.initDisplay_displayListener(); }
void function() { mLvDisplay_display = (PullToRefreshListView) mDisplay_display .findViewById(R.id.display_display); mSADisplay_dislpay = new SimpleInfoAdapter(this, mDSDisplay_Display); mVfooterDisplay_Display = mLayoutInflator.inflate( R.layout.listviewfooter, null); mVfooter_progressDisplay_Display = (ProgressBar) mVfooterDisplay_Display .findViewById(R.id.listview_foot_progress); mVfooter_moreDisplay_Display = (TextView) mVfooterDisplay_Display .findViewById(R.id.listview_foot_more); mVfooter_progressDisplay_Display.setVisibility(View.GONE); mLvDisplay_display.addFooterView(mVfooterDisplay_Display); mLvDisplay_display.setAdapter(mSADisplay_dislpay); this.initDisplay_displayListener(); }
/** * init pulltorefreshlistview */
init pulltorefreshlistview
initPullToRefreshListView
{ "repo_name": "zhanglei920802/Sartino", "path": "Android/src/com/sartino/huayi/app/ui/DisplayActivity.java", "license": "gpl-3.0", "size": 11302 }
[ "android.view.View", "android.widget.ProgressBar", "android.widget.TextView", "com.sartino.huayi.app.ui.adapter.SimpleInfoAdapter", "com.sartino.huayi.app.ui.widgets.PullToRefreshListView" ]
import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.sartino.huayi.app.ui.adapter.SimpleInfoAdapter; import com.sartino.huayi.app.ui.widgets.PullToRefreshListView;
import android.view.*; import android.widget.*; import com.sartino.huayi.app.ui.adapter.*; import com.sartino.huayi.app.ui.widgets.*;
[ "android.view", "android.widget", "com.sartino.huayi" ]
android.view; android.widget; com.sartino.huayi;
2,196,112
public Color getBGColor() { // try { // // defined by the SimpleFillSymbol layer // IFillSymbol symbol = (IFillSymbol) ((MultiLayerFillSymbol) getDefaultSymbol()). // getLayer(SIMPLE_FILL_LAYER_INDEX); // return symbol.getFillColor(); // } catch (NullPointerException npE) { // return null; // } return backgroundColor; }
Color function() { return backgroundColor; }
/** * Obtains the background color for the dot density legend * @return */
Obtains the background color for the dot density legend
getBGColor
{ "repo_name": "iCarto/siga", "path": "extSymbology/src/org/gvsig/symbology/fmap/rendering/DotDensityLegend.java", "license": "gpl-3.0", "size": 8916 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
446,311
public ServiceFuture<DataBoxEdgeDeviceInner> beginCreateOrUpdateAsync(String deviceName, String resourceGroupName, DataBoxEdgeDeviceInner dataBoxEdgeDevice, final ServiceCallback<DataBoxEdgeDeviceInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, dataBoxEdgeDevice), serviceCallback); }
ServiceFuture<DataBoxEdgeDeviceInner> function(String deviceName, String resourceGroupName, DataBoxEdgeDeviceInner dataBoxEdgeDevice, final ServiceCallback<DataBoxEdgeDeviceInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, dataBoxEdgeDevice), serviceCallback); }
/** * Creates or updates a Data Box Edge/Gateway resource. * * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param dataBoxEdgeDevice The resource object. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */
Creates or updates a Data Box Edge/Gateway resource
beginCreateOrUpdateAsync
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/edgegateway/mgmt-v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java", "license": "mit", "size": 143759 }
[ "com.microsoft.rest.ServiceCallback", "com.microsoft.rest.ServiceFuture" ]
import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.*;
[ "com.microsoft.rest" ]
com.microsoft.rest;
2,483,665
@Test public void testAsyncErrorRethrownOnInvoke() throws Throwable { final DummyFlinkKafkaProducer<String> producer = new DummyFlinkKafkaProducer<>( FakeStandardProducerConfig.get(), new KeyedSerializationSchemaWrapper<>(new SimpleStringSchema()), null); OneInputStreamOperatorTestHarness<String, Object> testHarness = new OneInputStreamOperatorTestHarness<>(new StreamSink<>(producer)); testHarness.open(); testHarness.processElement(new StreamRecord<>("msg-1")); // let the message request return an async exception producer.getPendingCallbacks().get(0).onCompletion(null, new Exception("artificial async exception")); try { testHarness.processElement(new StreamRecord<>("msg-2")); } catch (Exception e) { // the next invoke should rethrow the async exception Assert.assertTrue(e.getCause().getMessage().contains("artificial async exception")); // test succeeded return; } Assert.fail(); }
void function() throws Throwable { final DummyFlinkKafkaProducer<String> producer = new DummyFlinkKafkaProducer<>( FakeStandardProducerConfig.get(), new KeyedSerializationSchemaWrapper<>(new SimpleStringSchema()), null); OneInputStreamOperatorTestHarness<String, Object> testHarness = new OneInputStreamOperatorTestHarness<>(new StreamSink<>(producer)); testHarness.open(); testHarness.processElement(new StreamRecord<>("msg-1")); producer.getPendingCallbacks().get(0).onCompletion(null, new Exception(STR)); try { testHarness.processElement(new StreamRecord<>("msg-2")); } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage().contains(STR)); return; } Assert.fail(); }
/** * Test ensuring that if an invoke call happens right after an async exception is caught, it should be rethrown. */
Test ensuring that if an invoke call happens right after an async exception is caught, it should be rethrown
testAsyncErrorRethrownOnInvoke
{ "repo_name": "WangTaoTheTonic/flink", "path": "flink-connectors/flink-connector-kafka-base/src/test/java/org/apache/flink/streaming/connectors/kafka/FlinkKafkaProducerBaseTest.java", "license": "apache-2.0", "size": 16746 }
[ "org.apache.flink.streaming.api.operators.StreamSink", "org.apache.flink.streaming.connectors.kafka.testutils.FakeStandardProducerConfig", "org.apache.flink.streaming.runtime.streamrecord.StreamRecord", "org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness", "org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper", "org.apache.flink.streaming.util.serialization.SimpleStringSchema", "org.junit.Assert" ]
import org.apache.flink.streaming.api.operators.StreamSink; import org.apache.flink.streaming.connectors.kafka.testutils.FakeStandardProducerConfig; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness; import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper; import org.apache.flink.streaming.util.serialization.SimpleStringSchema; import org.junit.Assert;
import org.apache.flink.streaming.api.operators.*; import org.apache.flink.streaming.connectors.kafka.testutils.*; import org.apache.flink.streaming.runtime.streamrecord.*; import org.apache.flink.streaming.util.*; import org.apache.flink.streaming.util.serialization.*; import org.junit.*;
[ "org.apache.flink", "org.junit" ]
org.apache.flink; org.junit;
2,531,064
protected boolean isTimeToCheckPredicate(double time) { return time > lastProcessingTime && (long) time % getVm().getHost().getDatacenter().getSchedulingInterval() == 0; } /** * Performs the actual request to scale the Vm up or down, * depending if it is over or underloaded, respectively. * This method is automatically called by {@link #requestScalingIfPredicateMatch(double)}
boolean function(double time) { return time > lastProcessingTime && (long) time % getVm().getHost().getDatacenter().getSchedulingInterval() == 0; } /** * Performs the actual request to scale the Vm up or down, * depending if it is over or underloaded, respectively. * This method is automatically called by {@link #requestScalingIfPredicateMatch(double)}
/** * Checks if it is time to evaluate weather the Vm is under or overloaded. * * @param time current simulation time * @return true if it's time to check weather the Vm is over and underloaded, false otherwise */
Checks if it is time to evaluate weather the Vm is under or overloaded
isTimeToCheckPredicate
{ "repo_name": "RaysaOliveira/cloudsim-plus", "path": "cloudsim-plus/src/main/java/org/cloudsimplus/autoscaling/VmScalingAbstract.java", "license": "gpl-3.0", "size": 2968 }
[ "org.cloudbus.cloudsim.vms.Vm" ]
import org.cloudbus.cloudsim.vms.Vm;
import org.cloudbus.cloudsim.vms.*;
[ "org.cloudbus.cloudsim" ]
org.cloudbus.cloudsim;
1,219,697
@SuppressWarnings("deprecation") private void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views, int appWidgetId) { Intent intent = new Intent(context, DetailWidgetRemoteViewsService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); views.setRemoteAdapter(appWidgetId, R.id.widget_list, intent); }
@SuppressWarnings(STR) void function(Context context, @NonNull final RemoteViews views, int appWidgetId) { Intent intent = new Intent(context, DetailWidgetRemoteViewsService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); views.setRemoteAdapter(appWidgetId, R.id.widget_list, intent); }
/** * Sets the remote adapter used to fill in the list items * * @param views RemoteViews to set the RemoteAdapter */
Sets the remote adapter used to fill in the list items
setRemoteAdapterV11
{ "repo_name": "BNDKPNTR/Habito", "path": "app/src/main/java/com/ivanmagda/habito/widget/DetailWidgetProvider.java", "license": "mit", "size": 4190 }
[ "android.appwidget.AppWidgetManager", "android.content.Context", "android.content.Intent", "android.net.Uri", "android.support.annotation.NonNull", "android.widget.RemoteViews" ]
import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import android.widget.RemoteViews;
import android.appwidget.*; import android.content.*; import android.net.*; import android.support.annotation.*; import android.widget.*;
[ "android.appwidget", "android.content", "android.net", "android.support", "android.widget" ]
android.appwidget; android.content; android.net; android.support; android.widget;
1,377,785
void setProteaseNames(Set<String> proteaseNames);
void setProteaseNames(Set<String> proteaseNames);
/** * Sets the proteases peptides are generated for. * * @param proteaseNames the protease names */
Sets the proteases peptides are generated for
setProteaseNames
{ "repo_name": "compomics/compomics-sigpep", "path": "sigpep-app/src/main/java/com/compomics/sigpep/PeptideGenerator.java", "license": "apache-2.0", "size": 8810 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,096,631
public int run(String[] args) throws Exception { try { Path parentPath = null; List<Path> srcPaths = new ArrayList<Path>(); Path destPath = null; String archiveName = null; if (args.length < 5) { System.out.println(usage); throw new IOException("Invalid usage."); } if (!"-archiveName".equals(args[0])) { System.out.println(usage); throw new IOException("Archive Name not specified."); } archiveName = args[1]; if (!checkValidName(archiveName)) { System.out.println(usage); throw new IOException("Invalid name for archives. " + archiveName); } int i = 2; //check to see if relative parent has been provided or not //this is a required parameter. if (! "-p".equals(args[i])) { System.out.println(usage); throw new IOException("Parent path not specified."); } parentPath = new Path(args[i+1]); if (!parentPath.isAbsolute()) { parentPath= parentPath.getFileSystem(getConf()).makeQualified(parentPath); } i+=2; //read the rest of the paths for (; i < args.length; i++) { if (i == (args.length - 1)) { destPath = new Path(args[i]); if (!destPath.isAbsolute()) { destPath = destPath.getFileSystem(getConf()).makeQualified(destPath); } } else { Path argPath = new Path(args[i]); if (argPath.isAbsolute()) { System.out.println(usage); throw new IOException("source path " + argPath + " is not relative to "+ parentPath); } srcPaths.add(new Path(parentPath, argPath)); } } if (srcPaths.size() == 0) { // assuming if the user does not specify path for sources // the whole parent directory needs to be archived. srcPaths.add(parentPath); } // do a glob on the srcPaths and then pass it on List<Path> globPaths = new ArrayList<Path>(); for (Path p: srcPaths) { FileSystem fs = p.getFileSystem(getConf()); FileStatus[] statuses = fs.globStatus(p); if (statuses != null) { for (FileStatus status: statuses) { globPaths.add(fs.makeQualified(status.getPath())); } } } if (globPaths.isEmpty()) { throw new IOException("The resolved paths set is empty." + " Please check whether the srcPaths exist, where srcPaths = " + srcPaths); } archive(parentPath, globPaths, archiveName, destPath); } catch(IOException ie) { System.err.println(ie.getLocalizedMessage()); return -1; } return 0; } static final String TEST_HADOOP_ARCHIVES_JAR_PATH = "test.hadoop.archives.jar";
int function(String[] args) throws Exception { try { Path parentPath = null; List<Path> srcPaths = new ArrayList<Path>(); Path destPath = null; String archiveName = null; if (args.length < 5) { System.out.println(usage); throw new IOException(STR); } if (!STR.equals(args[0])) { System.out.println(usage); throw new IOException(STR); } archiveName = args[1]; if (!checkValidName(archiveName)) { System.out.println(usage); throw new IOException(STR + archiveName); } int i = 2; if (! "-p".equals(args[i])) { System.out.println(usage); throw new IOException(STR); } parentPath = new Path(args[i+1]); if (!parentPath.isAbsolute()) { parentPath= parentPath.getFileSystem(getConf()).makeQualified(parentPath); } i+=2; for (; i < args.length; i++) { if (i == (args.length - 1)) { destPath = new Path(args[i]); if (!destPath.isAbsolute()) { destPath = destPath.getFileSystem(getConf()).makeQualified(destPath); } } else { Path argPath = new Path(args[i]); if (argPath.isAbsolute()) { System.out.println(usage); throw new IOException(STR + argPath + STR+ parentPath); } srcPaths.add(new Path(parentPath, argPath)); } } if (srcPaths.size() == 0) { srcPaths.add(parentPath); } List<Path> globPaths = new ArrayList<Path>(); for (Path p: srcPaths) { FileSystem fs = p.getFileSystem(getConf()); FileStatus[] statuses = fs.globStatus(p); if (statuses != null) { for (FileStatus status: statuses) { globPaths.add(fs.makeQualified(status.getPath())); } } } if (globPaths.isEmpty()) { throw new IOException(STR + STR + srcPaths); } archive(parentPath, globPaths, archiveName, destPath); } catch(IOException ie) { System.err.println(ie.getLocalizedMessage()); return -1; } return 0; } static final String TEST_HADOOP_ARCHIVES_JAR_PATH = STR;
/** the main driver for creating the archives * it takes at least three command line parameters. The parent path, * The src and the dest. It does an lsr on the source paths. * The mapper created archuves and the reducer creates * the archive index. */
the main driver for creating the archives it takes at least three command line parameters. The parent path, The src and the dest. It does an lsr on the source paths. The mapper created archuves and the reducer creates the archive index
run
{ "repo_name": "tseen/Federated-HDFS", "path": "tseenliu/FedHDFS-hadoop-src/hadoop-tools/hadoop-archives/src/main/java/org/apache/hadoop/tools/HadoopArchives.java", "license": "apache-2.0", "size": 31710 }
[ "java.io.IOException", "java.util.ArrayList", "java.util.List", "org.apache.hadoop.fs.FileStatus", "org.apache.hadoop.fs.FileSystem", "org.apache.hadoop.fs.Path" ]
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path;
import java.io.*; import java.util.*; import org.apache.hadoop.fs.*;
[ "java.io", "java.util", "org.apache.hadoop" ]
java.io; java.util; org.apache.hadoop;
411,522
public void enable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (isOptOut()) { configuration.set("opt-out", false); configuration.save(configurationFile); } // Enable Task, if it is not running if (task == null) { start(); } } }
void function() throws IOException { synchronized (optOutLock) { if (isOptOut()) { configuration.set(STR, false); configuration.save(configurationFile); } if (task == null) { start(); } } }
/** * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * * @throws java.io.IOException */
Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task
enable
{ "repo_name": "CyberdyneCC/Thermos", "path": "src/main/java/org/spigotmc/Metrics.java", "license": "gpl-3.0", "size": 22796 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
15,404
public Builder error(@DrawableRes int errorRes) { this.crossbowImage.errorDrawable = context.getResources().getDrawable(errorRes); return this; }
Builder function(@DrawableRes int errorRes) { this.crossbowImage.errorDrawable = context.getResources().getDrawable(errorRes); return this; }
/** * The drawable res to use when the image fails to load * * @param errorRes the drawable res to use */
The drawable res to use when the image fails to load
error
{ "repo_name": "TwistedEquations/CrossBow", "path": "Libraries/shared-code/crossbow-core/main/src/com/crossbow/volley/CrossbowImage.java", "license": "apache-2.0", "size": 18067 }
[ "android.support.annotation.DrawableRes" ]
import android.support.annotation.DrawableRes;
import android.support.annotation.*;
[ "android.support" ]
android.support;
650,143
private void skipUnreadMessages() { processConfigMessages(new LinkedList<String>()); log.info("Config manager skipped messages"); }
void function() { processConfigMessages(new LinkedList<String>()); log.info(STR); }
/** * notAValidEvent all the unread messages up to the time this function is called. * This method just reads the messages, and it does not react to them or change any configuration of the system. */
notAValidEvent all the unread messages up to the time this function is called. This method just reads the messages, and it does not react to them or change any configuration of the system
skipUnreadMessages
{ "repo_name": "bharathkk/samza", "path": "samza-autoscaling/src/main/java/org/apache/samza/autoscaling/deployer/ConfigManager.java", "license": "apache-2.0", "size": 14812 }
[ "java.util.LinkedList" ]
import java.util.LinkedList;
import java.util.*;
[ "java.util" ]
java.util;
1,287,566
public String doConfirmRemoveAdminUser( HttpServletRequest request ) throws AccessDeniedException { String strUserId = request.getParameter( PARAMETER_USER_ID ); int nUserId = Integer.parseInt( strUserId ); AdminUser user = AdminUserHome.findByPrimaryKey( nUserId ); if ( user == null ) { return AdminMessageService.getMessageUrl( request, PROPERTY_MESSAGE_USER_ERROR_SESSION, AdminMessage.TYPE_ERROR ); } AdminUser currentUser = AdminUserService.getAdminUser( request ); if ( !isUserAuthorizedToModifyUser( currentUser, user ) ) { throw new fr.paris.lutece.portal.service.admin.AccessDeniedException( MESSAGE_NOT_AUTHORIZED ); } String strUrlRemove = JSP_URL_REMOVE_USER; Map<String, Object> parameters = new HashMap<>( ); parameters.put( PARAMETER_USER_ID, strUserId ); parameters.put( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, JSP_URL_REMOVE_USER ) ); return AdminMessageService.getMessageUrl( request, PROPERTY_MESSAGE_CONFIRM_REMOVE, new Object [ ] { user.getFirstName( ), user.getLastName( ), user.getAccessCode( ) }, null, strUrlRemove, null, AdminMessage.TYPE_CONFIRMATION, parameters ); }
String function( HttpServletRequest request ) throws AccessDeniedException { String strUserId = request.getParameter( PARAMETER_USER_ID ); int nUserId = Integer.parseInt( strUserId ); AdminUser user = AdminUserHome.findByPrimaryKey( nUserId ); if ( user == null ) { return AdminMessageService.getMessageUrl( request, PROPERTY_MESSAGE_USER_ERROR_SESSION, AdminMessage.TYPE_ERROR ); } AdminUser currentUser = AdminUserService.getAdminUser( request ); if ( !isUserAuthorizedToModifyUser( currentUser, user ) ) { throw new fr.paris.lutece.portal.service.admin.AccessDeniedException( MESSAGE_NOT_AUTHORIZED ); } String strUrlRemove = JSP_URL_REMOVE_USER; Map<String, Object> parameters = new HashMap<>( ); parameters.put( PARAMETER_USER_ID, strUserId ); parameters.put( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, JSP_URL_REMOVE_USER ) ); return AdminMessageService.getMessageUrl( request, PROPERTY_MESSAGE_CONFIRM_REMOVE, new Object [ ] { user.getFirstName( ), user.getLastName( ), user.getAccessCode( ) }, null, strUrlRemove, null, AdminMessage.TYPE_CONFIRMATION, parameters ); }
/** * Returns the page of confirmation for deleting a provider * * @param request * The Http Request * @return the confirmation url * @throws AccessDeniedException * When not authorized */
Returns the page of confirmation for deleting a provider
doConfirmRemoveAdminUser
{ "repo_name": "rzara/lutece-core", "path": "src/java/fr/paris/lutece/portal/web/user/AdminUserJspBean.java", "license": "bsd-3-clause", "size": 121999 }
[ "fr.paris.lutece.portal.business.user.AdminUser", "fr.paris.lutece.portal.business.user.AdminUserHome", "fr.paris.lutece.portal.service.admin.AccessDeniedException", "fr.paris.lutece.portal.service.admin.AdminUserService", "fr.paris.lutece.portal.service.message.AdminMessage", "fr.paris.lutece.portal.service.message.AdminMessageService", "fr.paris.lutece.portal.service.security.SecurityTokenService", "java.util.HashMap", "java.util.Map", "javax.servlet.http.HttpServletRequest" ]
import fr.paris.lutece.portal.business.user.AdminUser; import fr.paris.lutece.portal.business.user.AdminUserHome; import fr.paris.lutece.portal.service.admin.AccessDeniedException; import fr.paris.lutece.portal.service.admin.AdminUserService; import fr.paris.lutece.portal.service.message.AdminMessage; import fr.paris.lutece.portal.service.message.AdminMessageService; import fr.paris.lutece.portal.service.security.SecurityTokenService; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest;
import fr.paris.lutece.portal.business.user.*; import fr.paris.lutece.portal.service.admin.*; import fr.paris.lutece.portal.service.message.*; import fr.paris.lutece.portal.service.security.*; import java.util.*; import javax.servlet.http.*;
[ "fr.paris.lutece", "java.util", "javax.servlet" ]
fr.paris.lutece; java.util; javax.servlet;
2,040,973
public File getWorkingDir(String applicationOid) { Application app = Application.get(); return app.getConfiguration().getUserPath(applicationOid); }
File function(String applicationOid) { Application app = Application.get(); return app.getConfiguration().getUserPath(applicationOid); }
/** * Return the base directory where all users are stored * * @param applicationOid * @return */
Return the base directory where all users are stored
getWorkingDir
{ "repo_name": "mikegr/snipsnap", "path": "src/org/snipsnap/snip/storage/FileUserStorage.java", "license": "gpl-2.0", "size": 6096 }
[ "java.io.File", "org.snipsnap.app.Application" ]
import java.io.File; import org.snipsnap.app.Application;
import java.io.*; import org.snipsnap.app.*;
[ "java.io", "org.snipsnap.app" ]
java.io; org.snipsnap.app;
16,208
ProgressBarFilterInputStream getLoggedInputStream(InputStream in, int size) throws IOException;
ProgressBarFilterInputStream getLoggedInputStream(InputStream in, int size) throws IOException;
/** * Return a input stream that will generate log messages showing * the progress of the read from the given stream. * * @param in the input stream to be monitored * @param size the size in bytes of the date to be read, or 0 if not known */
Return a input stream that will generate log messages showing the progress of the read from the given stream
getLoggedInputStream
{ "repo_name": "arturog8m/ocs", "path": "bundle/jsky.util.gui/src/main/java/jsky/util/gui/StatusLogger.java", "license": "bsd-3-clause", "size": 2147 }
[ "java.io.IOException", "java.io.InputStream" ]
import java.io.IOException; import java.io.InputStream;
import java.io.*;
[ "java.io" ]
java.io;
1,076,515
private Rectangle2D drawFill(Graphics2D g2, Rectangle2D area) { Rectangle2D filledArea = (Rectangle2D)area.clone(); filledArea = trimMargin(filledArea); filledArea = trimBorder(filledArea); area = trimPadding(area); g2.setPaint(this.fillPaint); g2.fill(filledArea); drawBorder(g2, filledArea); return filledArea; }
Rectangle2D function(Graphics2D g2, Rectangle2D area) { Rectangle2D filledArea = (Rectangle2D)area.clone(); filledArea = trimMargin(filledArea); filledArea = trimBorder(filledArea); area = trimPadding(area); g2.setPaint(this.fillPaint); g2.fill(filledArea); drawBorder(g2, filledArea); return filledArea; }
/** * Draws a colored background. Returns the area wich has been filled. */
Draws a colored background. Returns the area wich has been filled
drawFill
{ "repo_name": "aborg0/RapidMiner-Unuk", "path": "src/com/rapidminer/gui/new_plotter/engine/jfreechart/legend/ColoredBlockContainer.java", "license": "agpl-3.0", "size": 4796 }
[ "java.awt.Graphics2D", "java.awt.geom.Rectangle2D" ]
import java.awt.Graphics2D; import java.awt.geom.Rectangle2D;
import java.awt.*; import java.awt.geom.*;
[ "java.awt" ]
java.awt;
777,323
public void _setCreator() { if (tEnv.getTestCase().getObjectName().equals("Desktop")) { log.println("Desktop has no creator"); tRes.tested("setCreator()", true) ; return; } XFramesSupplier oldCreator = oObj.getCreator() ; oObj.setCreator(null) ; tRes.tested("setCreator()", oObj.getCreator() == null) ; oObj.setCreator(oldCreator) ; }
void function() { if (tEnv.getTestCase().getObjectName().equals(STR)) { log.println(STR); tRes.tested(STR, true) ; return; } XFramesSupplier oldCreator = oObj.getCreator() ; oObj.setCreator(null) ; tRes.tested(STR, oObj.getCreator() == null) ; oObj.setCreator(oldCreator) ; }
/** * Test calls the method. Remembered old creater is restored at the end. <p> * Has <b> OK </b> status if the method successfully set new value to (XFrame) * oObj object. */
Test calls the method. Remembered old creater is restored at the end. Has OK status if the method successfully set new value to (XFrame) oObj object
_setCreator
{ "repo_name": "sbbic/core", "path": "qadevOOo/tests/java/ifc/frame/_XFrame.java", "license": "gpl-3.0", "size": 20035 }
[ "com.sun.star.frame.XFramesSupplier" ]
import com.sun.star.frame.XFramesSupplier;
import com.sun.star.frame.*;
[ "com.sun.star" ]
com.sun.star;
1,333,939
public void bulkLoad(final Code code) { if (isBulkLoad()) { Code.wrapThrow(code); } else { setBulkLoad(true); Code.wrapThrow(code, () -> setBulkLoad(false)); } }
void function(final Code code) { if (isBulkLoad()) { Code.wrapThrow(code); } else { setBulkLoad(true); Code.wrapThrow(code, () -> setBulkLoad(false)); } }
/** * Execute the supplied code fragment in bulk load mode and reset to * incremental mode when finished. * * @see #setBulkLoad(boolean) */
Execute the supplied code fragment in bulk load mode and reset to incremental mode when finished
bulkLoad
{ "repo_name": "blazegraph/tinkerpop3", "path": "src/main/java/com/blazegraph/gremlin/structure/BlazeGraph.java", "license": "gpl-2.0", "size": 56488 }
[ "com.blazegraph.gremlin.util.Code" ]
import com.blazegraph.gremlin.util.Code;
import com.blazegraph.gremlin.util.*;
[ "com.blazegraph.gremlin" ]
com.blazegraph.gremlin;
395,715
void enterLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx); void exitLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx);
void enterLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx); void exitLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx);
/** * Exit a parse tree produced by {@link JavaParser#lastFormalParameter}. * @param ctx the parse tree */
Exit a parse tree produced by <code>JavaParser#lastFormalParameter</code>
exitLastFormalParameter
{ "repo_name": "hgkmail/HelloJava", "path": "src/cn/hgk/hellojava/JavaListener.java", "license": "gpl-2.0", "size": 38976 }
[ "org.antlr.v4.runtime.misc.NotNull" ]
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.*;
[ "org.antlr.v4" ]
org.antlr.v4;
1,615,795
public static GraphStore connectGraphStore(Store store) { return new DatasetStoreGraph(store, SDB.getContext().copy()) ; }
static GraphStore function(Store store) { return new DatasetStoreGraph(store, SDB.getContext().copy()) ; }
/** * Connect to the store as a GraphStore * @param store * @return GraphStore */
Connect to the store as a GraphStore
connectGraphStore
{ "repo_name": "hdadler/sensetrace-src", "path": "com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-sdb/src/main/java/com/hp/hpl/jena/sdb/SDBFactory.java", "license": "gpl-2.0", "size": 13731 }
[ "com.hp.hpl.jena.sdb.store.DatasetStoreGraph", "com.hp.hpl.jena.update.GraphStore" ]
import com.hp.hpl.jena.sdb.store.DatasetStoreGraph; import com.hp.hpl.jena.update.GraphStore;
import com.hp.hpl.jena.sdb.store.*; import com.hp.hpl.jena.update.*;
[ "com.hp.hpl" ]
com.hp.hpl;
606,059
CmsAliasInitialFetchResult getAliasTable() throws CmsRpcException;
CmsAliasInitialFetchResult getAliasTable() throws CmsRpcException;
/** * Gets the initial data for the bulk alias editor.<p> * * @return the initial data for the alias editor * * @throws CmsRpcException if something goes wrong */
Gets the initial data for the bulk alias editor
getAliasTable
{ "repo_name": "sbonoc/opencms-core", "path": "src/org/opencms/ade/sitemap/shared/rpc/I_CmsSitemapService.java", "license": "lgpl-2.1", "size": 7853 }
[ "org.opencms.gwt.CmsRpcException", "org.opencms.gwt.shared.alias.CmsAliasInitialFetchResult" ]
import org.opencms.gwt.CmsRpcException; import org.opencms.gwt.shared.alias.CmsAliasInitialFetchResult;
import org.opencms.gwt.*; import org.opencms.gwt.shared.alias.*;
[ "org.opencms.gwt" ]
org.opencms.gwt;
633,496
public String getEffectiveListName() throws NoResponseException, XMPPErrorException, NotConnectedException { String activeListName = getActiveListName(); if (activeListName != null) { return activeListName; } return getDefaultListName(); }
String function() throws NoResponseException, XMPPErrorException, NotConnectedException { String activeListName = getActiveListName(); if (activeListName != null) { return activeListName; } return getDefaultListName(); }
/** * Returns the name of the effective privacy list. * <p> * The effective privacy list is the one that is currently enforced on the connection. It's either the active * privacy list, or, if the active privacy list is not set, the default privacy list. * </p> * * @return the name of the effective privacy list or null if there is none set. * @throws NoResponseException * @throws XMPPErrorException * @throws NotConnectedException * @since 4.1 */
Returns the name of the effective privacy list. The effective privacy list is the one that is currently enforced on the connection. It's either the active privacy list, or, if the active privacy list is not set, the default privacy list.
getEffectiveListName
{ "repo_name": "unisontech/Smack", "path": "smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java", "license": "apache-2.0", "size": 22570 }
[ "org.jivesoftware.smack.SmackException", "org.jivesoftware.smack.XMPPException" ]
import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.*;
[ "org.jivesoftware.smack" ]
org.jivesoftware.smack;
2,724,618
public void convert(IProgressMonitor monitor, File from, File to) throws IOException, SAXException, ParserConfigurationException { ReportReaderHandler reportReaderHandler; ReportXMLReader reportXMLReader; boolean success = false; if ((monitor == null) || (from == null) || (to == null)) { throw new IllegalArgumentException(); } if (to.isFile() && !to.canWrite()) { throw new IOException("File " + to.getAbsolutePath() + " is not writable"); } reportReaderHandler = new ReportReaderHandler(monitor, to); reportXMLReader = new ReportXMLReader(reportReaderHandler); try { reportXMLReader.read(from); success = true; } catch (OperationCanceledException e) { success = true; throw e; } finally { try { reportReaderHandler.close(); } catch (IOException e) { success = false; throw e; } finally { if (!success) { to.delete(); } } } } private static class ReportReaderHandler implements ReportReaderClient { private static final int REPORT_THRESHOLD = 500; private static final CPUReport[] CPU_REPORT_TYPE; private static final CPUPriorityReport[] CPU_PRIORITY_REPORT_TYPE; private static final CPUProcessReport[] CPU_PROCESS_REPORT_TYPE; private static final CPUBlockReport[] CPU_BLOCK_REPORT_TYPE; private static final UserReport[] USER_REPORT_TYPE; private final IProgressMonitor monitor; private final File file; private SystemModelDumpFileWriter reportDumpWriter; private List cpuReports; private List cpuPriorityReports; private List cpuProcessReports; private List cpuBlockReports; private List userReports; private boolean processesDone; private boolean blocksDone; private short executionUnit; private int reportNumber; private boolean continuous; private boolean maxMin; private boolean multiple; static { CPU_REPORT_TYPE = new CPUReport[0]; CPU_PRIORITY_REPORT_TYPE = new CPUPriorityReport[0]; CPU_PROCESS_REPORT_TYPE = new CPUProcessReport[0]; CPU_BLOCK_REPORT_TYPE = new CPUBlockReport[0]; USER_REPORT_TYPE = new UserReport[0]; } ReportReaderHandler(IProgressMonitor monitor, File file) throws IOException { this.monitor = monitor; this.file = file; }
void function(IProgressMonitor monitor, File from, File to) throws IOException, SAXException, ParserConfigurationException { ReportReaderHandler reportReaderHandler; ReportXMLReader reportXMLReader; boolean success = false; if ((monitor == null) (from == null) (to == null)) { throw new IllegalArgumentException(); } if (to.isFile() && !to.canWrite()) { throw new IOException(STR + to.getAbsolutePath() + STR); } reportReaderHandler = new ReportReaderHandler(monitor, to); reportXMLReader = new ReportXMLReader(reportReaderHandler); try { reportXMLReader.read(from); success = true; } catch (OperationCanceledException e) { success = true; throw e; } finally { try { reportReaderHandler.close(); } catch (IOException e) { success = false; throw e; } finally { if (!success) { to.delete(); } } } } private static class ReportReaderHandler implements ReportReaderClient { private static final int REPORT_THRESHOLD = 500; private static final CPUReport[] CPU_REPORT_TYPE; private static final CPUPriorityReport[] CPU_PRIORITY_REPORT_TYPE; private static final CPUProcessReport[] CPU_PROCESS_REPORT_TYPE; private static final CPUBlockReport[] CPU_BLOCK_REPORT_TYPE; private static final UserReport[] USER_REPORT_TYPE; private final IProgressMonitor monitor; private final File file; private SystemModelDumpFileWriter reportDumpWriter; private List cpuReports; private List cpuPriorityReports; private List cpuProcessReports; private List cpuBlockReports; private List userReports; private boolean processesDone; private boolean blocksDone; private short executionUnit; private int reportNumber; private boolean continuous; private boolean maxMin; private boolean multiple; static { CPU_REPORT_TYPE = new CPUReport[0]; CPU_PRIORITY_REPORT_TYPE = new CPUPriorityReport[0]; CPU_PROCESS_REPORT_TYPE = new CPUProcessReport[0]; CPU_BLOCK_REPORT_TYPE = new CPUBlockReport[0]; USER_REPORT_TYPE = new UserReport[0]; } ReportReaderHandler(IProgressMonitor monitor, File file) throws IOException { this.monitor = monitor; this.file = file; }
/** * Convert a profiling report XML file to a profiling report dump file. * * @param monitor the progress monitor used for cancellation. * @param from the input profiling report XML file. * @param to the output profiling report dump file. * @throws IOException if an I/O exception occurred. * @throws SAXException if an XML parsing exception occurred. * @throws ParserConfigurationException if an XML parser configuration * exception occurred. */
Convert a profiling report XML file to a profiling report dump file
convert
{ "repo_name": "debabratahazra/OptimaLA", "path": "Optima/com.ose.prof.ui/src/com/ose/prof/format/ReportXMLDumpConverter.java", "license": "epl-1.0", "size": 24934 }
[ "com.ose.system.CPUBlockReport", "com.ose.system.CPUPriorityReport", "com.ose.system.CPUProcessReport", "com.ose.system.CPUReport", "com.ose.system.SystemModelDumpFileWriter", "com.ose.system.UserReport", "java.io.File", "java.io.IOException", "java.util.List", "javax.xml.parsers.ParserConfigurationException", "org.eclipse.core.runtime.IProgressMonitor", "org.eclipse.core.runtime.OperationCanceledException", "org.xml.sax.SAXException" ]
import com.ose.system.CPUBlockReport; import com.ose.system.CPUPriorityReport; import com.ose.system.CPUProcessReport; import com.ose.system.CPUReport; import com.ose.system.SystemModelDumpFileWriter; import com.ose.system.UserReport; import java.io.File; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.xml.sax.SAXException;
import com.ose.system.*; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.eclipse.core.runtime.*; import org.xml.sax.*;
[ "com.ose.system", "java.io", "java.util", "javax.xml", "org.eclipse.core", "org.xml.sax" ]
com.ose.system; java.io; java.util; javax.xml; org.eclipse.core; org.xml.sax;
1,039,266
@Override public Value evalArray(Env env) { Value array = _expr.evalArray(env); Value index = _index.eval(env); return array.getArray(index); }
Value function(Env env) { Value array = _expr.evalArray(env); Value index = _index.eval(env); return array.getArray(index); }
/** * Evaluates the expression, creating an array if the value is unset.. * * @param env the calling environment. * * @return the expression value. */
Evaluates the expression, creating an array if the value is unset.
evalArray
{ "repo_name": "dwango/quercus", "path": "src/main/java/com/caucho/quercus/expr/ArrayGetExpr.java", "license": "gpl-2.0", "size": 5251 }
[ "com.caucho.quercus.env.Env", "com.caucho.quercus.env.Value" ]
import com.caucho.quercus.env.Env; import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.*;
[ "com.caucho.quercus" ]
com.caucho.quercus;
2,594,763
@BeforeClass public static void setupClass() throws Exception { config = ConfigUtility.getConfigProperties(); } // Vars for test final Map<String, List<IcdMap>> icd11Map = new TreeMap<>(); final Map<String, String> icd11MapNotes = new TreeMap<>(); final Map<String, String> sctConcepts = new HashMap<>(); final Map<String, List<IcdMap>> icd11MapEdits = new HashMap<>(); final Map<String, String> icd11Concepts = new HashMap<>(); final Map<String, Set<String>> icd11ParChd = new HashMap<>(); final Map<String, Set<String>> icd11Index = new HashMap<>(); final Map<String, String> icd10Concepts = new HashMap<>(); final Map<String, List<IcdMap>> icd10Map = new HashMap<>(); final Map<String, Set<String>> sctAncDesc = new HashMap<>(); final Map<String, Set<String>> sctDescAnc = new HashMap<>(); final Map<String, Set<String>> sctChdPar = new HashMap<>(); final Map<String, String> xtConcepts = new HashMap<>(); final Map<String, Set<WhoMap>> icd10To11 = new HashMap<>(); final Map<String, Set<WhoMap>> icd11To10Reverse = new HashMap<>(); final Map<String, List<Score>> sctIcd11Matches = new HashMap<>(); final List<String> sctScope = new ArrayList<>(); final List<String> starterSet = new ArrayList<>(); final Set<String> icd11Scope = new HashSet<>(); final Map<String, Set<String>> sctIcd11Equivalence = new HashMap<>(); final Map<String, String> sctIcd11EquivalenceType = new HashMap<>(); final Map<String, String> icd11BodyPartMap = new HashMap<>(); final Map<String, Set<String>> bodyPartIcd11Map = new HashMap<>(); final Map<String, String> sctBodyPartMap = new HashMap<>(); final Map<String, Set<String>> bodyPartSctMap = new HashMap<>(); // Vars final Set<String> advicesToExclude = new HashSet<>(Arrays.asList(new String[] { "THIS CODE MAY BE USED IN THE PRIMARY POSITION WHEN THE MANIFESTATION IS THE PRIMARY FOCUS OF CARE", "THIS MAP REQUIRES A DAGGER CODE AS WELL AS AN ASTERISK CODE", "FIFTH CHARACTER REQUIRED TO FURTHER SPECIFY THE SITE", "POSSIBLE REQUIREMENT FOR MORPHOLOGY CODE", "THIS CODE MAY BE USED IN THE PRIMARY POSITION WHEN THE MANIFESTATION IS THE PRIMARY FOCUS OF CARE", "THIS MAP REQUIRES A DAGGER CODE AS WELL AS AN ASTERISK CODE", "USE AS PRIMARY CODE ONLY IF SITE OF BURN UNSPECIFIED, OTHERWISE USE AS A SUPPLEMENTARY CODE WITH CATEGORIES T20-T29 (Burns)" })); final Map<String, String> advicesToReplace = new HashMap<>(); // Initializer { advicesToReplace.put( "POSSIBLE REQUIREMENT FOR ADDITIONAL CODE TO FULLY DESCRIBE DISEASE OR CONDITION", "ADDITIONAL CODES MAY BE ADDED AS SANCTIONED BY WHO"); advicesToReplace.put("POSSIBLE REQUIREMENT FOR AN EXTERNAL CAUSE CODE", "CODES SANCTIONED BY WHO MAY BE ADDED FROM CHAPTER 23 EXTERNAL CAUSES AND EXTENSION CODES IF RELEVANT"); advicesToReplace.put("POSSIBLE REQUIREMENT FOR CAUSATIVE AGENT CODE", "POSSIBLE REQUIREMENT FOR INFECTIOUS AGENT EXTENSION CODE"); advicesToReplace.put("POSSIBLE REQUIREMENT FOR PLACE OF OCCURRENCE", "EXTENSION CODES SANCTIONED BY WHO MAY BE ADDED IF RELEVANT"); advicesToReplace.put( "THIS IS AN EXTERNAL CAUSE CODE FOR USE IN A SECONDARY POSITION", "THIS IS AN EXTERNAL CAUSE CODE AND/OR EXTENSION CODE FOR USE IN A SECONDARY POSITION"); } final int sampleCt = 5; StringBuilder noteSb = null;
static void function() throws Exception { config = ConfigUtility.getConfigProperties(); } final Map<String, List<IcdMap>> icd11Map = new TreeMap<>(); final Map<String, String> icd11MapNotes = new TreeMap<>(); final Map<String, String> sctConcepts = new HashMap<>(); final Map<String, List<IcdMap>> icd11MapEdits = new HashMap<>(); final Map<String, String> icd11Concepts = new HashMap<>(); final Map<String, Set<String>> icd11ParChd = new HashMap<>(); final Map<String, Set<String>> icd11Index = new HashMap<>(); final Map<String, String> icd10Concepts = new HashMap<>(); final Map<String, List<IcdMap>> icd10Map = new HashMap<>(); final Map<String, Set<String>> sctAncDesc = new HashMap<>(); final Map<String, Set<String>> sctDescAnc = new HashMap<>(); final Map<String, Set<String>> sctChdPar = new HashMap<>(); final Map<String, String> xtConcepts = new HashMap<>(); final Map<String, Set<WhoMap>> icd10To11 = new HashMap<>(); final Map<String, Set<WhoMap>> icd11To10Reverse = new HashMap<>(); final Map<String, List<Score>> sctIcd11Matches = new HashMap<>(); final List<String> sctScope = new ArrayList<>(); final List<String> starterSet = new ArrayList<>(); final Set<String> icd11Scope = new HashSet<>(); final Map<String, Set<String>> sctIcd11Equivalence = new HashMap<>(); final Map<String, String> sctIcd11EquivalenceType = new HashMap<>(); final Map<String, String> icd11BodyPartMap = new HashMap<>(); final Map<String, Set<String>> bodyPartIcd11Map = new HashMap<>(); final Map<String, String> sctBodyPartMap = new HashMap<>(); final Map<String, Set<String>> bodyPartSctMap = new HashMap<>(); final Set<String> advicesToExclude = new HashSet<>(Arrays.asList(new String[] { STR, STR, STR, STR, STR, STR, STR })); final Map<String, String> advicesToReplace = new HashMap<>(); { advicesToReplace.put( STR, STR); advicesToReplace.put(STR, STR); advicesToReplace.put(STR, STR); advicesToReplace.put(STR, STR); advicesToReplace.put( STR, STR); } final int sampleCt = 5; StringBuilder noteSb = null;
/** * Create test fixtures for class. * * @throws Exception the exception */
Create test fixtures for class
setupClass
{ "repo_name": "IHTSDO/OTF-Mapping-Service", "path": "integration-tests/src/test/java/org/ihtsdo/otf/mapping/test/mojo/ComputeIcd11Map2.java", "license": "apache-2.0", "size": 104690 }
[ "java.util.ArrayList", "java.util.Arrays", "java.util.HashMap", "java.util.HashSet", "java.util.List", "java.util.Map", "java.util.Set", "java.util.TreeMap", "org.ihtsdo.otf.mapping.services.helpers.ConfigUtility" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility;
import java.util.*; import org.ihtsdo.otf.mapping.services.helpers.*;
[ "java.util", "org.ihtsdo.otf" ]
java.util; org.ihtsdo.otf;
2,543,872
private void restoreRequestAttribute(final HttpServletRequest request, final HttpSession session, final String name) { final String value = (String) session.getAttribute(name); request.setAttribute(name, value); }
void function(final HttpServletRequest request, final HttpSession session, final String name) { final String value = (String) session.getAttribute(name); request.setAttribute(name, value); }
/** * Restore an attribute in web session as an attribute in request. * * @param request * @param session * @param name */
Restore an attribute in web session as an attribute in request
restoreRequestAttribute
{ "repo_name": "yangjisheng/ServerCAS", "path": "cas-server-support-oauth/src/main/java/org/jasig/cas/support/oauth/web/flow/OAuthAction.java", "license": "apache-2.0", "size": 8352 }
[ "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpSession" ]
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;
import javax.servlet.http.*;
[ "javax.servlet" ]
javax.servlet;
332,086
protected AdhocQueryRequest createAdhocQueryRequestByDocumentId(String documentId, String repositoryId) { log.debug("Begin createAdhocQueryRequestByDocumentId"); AdhocQueryRequest request = null; try { if ((documentId != null) && (repositoryId != null)) { QueryUtil util = new QueryUtil(); request = util.createPatientIdQuery(documentId, repositoryId); } } catch (Exception e) { log.error("Error creating query by document id message: " + e.getMessage(), e); } log.debug("End createAdhocQueryRequestByDocumentId"); return request; }
AdhocQueryRequest function(String documentId, String repositoryId) { log.debug(STR); AdhocQueryRequest request = null; try { if ((documentId != null) && (repositoryId != null)) { QueryUtil util = new QueryUtil(); request = util.createPatientIdQuery(documentId, repositoryId); } } catch (Exception e) { log.error(STR + e.getMessage(), e); } log.debug(STR); return request; }
/** * Adhoc Query Request is created based on the Patient Id and Assigning Authority * * @param sPatId * @param sAA * @return AdhocQueryRequest */
Adhoc Query Request is created based on the Patient Id and Assigning Authority
createAdhocQueryRequestByDocumentId
{ "repo_name": "alameluchidambaram/CONNECT", "path": "Product/Production/Services/SharedEngineCore/src/main/java/gov/hhs/fha/nhinc/redactionengine/adapter/DocRetrieveResponseProcessor.java", "license": "bsd-3-clause", "size": 18168 }
[ "gov.hhs.fha.nhinc.policyengine.adapter.pip.QueryUtil" ]
import gov.hhs.fha.nhinc.policyengine.adapter.pip.QueryUtil;
import gov.hhs.fha.nhinc.policyengine.adapter.pip.*;
[ "gov.hhs.fha" ]
gov.hhs.fha;
2,148,540
public static void setVariableValueToObject( Object object, String variable, Object value ) throws IllegalAccessException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( variable, object.getClass() ); field.setAccessible( true ); field.set( object, value ); }
static void function( Object object, String variable, Object value ) throws IllegalAccessException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( variable, object.getClass() ); field.setAccessible( true ); field.set( object, value ); }
/** * convience method to set values to variables in objects that don't have * setters * * @param object * @param variable * @param value * @throws IllegalAccessException */
convience method to set values to variables in objects that don't have setters
setVariableValueToObject
{ "repo_name": "kidaa/maven-plugins", "path": "maven-dependency-plugin/src/test/java/org/apache/maven/plugins/dependency/testUtils/DependencyTestUtils.java", "license": "apache-2.0", "size": 3776 }
[ "java.lang.reflect.Field", "org.codehaus.plexus.util.ReflectionUtils" ]
import java.lang.reflect.Field; import org.codehaus.plexus.util.ReflectionUtils;
import java.lang.reflect.*; import org.codehaus.plexus.util.*;
[ "java.lang", "org.codehaus.plexus" ]
java.lang; org.codehaus.plexus;
2,890,922
@FIXVersion(introduced="4.3") @TagNumRef(tagNum=TagNum.NoLegs) public Integer getNoLegs() { throw new UnsupportedOperationException(getUnsupportedTagMessage()); }
@FIXVersion(introduced="4.3") @TagNumRef(tagNum=TagNum.NoLegs) Integer function() { throw new UnsupportedOperationException(getUnsupportedTagMessage()); }
/** * Message field getter. * @return field value */
Message field getter
getNoLegs
{ "repo_name": "marvisan/HadesFIX", "path": "Model/src/main/java/net/hades/fix/message/SecurityDefinitionMsg.java", "license": "gpl-3.0", "size": 67355 }
[ "net.hades.fix.message.anno.FIXVersion", "net.hades.fix.message.anno.TagNumRef", "net.hades.fix.message.type.TagNum" ]
import net.hades.fix.message.anno.FIXVersion; import net.hades.fix.message.anno.TagNumRef; import net.hades.fix.message.type.TagNum;
import net.hades.fix.message.anno.*; import net.hades.fix.message.type.*;
[ "net.hades.fix" ]
net.hades.fix;
2,122,476
private void parse() throws IOException { if ((gridFile == null) || !gridFile.exists()) { System.err.println("No existing file specified."); System.exit(1); } BufferedReader reader = null; try { if (encoding == null) { reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile))); } else { try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile), encoding)); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding: " + uee.getMessage()); reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile))); } } // Praat files on Windows and Linux are created with encoding // "Cp1252" // on Mac with encoding "MacRoman". The ui could/should be extended // with an option to specify the encoding // InputStreamReader isr = new InputStreamReader( // new FileInputStream(gridFile)); // System.out.println("Encoding: " + isr.getEncoding()); // System.out.println("Read encoding: " + encoding); if (verbose) System.out.println("Read encoding: " + encoding); boolean isShortNotation = isShortNotation(reader); if (verbose) System.out.println("Praat TextGrid is in short notation: " + isShortNotation); if (isShortNotation) { parseShortNotation(reader); return; } tierNames = new LinkedHashMap<String, String>(); annotationMap = new HashMap<String, ArrayList<Annot>>(); ArrayList<Annot> records = new ArrayList<Annot>(); Annot record = null; String line; // int lineNum = 0; String tierName = null; String annValue = ""; String begin = "-1"; String end = "-1"; boolean inTier = false; boolean inInterval = false; boolean inTextTier = false; boolean inPoints = false; int eqPos = -1; while ((line = reader.readLine()) != null) { // lineNum++; // System.out.println(lineNum + " " + line); if ((line.indexOf(cl) >= 0) && ((line.indexOf(tierSpec) > 5) || (line.indexOf(textTierSpec) > 5))) { // check if we have to include text (point) tiers if (line.indexOf(textTierSpec) > 5) { if (includeTextTiers) { inTextTier = true; } else { inTextTier = false; inTier = false; continue; } } // begin of a new tier records = new ArrayList<Annot>(); inTier = true; continue; } if (!inTier) { continue; } eqPos = line.indexOf(eq); if (inTextTier) { // text or point tier if (eqPos > 0) { // split and parse if (!inPoints && (line.indexOf(nm) >= 0) && (line.indexOf(nm) < eqPos)) { tierName = extractTierName(line, eqPos); if (!annotationMap.containsKey(tierName)) { annotationMap.put(tierName, records); tierNames.put(tierName, "TextTier"); if (verbose) System.out.println("Point Tier detected: " + tierName); } else { // the same (sometimes empty) tiername can occur // more than once, rename int count = 2; String nextName = ""; for (; count < 50; count++) { nextName = tierName + "-" + count; if (!annotationMap.containsKey(nextName)) { annotationMap.put(nextName, records); tierNames.put(nextName, "TextTier"); if (verbose) System.out.println( "Point Tier detected: " + tierName + " and renamed to: " + nextName); break; } } } continue; } else if (!inPoints) { continue; } else if (line.indexOf(time) > -1 || line.indexOf(number) > -1) { begin = extractTime(line, eqPos); // System.out.println("B: " + begin); } else if (line.indexOf(mark) > -1) { // extract value annValue = extractTextValue(line, eqPos); // finish and add the annotation record inPoints = false; // System.out.println("T: " + annValue); record = new Annot(tierName, annValue, begin, "-1" ); records.add(record); // reset annValue = ""; begin = "-1"; } } else { // points?? if ((line.indexOf(points) >= 0) && (line.indexOf(brack) > points.length())) { inPoints = true; continue; } else { if ((line.indexOf(item) >= 0) && (line.indexOf(brack) > item.length())) { // reset inTextTier = false; inPoints = false; } } } // end point tier } else { // interval tier if (eqPos > 0) { // split and parse if (!inInterval && (line.indexOf(nm) >= 0) && (line.indexOf(nm) < eqPos)) { tierName = extractTierName(line, eqPos); if (!annotationMap.containsKey(tierName)) { annotationMap.put(tierName, records); tierNames.put(tierName, "IntervalTier"); if (verbose) System.out.println("Tier detected: " + tierName); } else { // the same (sometimes empty) tiername can occur // more than once, rename int count = 2; String nextName = ""; for (; count < 50; count++) { nextName = tierName + "-" + count; if (!annotationMap.containsKey(nextName)) { annotationMap.put(nextName, records); tierNames.put(nextName, "IntervalTier"); if (verbose) System.out .println("Tier detected: " + tierName + " and renamed to: " + nextName); break; } } } continue; } else if (!inInterval) { continue; } else if (line.indexOf(min) > -1) { begin = extractTime(line, eqPos); // System.out.println("B: " + begin); } else if (line.indexOf(max) > -1) { end = extractTime(line, eqPos); // System.out.println("E: " + end); } else if (line.indexOf(tx) > -1) { // extract value annValue = extractTextValue(line, eqPos); // finish and add the annotation record inInterval = false; // System.out.println("T: " + annValue); record = new Annot(tierName, annValue, begin, end); if (Utils.isNotEmptyOrNull(annValue)) { records.add(record); } // reset annValue = ""; begin = "-1"; end = "-1"; } } else { // interval? if ((line.indexOf(interval) >= 0) && (line.indexOf(brack) > interval.length())) { inInterval = true; continue; } else { if ((line.indexOf(item) >= 0) && (line.indexOf(brack) > item.length())) { // reset inTier = false; inInterval = false; } } } } } reader.close(); } catch (IOException ioe) { if (reader != null) { reader.close(); } throw ioe; } catch (Exception fe) { if (reader != null) { reader.close(); } fe.printStackTrace(); throw new IOException("Error occurred while reading the file: " + fe.getMessage()); } }
void function() throws IOException { if ((gridFile == null) !gridFile.exists()) { System.err.println(STR); System.exit(1); } BufferedReader reader = null; try { if (encoding == null) { reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile))); } else { try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile), encoding)); } catch (UnsupportedEncodingException uee) { System.err.println(STR + uee.getMessage()); reader = new BufferedReader(new InputStreamReader(new FileInputStream(gridFile))); } } if (verbose) System.out.println(STR + encoding); boolean isShortNotation = isShortNotation(reader); if (verbose) System.out.println(STR + isShortNotation); if (isShortNotation) { parseShortNotation(reader); return; } tierNames = new LinkedHashMap<String, String>(); annotationMap = new HashMap<String, ArrayList<Annot>>(); ArrayList<Annot> records = new ArrayList<Annot>(); Annot record = null; String line; String tierName = null; String annValue = STR-1STR-1STRTextTierSTRPoint Tier detected: STRSTR-STRTextTierSTRPoint Tier detected: STR and renamed to: STR-1STRSTR-1STRIntervalTierSTRTier detected: STRSTR-STRIntervalTierSTRTier detected: STR and renamed to: STRSTR-1STR-1STRError occurred while reading the file: " + fe.getMessage()); } }
/** * Parses the file and extracts interval tiers with their annotations. * * @throws IOException * if the file can not be read for any reason */
Parses the file and extracts interval tiers with their annotations
parse
{ "repo_name": "christopheparisse/tei-corpo", "path": "src/fr/ortolang/teicorpo/PraatToTei.java", "license": "bsd-2-clause", "size": 29852 }
[ "java.io.BufferedReader", "java.io.FileInputStream", "java.io.IOException", "java.io.InputStreamReader", "java.io.UnsupportedEncodingException", "java.util.ArrayList", "java.util.HashMap", "java.util.LinkedHashMap" ]
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
988,971
private String readLine() throws IOException { String line = null; int newLineMatchByteCount; boolean isLastFilePart = no == 1; int i = currentLastBytePos; while (i > -1) { if (!isLastFilePart && i < avoidNewlineSplitBufferSize) { // avoidNewlineSplitBuffer: for all except the last file part we // take a few bytes to the next file part to avoid splitting of newlines createLeftOver(); break; // skip last few bytes and leave it to the next file part } // --- check for newline --- if ((newLineMatchByteCount = getNewLineMatchByteCount(data, i)) > 0 ) { final int lineStart = i + 1; int lineLengthBytes = currentLastBytePos - lineStart + 1; if (lineLengthBytes < 0) { throw new IllegalStateException("Unexpected negative line length="+lineLengthBytes); } byte[] lineData = new byte[lineLengthBytes]; System.arraycopy(data, lineStart, lineData, 0, lineLengthBytes); line = new String(lineData, encoding); currentLastBytePos = i - newLineMatchByteCount; break; // found line } // --- move cursor --- i -= byteDecrement; // --- end of file part handling --- if (i < 0) { createLeftOver(); break; // end of file part } } // --- last file part handling --- if (isLastFilePart && leftOver != null) { // there will be no line break anymore, this is the first line of the file line = new String(leftOver, encoding); leftOver = null; } return line; }
String function() throws IOException { String line = null; int newLineMatchByteCount; boolean isLastFilePart = no == 1; int i = currentLastBytePos; while (i > -1) { if (!isLastFilePart && i < avoidNewlineSplitBufferSize) { createLeftOver(); break; } if ((newLineMatchByteCount = getNewLineMatchByteCount(data, i)) > 0 ) { final int lineStart = i + 1; int lineLengthBytes = currentLastBytePos - lineStart + 1; if (lineLengthBytes < 0) { throw new IllegalStateException(STR+lineLengthBytes); } byte[] lineData = new byte[lineLengthBytes]; System.arraycopy(data, lineStart, lineData, 0, lineLengthBytes); line = new String(lineData, encoding); currentLastBytePos = i - newLineMatchByteCount; break; } i -= byteDecrement; if (i < 0) { createLeftOver(); break; } } if (isLastFilePart && leftOver != null) { line = new String(leftOver, encoding); leftOver = null; } return line; }
/** * Reads a line. * * @return the line or null * @throws IOException if there is an error reading from the file */
Reads a line
readLine
{ "repo_name": "irudyak/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/util/io/GridReversedLinesFileReader.java", "license": "apache-2.0", "size": 12989 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,389,614
public static Tag status(HttpServletResponse response) { return (response != null) ? Tag.of("status", Integer.toString(response.getStatus())) : STATUS_UNKNOWN; } /** * Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the * {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if * available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} * for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
static Tag function(HttpServletResponse response) { return (response != null) ? Tag.of(STR, Integer.toString(response.getStatus())) : STATUS_UNKNOWN; } /** * Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the * {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if * available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} * for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
/** * Creates a {@code status} tag based on the status of the given {@code response}. * @param response the HTTP response * @return the status tag derived from the status of the response */
Creates a status tag based on the status of the given response
status
{ "repo_name": "dreis2211/spring-boot", "path": "spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcTags.java", "license": "apache-2.0", "size": 6853 }
[ "io.micrometer.core.instrument.Tag", "jakarta.servlet.http.HttpServletResponse", "org.springframework.web.servlet.HandlerMapping" ]
import io.micrometer.core.instrument.Tag; import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerMapping;
import io.micrometer.core.instrument.*; import jakarta.servlet.http.*; import org.springframework.web.servlet.*;
[ "io.micrometer.core", "jakarta.servlet.http", "org.springframework.web" ]
io.micrometer.core; jakarta.servlet.http; org.springframework.web;
1,701,734
@Override public void applyTransformToOrigin(INDArray origin,int i, Object valueToApply) { if(valueToApply instanceof IComplexNumber) { if(origin instanceof IComplexNDArray) { IComplexNDArray c2 = (IComplexNDArray) origin; IComplexNumber apply = apply(origin,valueToApply,i); c2.putScalar(i,apply); } else throw new IllegalArgumentException("Unable to apply a non complex number to a real ndarray"); } else { Number f = apply(origin, valueToApply,i); double val = f.doubleValue(); if(Double.isNaN(val) || Double.isInfinite(val)) val = Nd4j.EPS_THRESHOLD; if(origin.data().dataType().equals(DataBuffer.FLOAT)) origin.putScalar(i,val); else origin.putScalar(i,val); } }
void function(INDArray origin,int i, Object valueToApply) { if(valueToApply instanceof IComplexNumber) { if(origin instanceof IComplexNDArray) { IComplexNDArray c2 = (IComplexNDArray) origin; IComplexNumber apply = apply(origin,valueToApply,i); c2.putScalar(i,apply); } else throw new IllegalArgumentException(STR); } else { Number f = apply(origin, valueToApply,i); double val = f.doubleValue(); if(Double.isNaN(val) Double.isInfinite(val)) val = Nd4j.EPS_THRESHOLD; if(origin.data().dataType().equals(DataBuffer.FLOAT)) origin.putScalar(i,val); else origin.putScalar(i,val); } }
/** * Apply the transformation at from[i] using the supplied value * @param origin the origin ndarray * @param i the index of the element to applyTransformToOrigin * @param valueToApply the value to apply to the given index */
Apply the transformation at from[i] using the supplied value
applyTransformToOrigin
{ "repo_name": "wlin12/JNN", "path": "src/org/nd4j/linalg/ops/BaseElementWiseOp.java", "license": "apache-2.0", "size": 4198 }
[ "org.nd4j.linalg.api.buffer.DataBuffer", "org.nd4j.linalg.api.complex.IComplexNDArray", "org.nd4j.linalg.api.complex.IComplexNumber", "org.nd4j.linalg.api.ndarray.INDArray", "org.nd4j.linalg.factory.Nd4j" ]
import org.nd4j.linalg.api.buffer.DataBuffer; import org.nd4j.linalg.api.complex.IComplexNDArray; import org.nd4j.linalg.api.complex.IComplexNumber; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.api.buffer.*; import org.nd4j.linalg.api.complex.*; import org.nd4j.linalg.api.ndarray.*; import org.nd4j.linalg.factory.*;
[ "org.nd4j.linalg" ]
org.nd4j.linalg;
2,289,867
public void requestSetVolume(int volume) { if (mPlaybackType == PLAYBACK_TYPE_LOCAL) { try { sStatic.mAudioService.setStreamVolume(mPlaybackStream, volume, 0); } catch (RemoteException e) { Log.e(TAG, "Error setting local stream volume", e); } } else { Log.e(TAG, getClass().getSimpleName() + ".requestSetVolume(): " + "Non-local volume playback on system route? " + "Could not request volume change."); } }
void function(int volume) { if (mPlaybackType == PLAYBACK_TYPE_LOCAL) { try { sStatic.mAudioService.setStreamVolume(mPlaybackStream, volume, 0); } catch (RemoteException e) { Log.e(TAG, STR, e); } } else { Log.e(TAG, getClass().getSimpleName() + STR + STR + STR); } }
/** * Request a volume change for this route. * @param volume value between 0 and getVolumeMax */
Request a volume change for this route
requestSetVolume
{ "repo_name": "haikuowuya/android_system_code", "path": "src/android/media/MediaRouter.java", "license": "apache-2.0", "size": 78874 }
[ "android.os.RemoteException", "android.util.Log" ]
import android.os.RemoteException; import android.util.Log;
import android.os.*; import android.util.*;
[ "android.os", "android.util" ]
android.os; android.util;
2,861,064
List<Truck> findFacebookTrucks();
List<Truck> findFacebookTrucks();
/** * Finds all trucks whose facebook feeds should be scanned */
Finds all trucks whose facebook feeds should be scanned
findFacebookTrucks
{ "repo_name": "aviolette/foodtrucklocator", "path": "main/src/main/java/foodtruck/dao/TruckDAO.java", "license": "mit", "size": 1711 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
82,947
List<Facility> getAssignedFacilities(PerunSession sess, SecurityTeam securityTeam);
List<Facility> getAssignedFacilities(PerunSession sess, SecurityTeam securityTeam);
/** * Get facilities where the security team is assigned * * @param sess * @param securityTeam * @return * * @throws InternalErrorException */
Get facilities where the security team is assigned
getAssignedFacilities
{ "repo_name": "mvocu/perun", "path": "perun-core/src/main/java/cz/metacentrum/perun/core/bl/FacilitiesManagerBl.java", "license": "bsd-2-clause", "size": 34798 }
[ "cz.metacentrum.perun.core.api.Facility", "cz.metacentrum.perun.core.api.PerunSession", "cz.metacentrum.perun.core.api.SecurityTeam", "java.util.List" ]
import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.SecurityTeam; import java.util.List;
import cz.metacentrum.perun.core.api.*; import java.util.*;
[ "cz.metacentrum.perun", "java.util" ]
cz.metacentrum.perun; java.util;
350,158
public void evaluate(ArrayList<String> results, Model model, ArrayList<String> specificPredicateNames) { this.specificPredicateNames = specificPredicateNames; HashSet<PredicateAbstract> hiddenPredicates = model.getAllHiddenPredicates(); ArrayList<String> goldStandard = new ArrayList<String>(); // groundPredicate == GoldStandard. for(PredicateAbstract predAbstr : hiddenPredicates) { if(predAbstr.getClass().equals(Predicate.class)) { // if specificPredicateName is empty, then choose everything. if(specificPredicateNames.size() == 0 || specificPredicateNames.contains(predAbstr.getName())) { Predicate pred = (Predicate) predAbstr; ArrayList<String[]> goldGroundValues = pred.getGroundValues(); if(goldGroundValues.size() == 0) { System.err.println("Warning: No ground values (gold standard) for Predicate " + pred.getName() + " found. All results concerning this predicate will be assigned to false negatives."); } for(String[] goldArray : goldGroundValues) { String goldStandardValue = transformGroundValue(pred.getName(), goldArray); goldStandard.add(goldStandardValue); } } else { // System.err.println("Predicate " + specificPredicateName + " does not exist. Precision, Recall and F-Measure will be 0."); } } } ArrayList<String> resultsWithNewPredNames = new ArrayList<String>(); if(specificPredicateNames != null) { for(String result : results) { String resPredName = result.split("\\|")[0]; for(String predName : specificPredicateNames) { if(resPredName.equals(predName)) { resultsWithNewPredNames.add(result); } } } } else { resultsWithNewPredNames = results; } this.evaluate(resultsWithNewPredNames, goldStandard); }
void function(ArrayList<String> results, Model model, ArrayList<String> specificPredicateNames) { this.specificPredicateNames = specificPredicateNames; HashSet<PredicateAbstract> hiddenPredicates = model.getAllHiddenPredicates(); ArrayList<String> goldStandard = new ArrayList<String>(); for(PredicateAbstract predAbstr : hiddenPredicates) { if(predAbstr.getClass().equals(Predicate.class)) { if(specificPredicateNames.size() == 0 specificPredicateNames.contains(predAbstr.getName())) { Predicate pred = (Predicate) predAbstr; ArrayList<String[]> goldGroundValues = pred.getGroundValues(); if(goldGroundValues.size() == 0) { System.err.println(STR + pred.getName() + STR); } for(String[] goldArray : goldGroundValues) { String goldStandardValue = transformGroundValue(pred.getName(), goldArray); goldStandard.add(goldStandardValue); } } else { } } } ArrayList<String> resultsWithNewPredNames = new ArrayList<String>(); if(specificPredicateNames != null) { for(String result : results) { String resPredName = result.split(STR)[0]; for(String predName : specificPredicateNames) { if(resPredName.equals(predName)) { resultsWithNewPredNames.add(result); } } } } else { resultsWithNewPredNames = results; } this.evaluate(resultsWithNewPredNames, goldStandard); }
/** * Evaluates the results. Thereby, the ground values of the hidden predicates are * used as gold standard. * * @param specificPredicateName * If you want to evaluate it only for a specific predicate, just plug in the name of the predicate here. * @param results * @param model */
Evaluates the results. Thereby, the ground values of the hidden predicates are used as gold standard
evaluate
{ "repo_name": "jnoessner/rockIt", "path": "src/main/java/com/googlecode/rockit/app/evaluator/PrecisionRecallEvaluator.java", "license": "gpl-3.0", "size": 10845 }
[ "com.googlecode.rockit.javaAPI.Model", "com.googlecode.rockit.javaAPI.predicates.Predicate", "com.googlecode.rockit.javaAPI.predicates.PredicateAbstract", "java.util.ArrayList", "java.util.HashSet" ]
import com.googlecode.rockit.javaAPI.Model; import com.googlecode.rockit.javaAPI.predicates.Predicate; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; import java.util.ArrayList; import java.util.HashSet;
import com.googlecode.rockit.*; import java.util.*;
[ "com.googlecode.rockit", "java.util" ]
com.googlecode.rockit; java.util;
2,028,363
@Cold public Single<OfflineArea> getOfflineArea(String offlineAreaId) { return localDataStore.getOfflineAreaById(offlineAreaId); }
Single<OfflineArea> function(String offlineAreaId) { return localDataStore.getOfflineAreaById(offlineAreaId); }
/** * Fetches a single offline area by ID. Triggers `onError` when the area is not found. Triggers * `onSuccess` when the area is found. */
Fetches a single offline area by ID. Triggers `onError` when the area is not found. Triggers `onSuccess` when the area is found
getOfflineArea
{ "repo_name": "google/ground-android", "path": "gnd/src/main/java/com/google/android/gnd/repository/OfflineAreaRepository.java", "license": "apache-2.0", "size": 12464 }
[ "com.google.android.gnd.model.basemap.OfflineArea", "io.reactivex.Single" ]
import com.google.android.gnd.model.basemap.OfflineArea; import io.reactivex.Single;
import com.google.android.gnd.model.basemap.*; import io.reactivex.*;
[ "com.google.android", "io.reactivex" ]
com.google.android; io.reactivex;
789,812
@ApiModelProperty(value = "Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.") public String getStatus() { return status; }
@ApiModelProperty(value = STR) String function() { return status; }
/** * Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.. * @return status **/
Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.
getStatus
{ "repo_name": "docusign/docusign-java-client", "path": "src/main/java/com/docusign/esign/model/LinkedExternalPrimaryAccount.java", "license": "mit", "size": 7137 }
[ "io.swagger.annotations.ApiModelProperty" ]
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
[ "io.swagger.annotations" ]
io.swagger.annotations;
2,609,478
public StringBuilder processPage(String id, String sitemap, String label, EList<Widget> children, boolean async) throws RenderException { String snippet = getSnippet(async ? "layer" : "main"); snippet = snippet.replaceAll("%id%", id); // if the label contains a value span, we remove this span as // the title of a page/layer cannot deal with this // Note: we can have a span here, if the parent widget had a label // with some value defined (e.g. "Windows [%d]"), which getLabel() // will convert into a "Windows <span>5</span>". if (label.contains("[") && label.endsWith("]")) { label = label.replace("[", "").replace("]", ""); } snippet = StringUtils.replace(snippet, "%label%", escapeHtml(label)); snippet = StringUtils.replace(snippet, "%servletname%", WebAppServlet.SERVLET_NAME); snippet = StringUtils.replace(snippet, "%sitemap%", sitemap); snippet = StringUtils.replace(snippet, "%htmlclass%", config.getCssClassList()); snippet = StringUtils.replace(snippet, "%icon_type%", config.getIconType()); String[] parts = snippet.split("%children%"); StringBuilder pre_children = new StringBuilder(parts[0]); StringBuilder post_children = new StringBuilder(parts[1]); if (parts.length == 2) { processChildren(pre_children, post_children, children); } else if (parts.length > 2) { logger.error("Snippet '{}' contains multiple %children% sections, but only one is allowed!", async ? "layer" : "main"); } return pre_children.append(post_children); }
StringBuilder function(String id, String sitemap, String label, EList<Widget> children, boolean async) throws RenderException { String snippet = getSnippet(async ? "layerSTRmain"); snippet = snippet.replaceAll("%id%", id); if (label.contains("[") && label.endsWith("]")) { label = label.replace("[", STR]STRSTR%label%STR%servletname%STR%sitemap%STR%htmlclass%STR%icon_type%STR%children%STRSnippet '{}' contains multiple %children% sections, but only one is allowed!STRlayerSTRmain"); } return pre_children.append(post_children); }
/** * This is the main method, which is called to produce the HTML code for a servlet request. * * @param id the id of the parent widget whose children are about to appear on this page * @param sitemap the sitemap to use * @param label the title of this page * @param children a list of widgets that should appear on this page * @param async true, if this is an asynchronous request. This will use a different HTML skeleton * @return a string builder with the produced HTML code * @throws RenderException if an error occurs during the processing */
This is the main method, which is called to produce the HTML code for a servlet request
processPage
{ "repo_name": "marinmitev/smarthome", "path": "extensions/ui/org.eclipse.smarthome.ui.basic/src/main/java/org/eclipse/smarthome/ui/basic/internal/render/PageRenderer.java", "license": "epl-1.0", "size": 9325 }
[ "org.eclipse.emf.common.util.EList", "org.eclipse.smarthome.model.sitemap.Widget", "org.eclipse.smarthome.ui.basic.render.RenderException" ]
import org.eclipse.emf.common.util.EList; import org.eclipse.smarthome.model.sitemap.Widget; import org.eclipse.smarthome.ui.basic.render.RenderException;
import org.eclipse.emf.common.util.*; import org.eclipse.smarthome.model.sitemap.*; import org.eclipse.smarthome.ui.basic.render.*;
[ "org.eclipse.emf", "org.eclipse.smarthome" ]
org.eclipse.emf; org.eclipse.smarthome;
1,345,864
private List<String> buildKillerList(String killerName) { KillerList killers = new KillerList(); for (Entry<Entity, Integer> entry : damageReceived.entrySet()) { final int damageDone = entry.getValue(); if (damageDone == 0) { continue; } killers.addEntity(entry.getKey()); } if (killerName != null) { killers.setKiller(killerName); } return killers.asList(); }
List<String> function(String killerName) { KillerList killers = new KillerList(); for (Entry<Entity, Integer> entry : damageReceived.entrySet()) { final int damageDone = entry.getValue(); if (damageDone == 0) { continue; } killers.addEntity(entry.getKey()); } if (killerName != null) { killers.setKiller(killerName); } return killers.asList(); }
/** * Build a list of killer names. * * @param killerName The "official" killer. This will be always included in * the list * @return list of killers */
Build a list of killer names
buildKillerList
{ "repo_name": "markuskeunecke/stendhal", "path": "src/games/stendhal/server/entity/RPEntity.java", "license": "gpl-2.0", "size": 87393 }
[ "java.util.List", "java.util.Map" ]
import java.util.List; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,020,590
public void assertIsSorted(AssertionInfo info, double[] actual) { arrays.assertIsSorted(info, failures, actual); }
void function(AssertionInfo info, double[] actual) { arrays.assertIsSorted(info, failures, actual); }
/** * Concrete implementation of {@link ArraySortedAssert#isSorted()}. * * @param info contains information about the assertion. * @param actual the given array. */
Concrete implementation of <code>ArraySortedAssert#isSorted()</code>
assertIsSorted
{ "repo_name": "yurloc/assertj-core", "path": "src/main/java/org/assertj/core/internal/DoubleArrays.java", "license": "apache-2.0", "size": 14215 }
[ "org.assertj.core.api.AssertionInfo" ]
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.api.*;
[ "org.assertj.core" ]
org.assertj.core;
2,627,951
InputStream wrapInIfNeeded(InputStream in) throws IOException;
InputStream wrapInIfNeeded(InputStream in) throws IOException;
/** * When using native support, return the InputStream to use for reading characters * else return the input stream passed as a parameter. * * @since 2.6 */
When using native support, return the InputStream to use for reading characters else return the input stream passed as a parameter
wrapInIfNeeded
{ "repo_name": "florianerhard/gedi", "path": "GediCore/src/jline/Terminal.java", "license": "apache-2.0", "size": 2352 }
[ "java.io.IOException", "java.io.InputStream" ]
import java.io.IOException; import java.io.InputStream;
import java.io.*;
[ "java.io" ]
java.io;
469,514
int build(MyAccount account, int unread, Uri firstThreadUri) { int convCount = mConversations.size(); Style style = null; CharSequence title, text, ticker; // more than one conversation - use InboxStyle if (convCount > 1) { InboxStyle inboxStyle = new InboxStyle(); // ticker: "X unread messages" ticker = mContext.getResources().getQuantityString(R.plurals.unread_messages, unread, unread); // title title = ticker; // text: comma separated names (TODO RTL?) StringBuilder btext = new StringBuilder(); int count = 0; for (String convId : mConversations.keySet()) { NotificationConversation conv = mConversations.get(convId); count++; // we'll take the last message and user who sent it String lastPeer = ((LinkedList<NotificationConversation.ConversationMessage>) conv.content) .getLast().peer; Contact contact = Contact.findByUserId(mContext, lastPeer); String name = contact.getDisplayName(); if (conv.groupJid != null) { name = mContext.getResources().getString(R.string.notification_group_title, name, (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } // add persons to notification for (String peer : conv.allPeers) { Contact lContact = Contact.findByUserId(mContext, peer); Uri personUri = lContact.getUri(); if (personUri == null && lContact.getNumber() != null) { // no contact uri available, try phone number lookup try { personUri = Uri.parse("tel:" + lContact.getNumber()); } catch (Exception ignored) { } } if (personUri != null) mBuilder.addPerson(personUri.toString()); } if (btext.length() > 0) btext.append(", "); btext.append(name); // inbox line if (count < 5) { SpannableStringBuilder buf = new SpannableStringBuilder(); buf.append(name).append(' '); buf.setSpan(new ForegroundColorSpan(ContextCompat .getColor(mContext, R.color.notification_name_color)), 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // take just the last message buf.append(conv.lastContent); inboxStyle.addLine(buf); } } if (btext.length() > 0) text = btext.toString(); else // TODO i18n text = "(unknown users)"; String summary; int moreCount = mConversations.size() - count; if (moreCount > 0) { summary = mContext.getResources() .getQuantityString(R.plurals.notification_more, moreCount, moreCount); } else { summary = account.getName(); } inboxStyle.setSummaryText(summary); style = inboxStyle; } // one conversation/one group, use MessagingStyle else { NotificationConversation conv = mConversations.values().iterator().next(); List<NotificationConversation.ConversationMessage> content = conv.content; CharSequence last = conv.lastContent; // needed only for custom direct reply SpannableStringBuilder allContent = null; if (!supportsDirectReply()) allContent = new SpannableStringBuilder(); String name = null; // single image media, use big picture style NotificationConversation.ConversationMessage soloMessage = content.get(0); if (unread == 1 && soloMessage.media != null && ImageComponent.supportsMimeType(soloMessage.mime)) { InputStream in = null; try { in = mContext.getContentResolver().openInputStream(soloMessage.media); Bitmap bitmap = MediaStorage.loadBitmapSimple(in); style = new BigPictureStyle() .bigPicture(bitmap); // show the group name next to the sender in this case if (conv.groupJid != null) { Contact contact = Contact.findByUserId(mContext, soloMessage.peer); name = mContext.getResources().getString(R.string.notification_group_title, contact.getDisplayName(), (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } } catch (Exception e) { // unable to load big picture // will go on with normal notification } finally { DataUtils.close(in); } } if (style == null) { MessagingStyle msgStyle = new MessagingStyle(new Person .Builder() .setName(mContext.getString(R.string.person_me)) //.setIcon(...no icon for now) .build() ); int start; for (NotificationConversation.ConversationMessage message : content) { Contact contact = Contact.findByUserId(mContext, message.peer); name = contact.getDisplayName(); String uri = contact.getUri() != null ? contact.getUri().toString() : null; Person person = new Person.Builder() .setName(name) .setUri(uri) .setKey(contact.getJID()) .setIcon(IconCompat.createWithBitmap(contact.getAvatarBitmap(mContext, true))) .build(); msgStyle.addMessage(message.content, message.timestamp, person); if (allContent != null) { if (allContent.length() > 0) allContent.append("\n"); start = allContent.length(); allContent.append(name).append(':').append(' '); allContent.setSpan(new StyleSpan(Typeface.BOLD), start, start + name.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); allContent.append(message.toString()); } } // group ticker if (conv.groupJid != null) { name = mContext.getResources().getString(R.string.notification_group_title, name, (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); msgStyle.setConversationTitle((TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } style = msgStyle; } else if (name == null) { NotificationConversation.ConversationMessage message = content.get(content.size()-1); Contact contact = Contact.findByUserId(mContext, message.peer); name = contact.getDisplayName(); } // name now contains data from the latest message // add people data for (String peer : conv.allPeers) { Contact contact = Contact.findByUserId(mContext, peer); Uri personUri = contact.getUri(); if (personUri == null && contact.getNumber() != null) { // no contact uri available, try phone number lookup try { personUri = Uri.parse("tel:" + contact.getNumber()); } catch (Exception ignored) { } } if (personUri != null) mBuilder.addPerson(personUri.toString()); // avatar (non-group) if (conv.groupJid == null) { // setLargeIcon will resize the icon Bitmap avatar = contact.getAvatarBitmap(mContext, false); mBuilder.setLargeIcon(avatar); } } // group avatar and ticker if (conv.groupJid != null) { // default group avatar Bitmap defaultGroupAvatar = MessageUtils.drawableToBitmap(ContextCompat .getDrawable(mContext, R.drawable.ic_default_group)); if (Contact.isRoundedAvatars()) { Bitmap roundedAvatar = MediaStorage.createRoundBitmap(defaultGroupAvatar); if (roundedAvatar != defaultGroupAvatar) defaultGroupAvatar.recycle(); defaultGroupAvatar = roundedAvatar; } mBuilder.setLargeIcon(defaultGroupAvatar); } SpannableStringBuilder buf = new SpannableStringBuilder(); buf.append(name).append(':').append(' '); buf.setSpan(new StyleSpan(Typeface.BOLD), 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); buf.append(last); ticker = buf; // title title = name; // text text = (unread > 1) ? mContext.getResources().getQuantityString(R.plurals.unread_messages, unread, unread) : last; // mark as read pending intent // TODO this should also be used for messages from a single group Intent markReadIntent = new Intent(ACTION_NOTIFICATION_MARK_READ, firstThreadUri, mContext, NotificationActionReceiver.class); PendingIntent readPendingIntent = PendingIntent.getBroadcast(mContext, 0, markReadIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (supportsDirectReply()) { // pending intent will start a broadcast receiver Intent replyIntent = new Intent(ACTION_NOTIFICATION_REPLY, firstThreadUri, mContext, NotificationActionReceiver.class); PendingIntent replyPendingIntent = PendingIntent .getBroadcast(mContext, 0, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); // reply action mBuilder.addAction(new androidx.core.app.NotificationCompat .Action.Builder(R.drawable.ic_menu_reply, mContext.getString(R.string.reply), replyPendingIntent) .addRemoteInput(NotificationActionReceiver.buildReplyInput(mContext)) .build() ); } else { // pending intent will start a the quick reply dialog long firstThreadId = ContentUris.parseId(firstThreadUri); Intent replyIntent = QuickReplyActivity.getStartIntent(mContext, firstThreadId, allContent); PendingIntent replyPendingIntent = PendingIntent .getActivity(mContext, 0, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); // reply action mBuilder.addAction(R.drawable.ic_menu_reply, mContext.getString(R.string.reply), replyPendingIntent); } mBuilder.addAction(R.drawable.ic_menu_check, mContext.getString(R.string.mark_read), readPendingIntent); } mBuilder.setTicker(ticker); mBuilder.setContentTitle(title); mBuilder.setContentText(text); mBuilder.setStyle(style); mBuilder.setNumber(unread); return convCount; } }
int build(MyAccount account, int unread, Uri firstThreadUri) { int convCount = mConversations.size(); Style style = null; CharSequence title, text, ticker; if (convCount > 1) { InboxStyle inboxStyle = new InboxStyle(); ticker = mContext.getResources().getQuantityString(R.plurals.unread_messages, unread, unread); title = ticker; StringBuilder btext = new StringBuilder(); int count = 0; for (String convId : mConversations.keySet()) { NotificationConversation conv = mConversations.get(convId); count++; String lastPeer = ((LinkedList<NotificationConversation.ConversationMessage>) conv.content) .getLast().peer; Contact contact = Contact.findByUserId(mContext, lastPeer); String name = contact.getDisplayName(); if (conv.groupJid != null) { name = mContext.getResources().getString(R.string.notification_group_title, name, (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } for (String peer : conv.allPeers) { Contact lContact = Contact.findByUserId(mContext, peer); Uri personUri = lContact.getUri(); if (personUri == null && lContact.getNumber() != null) { try { personUri = Uri.parse("tel:" + lContact.getNumber()); } catch (Exception ignored) { } } if (personUri != null) mBuilder.addPerson(personUri.toString()); } if (btext.length() > 0) btext.append(STR); btext.append(name); if (count < 5) { SpannableStringBuilder buf = new SpannableStringBuilder(); buf.append(name).append(' '); buf.setSpan(new ForegroundColorSpan(ContextCompat .getColor(mContext, R.color.notification_name_color)), 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); buf.append(conv.lastContent); inboxStyle.addLine(buf); } } if (btext.length() > 0) text = btext.toString(); else text = STR; String summary; int moreCount = mConversations.size() - count; if (moreCount > 0) { summary = mContext.getResources() .getQuantityString(R.plurals.notification_more, moreCount, moreCount); } else { summary = account.getName(); } inboxStyle.setSummaryText(summary); style = inboxStyle; } else { NotificationConversation conv = mConversations.values().iterator().next(); List<NotificationConversation.ConversationMessage> content = conv.content; CharSequence last = conv.lastContent; SpannableStringBuilder allContent = null; if (!supportsDirectReply()) allContent = new SpannableStringBuilder(); String name = null; NotificationConversation.ConversationMessage soloMessage = content.get(0); if (unread == 1 && soloMessage.media != null && ImageComponent.supportsMimeType(soloMessage.mime)) { InputStream in = null; try { in = mContext.getContentResolver().openInputStream(soloMessage.media); Bitmap bitmap = MediaStorage.loadBitmapSimple(in); style = new BigPictureStyle() .bigPicture(bitmap); if (conv.groupJid != null) { Contact contact = Contact.findByUserId(mContext, soloMessage.peer); name = mContext.getResources().getString(R.string.notification_group_title, contact.getDisplayName(), (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } } catch (Exception e) { } finally { DataUtils.close(in); } } if (style == null) { MessagingStyle msgStyle = new MessagingStyle(new Person .Builder() .setName(mContext.getString(R.string.person_me)) .build() ); int start; for (NotificationConversation.ConversationMessage message : content) { Contact contact = Contact.findByUserId(mContext, message.peer); name = contact.getDisplayName(); String uri = contact.getUri() != null ? contact.getUri().toString() : null; Person person = new Person.Builder() .setName(name) .setUri(uri) .setKey(contact.getJID()) .setIcon(IconCompat.createWithBitmap(contact.getAvatarBitmap(mContext, true))) .build(); msgStyle.addMessage(message.content, message.timestamp, person); if (allContent != null) { if (allContent.length() > 0) allContent.append("\n"); start = allContent.length(); allContent.append(name).append(':').append(' '); allContent.setSpan(new StyleSpan(Typeface.BOLD), start, start + name.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); allContent.append(message.toString()); } } if (conv.groupJid != null) { name = mContext.getResources().getString(R.string.notification_group_title, name, (TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); msgStyle.setConversationTitle((TextUtils.isEmpty(conv.groupSubject) ? mContext.getString(R.string.group_untitled) : conv.groupSubject)); } style = msgStyle; } else if (name == null) { NotificationConversation.ConversationMessage message = content.get(content.size()-1); Contact contact = Contact.findByUserId(mContext, message.peer); name = contact.getDisplayName(); } for (String peer : conv.allPeers) { Contact contact = Contact.findByUserId(mContext, peer); Uri personUri = contact.getUri(); if (personUri == null && contact.getNumber() != null) { try { personUri = Uri.parse("tel:" + contact.getNumber()); } catch (Exception ignored) { } } if (personUri != null) mBuilder.addPerson(personUri.toString()); if (conv.groupJid == null) { Bitmap avatar = contact.getAvatarBitmap(mContext, false); mBuilder.setLargeIcon(avatar); } } if (conv.groupJid != null) { Bitmap defaultGroupAvatar = MessageUtils.drawableToBitmap(ContextCompat .getDrawable(mContext, R.drawable.ic_default_group)); if (Contact.isRoundedAvatars()) { Bitmap roundedAvatar = MediaStorage.createRoundBitmap(defaultGroupAvatar); if (roundedAvatar != defaultGroupAvatar) defaultGroupAvatar.recycle(); defaultGroupAvatar = roundedAvatar; } mBuilder.setLargeIcon(defaultGroupAvatar); } SpannableStringBuilder buf = new SpannableStringBuilder(); buf.append(name).append(':').append(' '); buf.setSpan(new StyleSpan(Typeface.BOLD), 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); buf.append(last); ticker = buf; title = name; text = (unread > 1) ? mContext.getResources().getQuantityString(R.plurals.unread_messages, unread, unread) : last; Intent markReadIntent = new Intent(ACTION_NOTIFICATION_MARK_READ, firstThreadUri, mContext, NotificationActionReceiver.class); PendingIntent readPendingIntent = PendingIntent.getBroadcast(mContext, 0, markReadIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (supportsDirectReply()) { Intent replyIntent = new Intent(ACTION_NOTIFICATION_REPLY, firstThreadUri, mContext, NotificationActionReceiver.class); PendingIntent replyPendingIntent = PendingIntent .getBroadcast(mContext, 0, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.addAction(new androidx.core.app.NotificationCompat .Action.Builder(R.drawable.ic_menu_reply, mContext.getString(R.string.reply), replyPendingIntent) .addRemoteInput(NotificationActionReceiver.buildReplyInput(mContext)) .build() ); } else { long firstThreadId = ContentUris.parseId(firstThreadUri); Intent replyIntent = QuickReplyActivity.getStartIntent(mContext, firstThreadId, allContent); PendingIntent replyPendingIntent = PendingIntent .getActivity(mContext, 0, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.addAction(R.drawable.ic_menu_reply, mContext.getString(R.string.reply), replyPendingIntent); } mBuilder.addAction(R.drawable.ic_menu_check, mContext.getString(R.string.mark_read), readPendingIntent); } mBuilder.setTicker(ticker); mBuilder.setContentTitle(title); mBuilder.setContentText(text); mBuilder.setStyle(style); mBuilder.setNumber(unread); return convCount; } }
/** * Call this when all messages are added. We will fill the builder with * relevant information. * @param account account information * @param unread total number of unread messages * @param firstThreadUri Uri of first conversation, used for reply intent * @return the number of conversations (i.e. threads) involved */
Call this when all messages are added. We will fill the builder with relevant information
build
{ "repo_name": "kontalk/androidclient", "path": "app/src/main/java/org/kontalk/ui/MessagingNotification.java", "license": "gpl-3.0", "size": 53668 }
[ "android.app.PendingIntent", "android.content.ContentUris", "android.content.Intent", "android.graphics.Bitmap", "android.graphics.Typeface", "android.net.Uri", "android.text.Spannable", "android.text.SpannableStringBuilder", "android.text.TextUtils", "android.text.style.ForegroundColorSpan", "android.text.style.StyleSpan", "androidx.core.app.NotificationCompat", "androidx.core.app.Person", "androidx.core.content.ContextCompat", "androidx.core.graphics.drawable.IconCompat", "java.io.InputStream", "java.util.LinkedList", "java.util.List", "org.kontalk.authenticator.MyAccount", "org.kontalk.data.Contact", "org.kontalk.message.ImageComponent", "org.kontalk.service.NotificationActionReceiver", "org.kontalk.util.DataUtils", "org.kontalk.util.MediaStorage", "org.kontalk.util.MessageUtils" ]
import android.app.PendingIntent; import android.content.ContentUris; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Typeface; import android.net.Uri; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import androidx.core.app.NotificationCompat; import androidx.core.app.Person; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.IconCompat; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import org.kontalk.authenticator.MyAccount; import org.kontalk.data.Contact; import org.kontalk.message.ImageComponent; import org.kontalk.service.NotificationActionReceiver; import org.kontalk.util.DataUtils; import org.kontalk.util.MediaStorage; import org.kontalk.util.MessageUtils;
import android.app.*; import android.content.*; import android.graphics.*; import android.net.*; import android.text.*; import android.text.style.*; import androidx.core.app.*; import androidx.core.content.*; import androidx.core.graphics.drawable.*; import java.io.*; import java.util.*; import org.kontalk.authenticator.*; import org.kontalk.data.*; import org.kontalk.message.*; import org.kontalk.service.*; import org.kontalk.util.*;
[ "android.app", "android.content", "android.graphics", "android.net", "android.text", "androidx.core", "java.io", "java.util", "org.kontalk.authenticator", "org.kontalk.data", "org.kontalk.message", "org.kontalk.service", "org.kontalk.util" ]
android.app; android.content; android.graphics; android.net; android.text; androidx.core; java.io; java.util; org.kontalk.authenticator; org.kontalk.data; org.kontalk.message; org.kontalk.service; org.kontalk.util;
270,471
// XML Serialization public XStream getXStreamWriter() { XStream xstream = new XStream(); customizeXstream(xstream); return xstream; }
XStream function() { XStream xstream = new XStream(); customizeXstream(xstream); return xstream; }
/** * gets an <code>XStream</code> writer. Creates, customizes, and returns * <code>XStream</code> for XML serialization * * @pre <code>XStream</code> package is available @post <code>XStream</code> * for XML encoding is returned * * @return <code>XStream</code> - for XML serialization encoding */
gets an <code>XStream</code> writer. Creates, customizes, and returns <code>XStream</code> for XML serialization
getXStreamWriter
{ "repo_name": "bowring/ET_Redux", "path": "src/main/java/org/earthtime/UPb_Redux/pbBlanks/PbBlank.java", "license": "apache-2.0", "size": 21463 }
[ "com.thoughtworks.xstream.XStream" ]
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.*;
[ "com.thoughtworks.xstream" ]
com.thoughtworks.xstream;
1,302,875
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((requestCode == 2) && (resultCode == RESULT_OK)) { Uri uri = data.getData(); try { studentCardBtmp = BitmapUtils.createScaledBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri), 500, 500); } catch (IOException e) { e.printStackTrace(); } studentCardImage.setImageBitmap(studentCardBtmp); } super.onActivityResult(requestCode, resultCode, data); }
void function(int requestCode, int resultCode, Intent data) { if ((requestCode == 2) && (resultCode == RESULT_OK)) { Uri uri = data.getData(); try { studentCardBtmp = BitmapUtils.createScaledBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri), 500, 500); } catch (IOException e) { e.printStackTrace(); } studentCardImage.setImageBitmap(studentCardBtmp); } super.onActivityResult(requestCode, resultCode, data); }
/** * why pick the image cost so much memory * how to get the image effect? * * @param requestCode * @param resultCode * @param data */
why pick the image cost so much memory how to get the image effect
onActivityResult
{ "repo_name": "TonyChiangUSA/UPrint-Orange", "path": "app/src/main/java/com/uprint/android_pack/cloudprint4androidmanager/activity/ImproveInfoActivity.java", "license": "mit", "size": 19340 }
[ "android.content.Intent", "android.net.Uri", "android.provider.MediaStore", "com.uprint.android_pack.cloudprint4androidmanager.utils.BitmapUtils", "java.io.IOException" ]
import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; import com.uprint.android_pack.cloudprint4androidmanager.utils.BitmapUtils; import java.io.IOException;
import android.content.*; import android.net.*; import android.provider.*; import com.uprint.android_pack.cloudprint4androidmanager.utils.*; import java.io.*;
[ "android.content", "android.net", "android.provider", "com.uprint.android_pack", "java.io" ]
android.content; android.net; android.provider; com.uprint.android_pack; java.io;
1,575,420
public Province getProvince();
Province function();
/** * Province or a descendant class like City. */
Province or a descendant class like City
getProvince
{ "repo_name": "eldevanjr/helianto", "path": "helianto-core/src/main/java/org/helianto/core/domain/type/LocationEntity.java", "license": "apache-2.0", "size": 442 }
[ "org.helianto.core.domain.Province" ]
import org.helianto.core.domain.Province;
import org.helianto.core.domain.*;
[ "org.helianto.core" ]
org.helianto.core;
1,309,056
public IoBuffer fetchOutNetBuffer() { IoBuffer answer = outNetBuffer; if (answer == null) { return emptyBuffer; } outNetBuffer = null; return answer.shrink(); }
IoBuffer function() { IoBuffer answer = outNetBuffer; if (answer == null) { return emptyBuffer; } outNetBuffer = null; return answer.shrink(); }
/** * Get encrypted data to be sent. * * @return buffer with data */
Get encrypted data to be sent
fetchOutNetBuffer
{ "repo_name": "chao-sun-kaazing/gateway", "path": "mina.core/core/src/main/java/org/apache/mina/filter/ssl/SslHandler.java", "license": "apache-2.0", "size": 23849 }
[ "org.apache.mina.core.buffer.IoBuffer" ]
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.*;
[ "org.apache.mina" ]
org.apache.mina;
1,842,706
private void clearExceptionalCompletion() { int h = System.identityHashCode(this); final ReentrantLock lock = exceptionTableLock; lock.lock(); try { ExceptionNode[] t = exceptionTable; int i = h & (t.length - 1); ExceptionNode e = t[i]; ExceptionNode pred = null; while (e != null) { ExceptionNode next = e.next; if (e.get() == this) { if (pred == null) t[i] = next; else pred.next = next; break; } pred = e; e = next; } expungeStaleExceptions(); status = 0; } finally { lock.unlock(); } }
void function() { int h = System.identityHashCode(this); final ReentrantLock lock = exceptionTableLock; lock.lock(); try { ExceptionNode[] t = exceptionTable; int i = h & (t.length - 1); ExceptionNode e = t[i]; ExceptionNode pred = null; while (e != null) { ExceptionNode next = e.next; if (e.get() == this) { if (pred == null) t[i] = next; else pred.next = next; break; } pred = e; e = next; } expungeStaleExceptions(); status = 0; } finally { lock.unlock(); } }
/** * Removes exception node and clears status. */
Removes exception node and clears status
clearExceptionalCompletion
{ "repo_name": "s20121035/rk3288_android5.1_repo", "path": "libcore/luni/src/main/java/java/util/concurrent/ForkJoinTask.java", "license": "gpl-3.0", "size": 59895 }
[ "java.util.concurrent.locks.ReentrantLock" ]
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.*;
[ "java.util" ]
java.util;
2,504,083
public static String getDateAsISO8601String(Date date) { return DateFormatUtils.formatUTC(date, DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()); }
static String function(Date date) { return DateFormatUtils.formatUTC(date, DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()); }
/** * Convert a java date into the ISO8601 format YYYYMMDDTHH:mm:ss * in timezone UTC * * @param date the date to convert * @return ISO8601 formatted date as a String */
in timezone UTC
getDateAsISO8601String
{ "repo_name": "0x90sled/droidtowers", "path": "main/source/net/kencochrane/sentry/RavenUtils.java", "license": "mit", "size": 6992 }
[ "java.util.Date", "org.apach3.commons.lang3.time.DateFormatUtils" ]
import java.util.Date; import org.apach3.commons.lang3.time.DateFormatUtils;
import java.util.*; import org.apach3.commons.lang3.time.*;
[ "java.util", "org.apach3.commons" ]
java.util; org.apach3.commons;
1,586,670
protected static byte[] convertToBytes(String value) { return value.getBytes(StandardCharsets.UTF_8); }
static byte[] function(String value) { return value.getBytes(StandardCharsets.UTF_8); }
/** * Method to convert string to UTF-8 bytes. */
Method to convert string to UTF-8 bytes
convertToBytes
{ "repo_name": "b-slim/hive", "path": "ql/src/java/org/apache/hadoop/hive/ql/io/parquet/vector/ParquetDataColumnReaderFactory.java", "license": "apache-2.0", "size": 65428 }
[ "java.nio.charset.StandardCharsets" ]
import java.nio.charset.StandardCharsets;
import java.nio.charset.*;
[ "java.nio" ]
java.nio;
1,757,785
@Override public BindingSet project(Collection<String> vars, BindingSet bindings) { QueryBindingSet q = new QueryBindingSet(); for (String varName : vars) { Binding b = bindings.getBinding(varName); if (b != null) { q.addBinding(b); } } return q; }
BindingSet function(Collection<String> vars, BindingSet bindings) { QueryBindingSet q = new QueryBindingSet(); for (String varName : vars) { Binding b = bindings.getBinding(varName); if (b != null) { q.addBinding(b); } } return q; }
/** * Project a binding set to a potentially smaller binding set that * contain only the variable bindings that are in vars set. * @param bindings * @param vars * @return */
Project a binding set to a potentially smaller binding set that contain only the variable bindings that are in vars set
project
{ "repo_name": "semagrow/semagrow", "path": "core/src/main/java/org/semagrow/evaluation/util/SimpleBindingSetOps.java", "license": "apache-2.0", "size": 2517 }
[ "java.util.Collection", "org.eclipse.rdf4j.query.Binding", "org.eclipse.rdf4j.query.BindingSet", "org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet" ]
import java.util.Collection; import org.eclipse.rdf4j.query.Binding; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
import java.util.*; import org.eclipse.rdf4j.query.*; import org.eclipse.rdf4j.query.algebra.evaluation.*;
[ "java.util", "org.eclipse.rdf4j" ]
java.util; org.eclipse.rdf4j;
1,263,090
private ByteBuffer acquireDirectBuffer(int size, boolean send) { ByteBuffer result; if (useDirectBuffers) { if (size <= MEDIUM_BUFFER_SIZE) { return acquirePredefinedFixedBuffer(send, size); } else { return acquireLargeBuffer(send, size); } } else { // if we are using heap buffers then don't bother with keeping them around result = ByteBuffer.allocate(size); } updateBufferStats(size, send, false); return result; }
ByteBuffer function(int size, boolean send) { ByteBuffer result; if (useDirectBuffers) { if (size <= MEDIUM_BUFFER_SIZE) { return acquirePredefinedFixedBuffer(send, size); } else { return acquireLargeBuffer(send, size); } } else { result = ByteBuffer.allocate(size); } updateBufferStats(size, send, false); return result; }
/** * try to acquire direct buffer, if enabled by configuration */
try to acquire direct buffer, if enabled by configuration
acquireDirectBuffer
{ "repo_name": "davinash/geode", "path": "geode-core/src/main/java/org/apache/geode/internal/net/BufferPool.java", "license": "apache-2.0", "size": 10676 }
[ "java.nio.ByteBuffer" ]
import java.nio.ByteBuffer;
import java.nio.*;
[ "java.nio" ]
java.nio;
2,845,581
public void evictAll() throws IOException { cache.evictAll(); }
void function() throws IOException { cache.evictAll(); }
/** * Deletes all values stored in the cache. In-flight writes to the cache will complete normally, * but the corresponding responses will not be stored. */
Deletes all values stored in the cache. In-flight writes to the cache will complete normally, but the corresponding responses will not be stored
evictAll
{ "repo_name": "caojing35/MustacheWeather", "path": "app/src/main/java/com/mustacheweather/android/util/secure/SecureCache.java", "license": "apache-2.0", "size": 25650 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
417,294
public List<? extends Peer> getSomePeers(TrackedPeer client, int numWant) { numWant = Math.min(numWant, DEFAULT_ANSWER_NUM_PEERS); // Extract answerPeers random peers List<TrackedPeer> candidates = new ArrayList<TrackedPeer>(peers.values()); Collections.shuffle(candidates); List<Peer> out = new ArrayList<Peer>(numWant); long now = System.currentTimeMillis(); // LOG.info("Client PeerAddress is " + client.getPeerAddress()); for (TrackedPeer candidate : candidates) { // LOG.info("Candidate PeerAddress is " + candidate.getPeerAddress()); // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh(now, getPeerExpiryInterval())) { LOG.debug("Collecting stale peer {}...", candidate.getPeerAddresses()); peers.remove(TorrentUtils.toHex(candidate.getPeerId()), candidate); continue; } // Don't include the requesting peer in the answer. if (Arrays.equals(client.getPeerId(), candidate.getPeerId())) { if (!client.equals(candidate)) { LOG.debug("Collecting superceded peer {}...", candidate); removePeer(candidate.getPeerId()); } continue; } for (InetSocketAddress peerAddress : candidate.getPeerAddresses()) out.add(new Peer(peerAddress, candidate.getPeerId())); if (out.size() >= numWant) break; } LOG.trace("Some peers are {}", out); return out; }
List<? extends Peer> function(TrackedPeer client, int numWant) { numWant = Math.min(numWant, DEFAULT_ANSWER_NUM_PEERS); List<TrackedPeer> candidates = new ArrayList<TrackedPeer>(peers.values()); Collections.shuffle(candidates); List<Peer> out = new ArrayList<Peer>(numWant); long now = System.currentTimeMillis(); for (TrackedPeer candidate : candidates) { if (!candidate.isFresh(now, getPeerExpiryInterval())) { LOG.debug(STR, candidate.getPeerAddresses()); peers.remove(TorrentUtils.toHex(candidate.getPeerId()), candidate); continue; } if (Arrays.equals(client.getPeerId(), candidate.getPeerId())) { if (!client.equals(candidate)) { LOG.debug(STR, candidate); removePeer(candidate.getPeerId()); } continue; } for (InetSocketAddress peerAddress : candidate.getPeerAddresses()) out.add(new Peer(peerAddress, candidate.getPeerId())); if (out.size() >= numWant) break; } LOG.trace(STR, out); return out; }
/** * Get a list of peers we can return in an announce response for this * torrent. * * @param peer The peer making the request, so we can exclude it from the * list of returned peers. * @return A list of peers we can include in an announce response. */
Get a list of peers we can return in an announce response for this torrent
getSomePeers
{ "repo_name": "letroll/TtorrentAndroid", "path": "app/src/main/java/fr/letroll/ttorrentandroid/tracker/TrackedTorrent.java", "license": "apache-2.0", "size": 10687 }
[ "fr.letroll.ttorrentandroid.common.Peer", "fr.letroll.ttorrentandroid.common.TorrentUtils", "java.net.InetSocketAddress", "java.util.ArrayList", "java.util.Arrays", "java.util.Collections", "java.util.List" ]
import fr.letroll.ttorrentandroid.common.Peer; import fr.letroll.ttorrentandroid.common.TorrentUtils; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
import fr.letroll.ttorrentandroid.common.*; import java.net.*; import java.util.*;
[ "fr.letroll.ttorrentandroid", "java.net", "java.util" ]
fr.letroll.ttorrentandroid; java.net; java.util;
910,914
private long getFileSize(String fullName) throws IOException { //Manages to find the device's file using the FS long pictureSize; FileAdapter fa = new FileAdapter(fullName); pictureSize = fa.getSize(); fa = null; return pictureSize; }
long function(String fullName) throws IOException { long pictureSize; FileAdapter fa = new FileAdapter(fullName); pictureSize = fa.getSize(); fa = null; return pictureSize; }
/** * Check the size of a file on the file system * @param fullName the file name with path * @return long the size on the file long formatted * @throws IOException if the FileAdapter pointing to the file encounters a * problem */
Check the size of a file on the file system
getFileSize
{ "repo_name": "zhangdakun/funasyn", "path": "src/com/funambol/android/providers/FilesContentProvider.java", "license": "agpl-3.0", "size": 6062 }
[ "com.funambol.platform.FileAdapter", "java.io.IOException" ]
import com.funambol.platform.FileAdapter; import java.io.IOException;
import com.funambol.platform.*; import java.io.*;
[ "com.funambol.platform", "java.io" ]
com.funambol.platform; java.io;
2,323,332
public void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setInteger("DataVersion", 512); compound.setTag("Inventory", this.inventory.writeToNBT(new NBTTagList())); compound.setInteger("SelectedItemSlot", this.inventory.currentItem); compound.setBoolean("Sleeping", this.sleeping); compound.setShort("SleepTimer", (short)this.sleepTimer); compound.setFloat("XpP", this.experience); compound.setInteger("XpLevel", this.experienceLevel); compound.setInteger("XpTotal", this.experienceTotal); compound.setInteger("XpSeed", this.xpSeed); compound.setInteger("Score", this.getScore()); if (this.spawnChunk != null) { compound.setInteger("SpawnX", this.spawnChunk.getX()); compound.setInteger("SpawnY", this.spawnChunk.getY()); compound.setInteger("SpawnZ", this.spawnChunk.getZ()); compound.setBoolean("SpawnForced", this.spawnForced); } NBTTagList spawnlist = new NBTTagList(); for (java.util.Map.Entry<Integer, BlockPos> entry : this.spawnChunkMap.entrySet()) { BlockPos spawn = entry.getValue(); if (spawn == null) continue; Boolean forced = spawnForcedMap.get(entry.getKey()); if (forced == null) forced = false; NBTTagCompound spawndata = new NBTTagCompound(); spawndata.setInteger("Dim", entry.getKey()); spawndata.setInteger("SpawnX", spawn.getX()); spawndata.setInteger("SpawnY", spawn.getY()); spawndata.setInteger("SpawnZ", spawn.getZ()); spawndata.setBoolean("SpawnForced", forced); spawnlist.appendTag(spawndata); } compound.setTag("Spawns", spawnlist); this.foodStats.writeNBT(compound); this.capabilities.writeCapabilitiesToNBT(compound); compound.setTag("EnderItems", this.theInventoryEnderChest.saveInventoryToNBT()); }
void function(NBTTagCompound compound) { super.writeEntityToNBT(compound); compound.setInteger(STR, 512); compound.setTag(STR, this.inventory.writeToNBT(new NBTTagList())); compound.setInteger(STR, this.inventory.currentItem); compound.setBoolean(STR, this.sleeping); compound.setShort(STR, (short)this.sleepTimer); compound.setFloat("XpP", this.experience); compound.setInteger(STR, this.experienceLevel); compound.setInteger(STR, this.experienceTotal); compound.setInteger(STR, this.xpSeed); compound.setInteger("Score", this.getScore()); if (this.spawnChunk != null) { compound.setInteger(STR, this.spawnChunk.getX()); compound.setInteger(STR, this.spawnChunk.getY()); compound.setInteger(STR, this.spawnChunk.getZ()); compound.setBoolean(STR, this.spawnForced); } NBTTagList spawnlist = new NBTTagList(); for (java.util.Map.Entry<Integer, BlockPos> entry : this.spawnChunkMap.entrySet()) { BlockPos spawn = entry.getValue(); if (spawn == null) continue; Boolean forced = spawnForcedMap.get(entry.getKey()); if (forced == null) forced = false; NBTTagCompound spawndata = new NBTTagCompound(); spawndata.setInteger("Dim", entry.getKey()); spawndata.setInteger(STR, spawn.getX()); spawndata.setInteger(STR, spawn.getY()); spawndata.setInteger(STR, spawn.getZ()); spawndata.setBoolean(STR, forced); spawnlist.appendTag(spawndata); } compound.setTag(STR, spawnlist); this.foodStats.writeNBT(compound); this.capabilities.writeCapabilitiesToNBT(compound); compound.setTag(STR, this.theInventoryEnderChest.saveInventoryToNBT()); }
/** * (abstract) Protected helper method to write subclass entity data to NBT. */
(abstract) Protected helper method to write subclass entity data to NBT
writeEntityToNBT
{ "repo_name": "Im-Jrotica/forge_latest", "path": "build/tmp/recompileMc/sources/net/minecraft/entity/player/EntityPlayer.java", "license": "lgpl-2.1", "size": 99086 }
[ "net.minecraft.nbt.NBTTagCompound", "net.minecraft.nbt.NBTTagList", "net.minecraft.scoreboard.Score", "net.minecraft.util.math.BlockPos" ]
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.scoreboard.Score; import net.minecraft.util.math.BlockPos;
import net.minecraft.nbt.*; import net.minecraft.scoreboard.*; import net.minecraft.util.math.*;
[ "net.minecraft.nbt", "net.minecraft.scoreboard", "net.minecraft.util" ]
net.minecraft.nbt; net.minecraft.scoreboard; net.minecraft.util;
1,503,635
@WebMethod(operationName = "deleteDocumentLinksByDocumentId") @XmlElementWrapper(name = "documentLinks", required = true) @XmlElement(name = "documentLink", required = false) @WebResult(name = "documentLinks") List<DocumentLink> deleteDocumentLinksByDocumentId(@WebParam(name = "originatingDocumentId") String originatingDocumentId) throws RiceIllegalArgumentException;
@WebMethod(operationName = STR) @XmlElementWrapper(name = STR, required = true) @XmlElement(name = STR, required = false) @WebResult(name = STR) List<DocumentLink> deleteDocumentLinksByDocumentId(@WebParam(name = STR) String originatingDocumentId) throws RiceIllegalArgumentException;
/** * Removes all {@link DocumentLink}s for the given {@link Document} with the given originatingDocumentId. * * @param originatingDocumentId the unique id of the originating Document of the document links to delete * * @return a list of the deleted {@link DocumentLink}s * * @throws RiceIllegalArgumentException if {@code documentLink} is null */
Removes all <code>DocumentLink</code>s for the given <code>Document</code> with the given originatingDocumentId
deleteDocumentLinksByDocumentId
{ "repo_name": "mztaylor/rice-git", "path": "rice-middleware/kew/api/src/main/java/org/kuali/rice/kew/api/document/WorkflowDocumentService.java", "license": "apache-2.0", "size": 32355 }
[ "java.util.List", "javax.jws.WebMethod", "javax.jws.WebParam", "javax.jws.WebResult", "javax.xml.bind.annotation.XmlElement", "javax.xml.bind.annotation.XmlElementWrapper", "org.kuali.rice.core.api.exception.RiceIllegalArgumentException" ]
import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import java.util.*; import javax.jws.*; import javax.xml.bind.annotation.*; import org.kuali.rice.core.api.exception.*;
[ "java.util", "javax.jws", "javax.xml", "org.kuali.rice" ]
java.util; javax.jws; javax.xml; org.kuali.rice;
1,791,037
void recoverCreateRead() throws IOException { for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); StorageState curState; try { curState = sd.analyzeStorage(HdfsServerConstants.StartupOption.REGULAR, storage); // sd is locked but not opened switch(curState) { case NON_EXISTENT: // fail if any of the configured storage dirs are inaccessible throw new InconsistentFSStateException(sd.getRoot(), "checkpoint directory does not exist or is not accessible."); case NOT_FORMATTED: // for backup node all directories may be unformatted initially LOG.info("Storage directory " + sd.getRoot() + " is not formatted."); LOG.info("Formatting ..."); sd.clearDirectory(); // create empty current break; case NORMAL: break; default: // recovery is possible sd.doRecover(curState); } if(curState != StorageState.NOT_FORMATTED) { // read and verify consistency with other directories storage.readProperties(sd); } } catch(IOException ioe) { sd.unlock(); throw ioe; } } } /** * Receive a batch of edits from the NameNode. * * Depending on bnState, different actions are taken. See * {@link BackupImage.BNState}
void recoverCreateRead() throws IOException { for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); StorageState curState; try { curState = sd.analyzeStorage(HdfsServerConstants.StartupOption.REGULAR, storage); switch(curState) { case NON_EXISTENT: throw new InconsistentFSStateException(sd.getRoot(), STR); case NOT_FORMATTED: LOG.info(STR + sd.getRoot() + STR); LOG.info(STR); sd.clearDirectory(); break; case NORMAL: break; default: sd.doRecover(curState); } if(curState != StorageState.NOT_FORMATTED) { storage.readProperties(sd); } } catch(IOException ioe) { sd.unlock(); throw ioe; } } } /** * Receive a batch of edits from the NameNode. * * Depending on bnState, different actions are taken. See * {@link BackupImage.BNState}
/** * Analyze backup storage directories for consistency.<br> * Recover from incomplete checkpoints if required.<br> * Read VERSION and fstime files if exist.<br> * Do not load image or edits. * * @throws IOException if the node should shutdown. */
Analyze backup storage directories for consistency. Recover from incomplete checkpoints if required. Read VERSION and fstime files if exist. Do not load image or edits
recoverCreateRead
{ "repo_name": "mapr/hadoop-common", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/BackupImage.java", "license": "apache-2.0", "size": 13355 }
[ "java.io.IOException", "java.util.Iterator", "org.apache.hadoop.hdfs.server.common.HdfsServerConstants", "org.apache.hadoop.hdfs.server.common.InconsistentFSStateException", "org.apache.hadoop.hdfs.server.common.Storage" ]
import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException; import org.apache.hadoop.hdfs.server.common.Storage;
import java.io.*; import java.util.*; import org.apache.hadoop.hdfs.server.common.*;
[ "java.io", "java.util", "org.apache.hadoop" ]
java.io; java.util; org.apache.hadoop;
909,687
public Component getComponentFromLastRenderedPage(String path) { return getComponentFromLastRenderedPage(path, true); }
Component function(String path) { return getComponentFromLastRenderedPage(path, true); }
/** * Gets the component with the given path from last rendered page. This method fails in case the * component couldn't be found, and it will return null if the component was found, but is not * visible. * * @param path * Path to component * @return The component at the path * @see org.apache.wicket.MarkupContainer#get(String) */
Gets the component with the given path from last rendered page. This method fails in case the component couldn't be found, and it will return null if the component was found, but is not visible
getComponentFromLastRenderedPage
{ "repo_name": "AlienQueen/wicket", "path": "wicket-core/src/main/java/org/apache/wicket/util/tester/BaseWicketTester.java", "license": "apache-2.0", "size": 83429 }
[ "org.apache.wicket.Component" ]
import org.apache.wicket.Component;
import org.apache.wicket.*;
[ "org.apache.wicket" ]
org.apache.wicket;
1,281,156
protected final void validateCacheKey(Object key) { if (keyCheck) { CU.validateCacheKey(key); keyCheck = false; } }
final void function(Object key) { if (keyCheck) { CU.validateCacheKey(key); keyCheck = false; } }
/** * Validates that given cache key has overridden equals and hashCode methods and * implements {@link Externalizable}. * * @param key Cache key. * @throws IllegalArgumentException If validation fails. */
Validates that given cache key has overridden equals and hashCode methods and implements <code>Externalizable</code>
validateCacheKey
{ "repo_name": "ptupitsyn/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java", "license": "apache-2.0", "size": 228325 }
[ "org.apache.ignite.internal.util.typedef.internal.CU" ]
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.*;
[ "org.apache.ignite" ]
org.apache.ignite;
2,146,043
if(message == null || message.trim().length() == 0) { log.warning("Not sending message because it is empty"); return; } // crop longer messages if (message.length() > 1000) { message = message.substring(0, 1000) + "[...]"; } Sender sender = new Sender(API_KEY); Message msg = new Message.Builder().addData("message", message).build(); List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list(); for(RegistrationRecord record : records) { Result result = sender.send(msg, record.getRegId(), 5); if (result.getMessageId() != null) { log.info("Message sent to " + record.getRegId()); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // if the regId changed, we have to update the datastore log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId); record.setRegId(canonicalRegId); ofy().save().entity(record).now(); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { log.warning("Registration Id " + record.getRegId() + " no longer registered with GCM, removing from datastore"); // if the device is no longer registered with Gcm, remove it from the datastore ofy().delete().entity(record).now(); } else { log.warning("Error when sending message : " + error); } } } }
if(message == null message.trim().length() == 0) { log.warning(STR); return; } if (message.length() > 1000) { message = message.substring(0, 1000) + "[...]"; } Sender sender = new Sender(API_KEY); Message msg = new Message.Builder().addData(STR, message).build(); List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list(); for(RegistrationRecord record : records) { Result result = sender.send(msg, record.getRegId(), 5); if (result.getMessageId() != null) { log.info(STR + record.getRegId()); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { log.info(STR + record.getRegId() + STR + canonicalRegId); record.setRegId(canonicalRegId); ofy().save().entity(record).now(); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { log.warning(STR + record.getRegId() + STR); ofy().delete().entity(record).now(); } else { log.warning(STR + error); } } } }
/** * Send to the first 10 devices (You can modify this to send to any number of devices or a specific device) * * @param message The message to send */
Send to the first 10 devices (You can modify this to send to any number of devices or a specific device)
sendMessage
{ "repo_name": "lukeinnovationlab/clouddevicemanager", "path": "backend/src/main/java/com/lukeinnovationlab/clouddevicemanager/backend/MessagingEndpoint.java", "license": "apache-2.0", "size": 3786 }
[ "com.google.android.gcm.server.Constants", "com.google.android.gcm.server.Message", "com.google.android.gcm.server.Result", "com.google.android.gcm.server.Sender", "com.lukeinnovationlab.clouddevicemanager.backend.OfyService", "java.util.List" ]
import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.lukeinnovationlab.clouddevicemanager.backend.OfyService; import java.util.List;
import com.google.android.gcm.server.*; import com.lukeinnovationlab.clouddevicemanager.backend.*; import java.util.*;
[ "com.google.android", "com.lukeinnovationlab.clouddevicemanager", "java.util" ]
com.google.android; com.lukeinnovationlab.clouddevicemanager; java.util;
1,892,681
public final AbstractBusinessDelegate init(final DataTransferAssembler command) throws SpineException { synchronized (initThisObject){ initialize(command); } return this; }
final AbstractBusinessDelegate function(final DataTransferAssembler command) throws SpineException { synchronized (initThisObject){ initialize(command); } return this; }
/** * Initializes this AbstractBusinessDelegate and returns a copy to the user * * @param command The CommandComponent used by this AbstractBusinessDelegate * @throws SpineException */
Initializes this AbstractBusinessDelegate and returns a copy to the user
init
{ "repo_name": "davidlad123/spine", "path": "spine/src/com/zphinx/spine/core/AbstractBusinessDelegate.java", "license": "gpl-3.0", "size": 12835 }
[ "com.zphinx.spine.exceptions.SpineException", "com.zphinx.spine.vo.DataTransferAssembler" ]
import com.zphinx.spine.exceptions.SpineException; import com.zphinx.spine.vo.DataTransferAssembler;
import com.zphinx.spine.exceptions.*; import com.zphinx.spine.vo.*;
[ "com.zphinx.spine" ]
com.zphinx.spine;
2,424,312