method
stringlengths
13
441k
clean_method
stringlengths
7
313k
doc
stringlengths
17
17.3k
comment
stringlengths
3
1.42k
method_name
stringlengths
1
273
extra
dict
imports
sequence
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
sequence
libraries_info
stringlengths
6
661
id
int64
0
2.92M
@Test public void testRightVaultPassword() throws Exception { String cliOutput = CustomCLIExecutor.execute(RIGHT_VAULT_PASSWORD_FILE, READ_ATTRIBUTE_OPERATION + " server-state"); assertThat("Password should be right", cliOutput, containsString("Password is: " + RIGHT_PASSWORD)); assertThat("CLI should successfully initialize ", cliOutput, containsString("running")); }
void function() throws Exception { String cliOutput = CustomCLIExecutor.execute(RIGHT_VAULT_PASSWORD_FILE, READ_ATTRIBUTE_OPERATION + STR); assertThat(STR, cliOutput, containsString(STR + RIGHT_PASSWORD)); assertThat(STR, cliOutput, containsString(STR)); }
/** * Run CLI with vaulted keystore and truststore passwords. Vault expression * should return right password. */
Run CLI with vaulted keystore and truststore passwords. Vault expression should return right password
testRightVaultPassword
{ "repo_name": "JiriOndrusek/wildfly-core", "path": "testsuite/manualmode/src/test/java/org/jboss/as/test/manualmode/management/cli/CustomVaultInCLITestCase.java", "license": "lgpl-2.1", "size": 8703 }
[ "org.hamcrest.CoreMatchers", "org.jboss.as.test.integration.management.util.CustomCLIExecutor", "org.junit.Assert" ]
import org.hamcrest.CoreMatchers; import org.jboss.as.test.integration.management.util.CustomCLIExecutor; import org.junit.Assert;
import org.hamcrest.*; import org.jboss.as.test.integration.management.util.*; import org.junit.*;
[ "org.hamcrest", "org.jboss.as", "org.junit" ]
org.hamcrest; org.jboss.as; org.junit;
2,771,243
public static AnimatablePaintValue createURIPaintValue (AnimationTarget target, String uri) { AnimatablePaintValue v = new AnimatablePaintValue(target); v.uri = uri; v.paintType = PAINT_URI; return v; }
static AnimatablePaintValue function (AnimationTarget target, String uri) { AnimatablePaintValue v = new AnimatablePaintValue(target); v.uri = uri; v.paintType = PAINT_URI; return v; }
/** * Creates a new AnimatablePaintValue for a URI reference. */
Creates a new AnimatablePaintValue for a URI reference
createURIPaintValue
{ "repo_name": "Uni-Sol/batik", "path": "sources/org/apache/batik/anim/values/AnimatablePaintValue.java", "license": "apache-2.0", "size": 8740 }
[ "org.apache.batik.anim.AnimationTarget" ]
import org.apache.batik.anim.AnimationTarget;
import org.apache.batik.anim.*;
[ "org.apache.batik" ]
org.apache.batik;
1,774,656
RESULT_TYPE visitCouponFixedAccruedCompoundingDefinition(CouponFixedAccruedCompoundingDefinition payment);
RESULT_TYPE visitCouponFixedAccruedCompoundingDefinition(CouponFixedAccruedCompoundingDefinition payment);
/** * Fixed coupon with accrued compounding method. * @param payment A fixed coupon with accrued compounding * @return The result */
Fixed coupon with accrued compounding method
visitCouponFixedAccruedCompoundingDefinition
{ "repo_name": "jerome79/OG-Platform", "path": "projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/instrument/InstrumentDefinitionVisitor.java", "license": "apache-2.0", "size": 78879 }
[ "com.opengamma.analytics.financial.instrument.payment.CouponFixedAccruedCompoundingDefinition" ]
import com.opengamma.analytics.financial.instrument.payment.CouponFixedAccruedCompoundingDefinition;
import com.opengamma.analytics.financial.instrument.payment.*;
[ "com.opengamma.analytics" ]
com.opengamma.analytics;
2,216,816
@Test public void testValueOfByteArrayIPv6() { IpAddress ipAddress; byte[] value; value = new byte[] {0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77, (byte) 0x88, (byte) 0x88}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is("1111:2222:3333:4444:5555:6666:7777:8888")); value = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is("::")); value = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); }
void function() { IpAddress ipAddress; byte[] value; value = new byte[] {0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77, (byte) 0x88, (byte) 0x88}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is(STR)); value = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is("::")); value = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; ipAddress = IpAddress.valueOf(IpAddress.Version.INET6, value); assertThat(ipAddress.toString(), is(STR)); }
/** * Tests valueOf() converter for IPv6 byte array. */
Tests valueOf() converter for IPv6 byte array
testValueOfByteArrayIPv6
{ "repo_name": "Shashikanth-Huawei/bmp", "path": "utils/misc/src/test/java/org/onlab/packet/IpAddressTest.java", "license": "apache-2.0", "size": 33307 }
[ "org.hamcrest.Matchers", "org.junit.Assert" ]
import org.hamcrest.Matchers; import org.junit.Assert;
import org.hamcrest.*; import org.junit.*;
[ "org.hamcrest", "org.junit" ]
org.hamcrest; org.junit;
2,018,788
private void deleteSinger(HttpServletRequest req, HttpServletResponse res) { String name = req.getParameter("deletesinger"); SingerService ss = new SingerService(); MusicService ms = new MusicService(); try { if (ss.deleteSinger(name)) { System.out.println(name + "mahua"); res.sendRedirect("/byzq/bosombuddymanager/singer.jsp"); } } catch (IOException e) { e.printStackTrace(); } }
void function(HttpServletRequest req, HttpServletResponse res) { String name = req.getParameter(STR); SingerService ss = new SingerService(); MusicService ms = new MusicService(); try { if (ss.deleteSinger(name)) { System.out.println(name + "mahua"); res.sendRedirect(STR); } } catch (IOException e) { e.printStackTrace(); } }
/** * This class is used for ... * * @author Hewie * @version 1.0, 2015-7-7 ÉÏÎç9:03:08 */
This class is used for ..
deleteSinger
{ "repo_name": "Hewie8023/byzq", "path": "src/com/byzq/servlet/ManagerServlet.java", "license": "gpl-2.0", "size": 13839 }
[ "com.byzq.service.MusicService", "com.byzq.service.SingerService", "java.io.IOException", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" ]
import com.byzq.service.MusicService; import com.byzq.service.SingerService; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.byzq.service.*; import java.io.*; import javax.servlet.http.*;
[ "com.byzq.service", "java.io", "javax.servlet" ]
com.byzq.service; java.io; javax.servlet;
651,468
public void testAddAll() throws Exception{ HabitHistoryController.getInstance(); // Clear out the habit history. while (!HabitHistoryController.getInstance().isEmpty()){HabitHistoryController.getInstance().remove(0);} HabitEvent he = null; try { Habit h = new Habit("Feed the Cat", new Date()); he = new HabitEvent(h, "Title", "Did my habit!", null, null, new Date()); } catch (HabitCommentTooLongException e) { e.printStackTrace(); } catch (HabitTitleTooLongException e) { e.printStackTrace(); } catch (DateNotValidException e) { e.printStackTrace(); } // Add 10 new habit events int addNum = 10; ArrayList<HabitEvent> habitEvents = new ArrayList<HabitEvent>(); for (int i = 0; i < addNum; i++){ habitEvents.add(he); } int size = habitEvents.size(); Log.d("Size:", String.valueOf(size)); assertTrue(size == addNum); HabitHistoryController.getInstance().addAllHabitEvents(habitEvents); size = HabitHistoryController.getInstance().size(); Log.d("Size:", String.valueOf(size)); assertTrue(size == addNum); }
void function() throws Exception{ HabitHistoryController.getInstance(); while (!HabitHistoryController.getInstance().isEmpty()){HabitHistoryController.getInstance().remove(0);} HabitEvent he = null; try { Habit h = new Habit(STR, new Date()); he = new HabitEvent(h, "Title", STR, null, null, new Date()); } catch (HabitCommentTooLongException e) { e.printStackTrace(); } catch (HabitTitleTooLongException e) { e.printStackTrace(); } catch (DateNotValidException e) { e.printStackTrace(); } int addNum = 10; ArrayList<HabitEvent> habitEvents = new ArrayList<HabitEvent>(); for (int i = 0; i < addNum; i++){ habitEvents.add(he); } int size = habitEvents.size(); Log.d("Size:", String.valueOf(size)); assertTrue(size == addNum); HabitHistoryController.getInstance().addAllHabitEvents(habitEvents); size = HabitHistoryController.getInstance().size(); Log.d("Size:", String.valueOf(size)); assertTrue(size == addNum); }
/** * Tests adding a list of HabitEvents to HabitHistory * Also tests remove(int idx) to ensure that HabitHistory isEmpty */
Tests adding a list of HabitEvents to HabitHistory Also tests remove(int idx) to ensure that HabitHistory isEmpty
testAddAll
{ "repo_name": "CMPUT301F17T18/WSFMN", "path": "app/src/androidTest/java/com/wsfmn/view/controller/HabitHistoryControllerTest.java", "license": "mit", "size": 12387 }
[ "android.util.Log", "com.wsfmn.controller.HabitHistoryController", "com.wsfmn.exceptions.DateNotValidException", "com.wsfmn.exceptions.HabitCommentTooLongException", "com.wsfmn.exceptions.HabitTitleTooLongException", "com.wsfmn.model.Date", "com.wsfmn.model.Habit", "com.wsfmn.model.HabitEvent", "java.util.ArrayList" ]
import android.util.Log; import com.wsfmn.controller.HabitHistoryController; import com.wsfmn.exceptions.DateNotValidException; import com.wsfmn.exceptions.HabitCommentTooLongException; import com.wsfmn.exceptions.HabitTitleTooLongException; import com.wsfmn.model.Date; import com.wsfmn.model.Habit; import com.wsfmn.model.HabitEvent; import java.util.ArrayList;
import android.util.*; import com.wsfmn.controller.*; import com.wsfmn.exceptions.*; import com.wsfmn.model.*; import java.util.*;
[ "android.util", "com.wsfmn.controller", "com.wsfmn.exceptions", "com.wsfmn.model", "java.util" ]
android.util; com.wsfmn.controller; com.wsfmn.exceptions; com.wsfmn.model; java.util;
1,887,184
void removeAdmin(PerunSession perunSession, SecurityTeam securityTeam, User user) throws InternalErrorException, PrivilegeException, SecurityTeamNotExistsException, UserNotExistsException, UserNotAdminException;
void removeAdmin(PerunSession perunSession, SecurityTeam securityTeam, User user) throws InternalErrorException, PrivilegeException, SecurityTeamNotExistsException, UserNotExistsException, UserNotAdminException;
/** * Remove security admin role for given security team from user * * @param perunSession * @param securityTeam * @param user * @throws InternalErrorException * @throws PrivilegeException Can do only PerunAdmin or SecurityAdmin of the SecurityTeam * @throws SecurityTeamNotExistsException * @throws UserNotExistsException * @throws UserNotAdminException */
Remove security admin role for given security team from user
removeAdmin
{ "repo_name": "licehammer/perun", "path": "perun-core/src/main/java/cz/metacentrum/perun/core/api/SecurityTeamsManager.java", "license": "bsd-2-clause", "size": 12360 }
[ "cz.metacentrum.perun.core.api.exceptions.InternalErrorException", "cz.metacentrum.perun.core.api.exceptions.PrivilegeException", "cz.metacentrum.perun.core.api.exceptions.SecurityTeamNotExistsException", "cz.metacentrum.perun.core.api.exceptions.UserNotAdminException", "cz.metacentrum.perun.core.api.exceptions.UserNotExistsException" ]
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.PrivilegeException; import cz.metacentrum.perun.core.api.exceptions.SecurityTeamNotExistsException; import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException; import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.*;
[ "cz.metacentrum.perun" ]
cz.metacentrum.perun;
230,853
private boolean currentBendPointMatches(Point currentBendpoint, Point point) { Point root = currentBendpoint.getCopy(); GraphicsUtil.synchronizePoints(root, point, 6); return root.equals(point); }
boolean function(Point currentBendpoint, Point point) { Point root = currentBendpoint.getCopy(); GraphicsUtil.synchronizePoints(root, point, 6); return root.equals(point); }
/** * Here we need to compare the two points, including the same adjustment * made by the router * * @param currentBendpoint * @param point * @return */
Here we need to compare the two points, including the same adjustment made by the router
currentBendPointMatches
{ "repo_name": "lwriemen/bridgepoint", "path": "src/org.xtuml.bp.ui.graphics/src/org/xtuml/bp/ui/graphics/policies/ConnectorBendPointEditPolicy.java", "license": "apache-2.0", "size": 5503 }
[ "org.eclipse.draw2d.geometry.Point", "org.xtuml.bp.ui.graphics.utilities.GraphicsUtil" ]
import org.eclipse.draw2d.geometry.Point; import org.xtuml.bp.ui.graphics.utilities.GraphicsUtil;
import org.eclipse.draw2d.geometry.*; import org.xtuml.bp.ui.graphics.utilities.*;
[ "org.eclipse.draw2d", "org.xtuml.bp" ]
org.eclipse.draw2d; org.xtuml.bp;
1,178,198
private static Bitmap getMiddlePictureInTimeLineGif(String filePath, int reqWidth, int reqHeight) { // try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); if (bitmap == null) return null; int height = options.outHeight; int width = options.outWidth; int cutHeight = 0; int cutWidth = 0; if (height >= reqHeight && width >= reqWidth) { cutHeight = reqHeight; cutWidth = reqWidth; } else if (height < reqHeight && width >= reqWidth) { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } else if (height >= reqHeight && width < reqWidth) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else if (height < reqHeight && width < reqWidth) { float betweenWidth = ((float) reqWidth - (float) width) / (float) width; float betweenHeight = ((float) reqHeight - (float) height) / (float) height; if (betweenWidth > betweenHeight) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } } if (cutWidth <= 0 || cutHeight <= 0) { return null; } Bitmap region = Bitmap.createBitmap(bitmap, 0, 0, cutWidth, cutHeight); if (region != bitmap) { bitmap.recycle(); bitmap = region; } if (bitmap.getHeight() < reqHeight && bitmap.getWidth() < reqWidth) { Bitmap scale = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true); if (scale != bitmap) { bitmap.recycle(); bitmap = scale; } } Bitmap cornerBitmap = ImageEdit.getRoundedCornerBitmap(bitmap); if (cornerBitmap != bitmap) { bitmap.recycle(); bitmap = cornerBitmap; } return bitmap; // } catch (OutOfMemoryError ignored) { // return null; // } }
static Bitmap function(String filePath, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); if (bitmap == null) return null; int height = options.outHeight; int width = options.outWidth; int cutHeight = 0; int cutWidth = 0; if (height >= reqHeight && width >= reqWidth) { cutHeight = reqHeight; cutWidth = reqWidth; } else if (height < reqHeight && width >= reqWidth) { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } else if (height >= reqHeight && width < reqWidth) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else if (height < reqHeight && width < reqWidth) { float betweenWidth = ((float) reqWidth - (float) width) / (float) width; float betweenHeight = ((float) reqHeight - (float) height) / (float) height; if (betweenWidth > betweenHeight) { cutWidth = width; cutHeight = (reqHeight * cutWidth) / reqWidth; } else { cutHeight = height; cutWidth = (reqWidth * cutHeight) / reqHeight; } } if (cutWidth <= 0 cutHeight <= 0) { return null; } Bitmap region = Bitmap.createBitmap(bitmap, 0, 0, cutWidth, cutHeight); if (region != bitmap) { bitmap.recycle(); bitmap = region; } if (bitmap.getHeight() < reqHeight && bitmap.getWidth() < reqWidth) { Bitmap scale = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true); if (scale != bitmap) { bitmap.recycle(); bitmap = scale; } } Bitmap cornerBitmap = ImageEdit.getRoundedCornerBitmap(bitmap); if (cornerBitmap != bitmap) { bitmap.recycle(); bitmap = cornerBitmap; } return bitmap; }
/** * 1. convert gif to normal bitmap * 2. cut bitmap */
1. convert gif to normal bitmap 2. cut bitmap
getMiddlePictureInTimeLineGif
{ "repo_name": "AndroidREPo-jason/TestWeiBo", "path": "src/org/qii/weiciyuan/support/imagetool/ImageTool.java", "license": "gpl-3.0", "size": 15311 }
[ "android.graphics.Bitmap", "android.graphics.BitmapFactory" ]
import android.graphics.Bitmap; import android.graphics.BitmapFactory;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
2,849,440
@Test public void testEmpty3() { setMethod(M_EMPTY); assertTrue(getPosition(), empty(" ")); }
void function() { setMethod(M_EMPTY); assertTrue(getPosition(), empty(" ")); }
/** * Validator.empty: true */
Validator.empty: true
testEmpty3
{ "repo_name": "silentbalanceyh/lyra", "path": "lyra-bus/util-comet/src/test/java/com/test/lyra/util/internal/Validator1TestCase.java", "license": "gpl-3.0", "size": 2067 }
[ "com.lyra.util.internal.Validator", "org.junit.Assert" ]
import com.lyra.util.internal.Validator; import org.junit.Assert;
import com.lyra.util.internal.*; import org.junit.*;
[ "com.lyra.util", "org.junit" ]
com.lyra.util; org.junit;
1,810,213
@Override public GerenciadorCache<K, V> build(String nomeCache) { this.cache.setNomeCache(nomeCache); return new GerenciadorCache<>(tipoChave, tipoValor, cache); }
GerenciadorCache<K, V> function(String nomeCache) { this.cache.setNomeCache(nomeCache); return new GerenciadorCache<>(tipoChave, tipoValor, cache); }
/** * * Inicializa o gerenciador de cache * * @param nomeCache Nome da instância que está sendo criada * * @return O gerenciador de cache */
Inicializa o gerenciador de cache
build
{ "repo_name": "pedrohnog/Trabalhos-FIAP", "path": "Trabalho3/Netgifx/src/br/com/fiap/cache/builder/impl/CacheBuilderImpl.java", "license": "unlicense", "size": 4876 }
[ "br.com.fiap.cache.manager.GerenciadorCache" ]
import br.com.fiap.cache.manager.GerenciadorCache;
import br.com.fiap.cache.manager.*;
[ "br.com.fiap" ]
br.com.fiap;
1,485,790
public ClientFactoryBuilder tlsNoVerify() { checkState(insecureHosts.isEmpty(), "tlsNoVerify() and tlsNoVerifyHosts() are mutually exclusive."); tlsNoVerifySet = true; return this; }
ClientFactoryBuilder function() { checkState(insecureHosts.isEmpty(), STR); tlsNoVerifySet = true; return this; }
/** * Disables the verification of server's TLS certificate chain. If you want to disable verification for * only specific hosts, use {@link #tlsNoVerifyHosts(String...)}. * <strong>Note:</strong> You should never use this in production but only for a testing purpose. * * @see InsecureTrustManagerFactory * @see #tlsCustomizer(Consumer) */
Disables the verification of server's TLS certificate chain. If you want to disable verification for only specific hosts, use <code>#tlsNoVerifyHosts(String...)</code>. Note: You should never use this in production but only for a testing purpose
tlsNoVerify
{ "repo_name": "minwoox/armeria", "path": "core/src/main/java/com/linecorp/armeria/client/ClientFactoryBuilder.java", "license": "apache-2.0", "size": 31760 }
[ "com.google.common.base.Preconditions" ]
import com.google.common.base.Preconditions;
import com.google.common.base.*;
[ "com.google.common" ]
com.google.common;
1,837,366
SizeValue getAsSize(String[] settings, SizeValue defaultValue) throws SettingsException;
SizeValue getAsSize(String[] settings, SizeValue defaultValue) throws SettingsException;
/** * Returns the setting value (as size) associated with the setting key. If it does not exists, * returns the default value provided. */
Returns the setting value (as size) associated with the setting key. If it does not exists, returns the default value provided
getAsSize
{ "repo_name": "combinatorist/elasticsearch", "path": "src/main/java/org/elasticsearch/common/settings/Settings.java", "license": "apache-2.0", "size": 13787 }
[ "org.elasticsearch.common.unit.SizeValue" ]
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.unit.*;
[ "org.elasticsearch.common" ]
org.elasticsearch.common;
2,593,347
public Object visitCompositeExpression(CompositeExpression ex) throws VilException;
Object function(CompositeExpression ex) throws VilException;
/** * Visits a composite expression. * * @param ex the expression * @return the result of visiting the given statement * @throws VilException in case that visiting fails (e.g., execution) */
Visits a composite expression
visitCompositeExpression
{ "repo_name": "SSEHUB/EASyProducer", "path": "Plugins/Instantiation/de.uni_hildesheim.sse.easy.instantiatorCore/src/net/ssehub/easy/instantiation/core/model/expressions/IExpressionVisitor.java", "license": "apache-2.0", "size": 5805 }
[ "net.ssehub.easy.instantiation.core.model.common.VilException" ]
import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.instantiation.core.model.common.*;
[ "net.ssehub.easy" ]
net.ssehub.easy;
295,807
public static String getPhysicalFileFromResource(final String resource) throws IOException { final File file = File.createTempFile("tempfile", ".txt"); file.deleteOnExit(); final PrintWriter printWriter = new PrintWriter(file); printWriter.write(BaseTestQuery.getFile(resource)); printWriter.close(); return file.getPath(); }
static String function(final String resource) throws IOException { final File file = File.createTempFile(STR, ".txt"); file.deleteOnExit(); final PrintWriter printWriter = new PrintWriter(file); printWriter.write(BaseTestQuery.getFile(resource)); printWriter.close(); return file.getPath(); }
/** * Copy the resource (ex. file on classpath) to a physical file on FileSystem. * @param resource * @return the file path * @throws IOException */
Copy the resource (ex. file on classpath) to a physical file on FileSystem
getPhysicalFileFromResource
{ "repo_name": "myroch/drill", "path": "exec/java-exec/src/test/java/org/apache/drill/BaseTestQuery.java", "license": "apache-2.0", "size": 18458 }
[ "java.io.File", "java.io.IOException", "java.io.PrintWriter" ]
import java.io.File; import java.io.IOException; import java.io.PrintWriter;
import java.io.*;
[ "java.io" ]
java.io;
2,592,431
public ICoreDistributedServices getDistributedServices() { return _distributed_services; }
ICoreDistributedServices function() { return _distributed_services; }
/** Returns the various distributed services present * @return the distributed services */
Returns the various distributed services present
getDistributedServices
{ "repo_name": "robgil/Aleph2", "path": "aleph2_management_db_service/src/com/ikanow/aleph2/management_db/services/ManagementDbActorContext.java", "license": "apache-2.0", "size": 10135 }
[ "com.ikanow.aleph2.distributed_services.services.ICoreDistributedServices" ]
import com.ikanow.aleph2.distributed_services.services.ICoreDistributedServices;
import com.ikanow.aleph2.distributed_services.services.*;
[ "com.ikanow.aleph2" ]
com.ikanow.aleph2;
2,035,485
private IdmGenerateValueDto createGenerator() { IdmGenerateValueDto generateValue = new IdmGenerateValueDto(); generateValue.setDtoType(getDtoType().getCanonicalName()); generateValue.setGeneratorType(getGeneratorType()); generateValue.setSeq((short) 100); generateValue.setUnmodifiable(true); return generateValueService.save(generateValue); }
IdmGenerateValueDto function() { IdmGenerateValueDto generateValue = new IdmGenerateValueDto(); generateValue.setDtoType(getDtoType().getCanonicalName()); generateValue.setGeneratorType(getGeneratorType()); generateValue.setSeq((short) 100); generateValue.setUnmodifiable(true); return generateValueService.save(generateValue); }
/** * Method create generator for this test and remove all another generators. * * @return * */
Method create generator for this test and remove all another generators
createGenerator
{ "repo_name": "bcvsolutions/CzechIdMng", "path": "Realization/backend/core/core-impl/src/test/java/eu/bcvsolutions/idm/core/generator/role/IdentityRoleFormDefaultValueGeneratorTest.java", "license": "mit", "size": 13401 }
[ "eu.bcvsolutions.idm.core.api.dto.IdmGenerateValueDto" ]
import eu.bcvsolutions.idm.core.api.dto.IdmGenerateValueDto;
import eu.bcvsolutions.idm.core.api.dto.*;
[ "eu.bcvsolutions.idm" ]
eu.bcvsolutions.idm;
2,282,134
public StepInterface getRunThread( int i ) { if ( steps == null ) { return null; } return steps.get( i ).step; }
StepInterface function( int i ) { if ( steps == null ) { return null; } return steps.get( i ).step; }
/** * Gets the run thread for the step at the specified index. * * @param i * the index of the desired step * @return a StepInterface object corresponding to the run thread for the specified step */
Gets the run thread for the step at the specified index
getRunThread
{ "repo_name": "ma459006574/pentaho-kettle", "path": "engine/src/org/pentaho/di/trans/Trans.java", "license": "apache-2.0", "size": 191984 }
[ "org.pentaho.di.trans.step.StepInterface" ]
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.*;
[ "org.pentaho.di" ]
org.pentaho.di;
2,772,008
public void delete(Person person) { logger.debug("delete({})", person); hibernateService.delete(person); }
void function(Person person) { logger.debug(STR, person); hibernateService.delete(person); }
/** * Delete person. */
Delete person
delete
{ "repo_name": "gammaliu/mongo-elastic-demo", "path": "src/main/java/io/github/gammaliu/demo/dao/PersonDaoImpl.java", "license": "apache-2.0", "size": 1757 }
[ "io.github.gammaliu.demo.domain.Person" ]
import io.github.gammaliu.demo.domain.Person;
import io.github.gammaliu.demo.domain.*;
[ "io.github.gammaliu" ]
io.github.gammaliu;
1,323,226
public Map<String,Collection<String>> getFeatureOfInterestIdentifiersWithParents(final Session session) { Criteria criteria = session.createCriteria(FeatureOfInterest.class); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.property(FeatureOfInterest.IDENTIFIER)); //get parents if transactional profile is active boolean tFoiSupported = HibernateHelper.isEntitySupported(TFeatureOfInterest.class, session); if (tFoiSupported) { criteria.createAlias(TFeatureOfInterest.PARENTS, "pfoi", JoinType.LEFT_OUTER_JOIN); projectionList.add(Projections.property("pfoi." + FeatureOfInterest.IDENTIFIER)); } criteria.setProjection(projectionList); //return as List<Object[]> even if there's only one column for consistency criteria.setResultTransformer(NoopTransformerAdapter.INSTANCE); LOGGER.debug("QUERY getFeatureOfInterestIdentifiersWithParents(): {}", HibernateHelper.getSqlString(criteria)); @SuppressWarnings("unchecked") List<Object[]> results = criteria.list(); Map<String,Collection<String>> foiMap = Maps.newHashMap(); for(Object[] result : results) { String featureIdentifier = (String) result[0]; String parentFeatureIdentifier = null; if (tFoiSupported) { parentFeatureIdentifier = (String) result[1]; } if (parentFeatureIdentifier != null) { CollectionHelper.addToCollectionMap(featureIdentifier, parentFeatureIdentifier, foiMap); } else { foiMap.put(featureIdentifier, null); } } return foiMap; }
Map<String,Collection<String>> function(final Session session) { Criteria criteria = session.createCriteria(FeatureOfInterest.class); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.property(FeatureOfInterest.IDENTIFIER)); boolean tFoiSupported = HibernateHelper.isEntitySupported(TFeatureOfInterest.class, session); if (tFoiSupported) { criteria.createAlias(TFeatureOfInterest.PARENTS, "pfoi", JoinType.LEFT_OUTER_JOIN); projectionList.add(Projections.property("pfoi." + FeatureOfInterest.IDENTIFIER)); } criteria.setProjection(projectionList); criteria.setResultTransformer(NoopTransformerAdapter.INSTANCE); LOGGER.debug(STR, HibernateHelper.getSqlString(criteria)); @SuppressWarnings(STR) List<Object[]> results = criteria.list(); Map<String,Collection<String>> foiMap = Maps.newHashMap(); for(Object[] result : results) { String featureIdentifier = (String) result[0]; String parentFeatureIdentifier = null; if (tFoiSupported) { parentFeatureIdentifier = (String) result[1]; } if (parentFeatureIdentifier != null) { CollectionHelper.addToCollectionMap(featureIdentifier, parentFeatureIdentifier, foiMap); } else { foiMap.put(featureIdentifier, null); } } return foiMap; }
/** * Load FOI identifiers and parent ids for use in the cache. Just loading the ids allows us to not load * the geometry columns, XML, etc. * * @param session * @return Map keyed by FOI identifiers, with value collections of parent FOI identifiers if supported */
Load FOI identifiers and parent ids for use in the cache. Just loading the ids allows us to not load the geometry columns, XML, etc
getFeatureOfInterestIdentifiersWithParents
{ "repo_name": "shane-axiom/SOS", "path": "hibernate/common/src/main/java/org/n52/sos/ds/hibernate/dao/FeatureOfInterestDAO.java", "license": "gpl-2.0", "size": 18200 }
[ "com.google.common.collect.Maps", "java.util.Collection", "java.util.List", "java.util.Map", "org.hibernate.Criteria", "org.hibernate.Session", "org.hibernate.criterion.ProjectionList", "org.hibernate.criterion.Projections", "org.hibernate.sql.JoinType", "org.n52.sos.ds.hibernate.entities.FeatureOfInterest", "org.n52.sos.ds.hibernate.entities.TFeatureOfInterest", "org.n52.sos.ds.hibernate.util.HibernateHelper", "org.n52.sos.ds.hibernate.util.NoopTransformerAdapter", "org.n52.sos.util.CollectionHelper" ]
import com.google.common.collect.Maps; import java.util.Collection; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.sql.JoinType; import org.n52.sos.ds.hibernate.entities.FeatureOfInterest; import org.n52.sos.ds.hibernate.entities.TFeatureOfInterest; import org.n52.sos.ds.hibernate.util.HibernateHelper; import org.n52.sos.ds.hibernate.util.NoopTransformerAdapter; import org.n52.sos.util.CollectionHelper;
import com.google.common.collect.*; import java.util.*; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.sql.*; import org.n52.sos.ds.hibernate.entities.*; import org.n52.sos.ds.hibernate.util.*; import org.n52.sos.util.*;
[ "com.google.common", "java.util", "org.hibernate", "org.hibernate.criterion", "org.hibernate.sql", "org.n52.sos" ]
com.google.common; java.util; org.hibernate; org.hibernate.criterion; org.hibernate.sql; org.n52.sos;
2,460,804
private void setPicToView(Intent picdata) { Bundle extras = picdata.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); Drawable drawable = new BitmapDrawable(getResources(), photo); headAvatar.setImageDrawable(drawable); uploadUserAvatar(Bitmap2Bytes(photo)); } }
void function(Intent picdata) { Bundle extras = picdata.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); Drawable drawable = new BitmapDrawable(getResources(), photo); headAvatar.setImageDrawable(drawable); uploadUserAvatar(Bitmap2Bytes(photo)); } }
/** * save the picture data * * @param picdata */
save the picture data
setPicToView
{ "repo_name": "xumorden/WoZai", "path": "app/src/main/java/com/a200fang/wozai/activity/UserProfileActivity.java", "license": "mit", "size": 8758 }
[ "android.content.Intent", "android.graphics.Bitmap", "android.graphics.drawable.BitmapDrawable", "android.graphics.drawable.Drawable", "android.os.Bundle" ]
import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle;
import android.content.*; import android.graphics.*; import android.graphics.drawable.*; import android.os.*;
[ "android.content", "android.graphics", "android.os" ]
android.content; android.graphics; android.os;
2,904,499
void close() throws IOException;
void close() throws IOException;
/** Frees resources associated with this Searcher. * Be careful not to call this method while you are still using objects * that reference this Searchable. */
Frees resources associated with this Searcher. Be careful not to call this method while you are still using objects that reference this Searchable
close
{ "repo_name": "chrishumphreys/provocateur", "path": "provocateur-thirdparty/src/main/java/org/targettest/org/apache/lucene/search/Searchable.java", "license": "apache-2.0", "size": 7248 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,612,910
public RecipeImpl getRecipe(MachineConfig machineConfig) throws MachineException { URL recipeUrl; File file = null; final String location = machineConfig.getSource().getLocation(); try { UriBuilder targetUriBuilder = UriBuilder.fromUri(location); // add user token to be able to download user's private recipe final String apiEndPointHost = apiEndpoint.getHost(); final String host = targetUriBuilder.build().getHost(); if (apiEndPointHost.equals(host)) { if (EnvironmentContext.getCurrent().getSubject() != null && EnvironmentContext.getCurrent().getSubject().getToken() != null) { targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken()); } } recipeUrl = targetUriBuilder.build().toURL(); file = IoUtil.downloadFileWithRedirect(null, "recipe", null, recipeUrl); return new RecipeImpl().withType(machineConfig.getSource().getType()) .withScript(IoUtil.readAndCloseQuietly(new FileInputStream(file))); } catch (IOException | IllegalArgumentException e) { throw new MachineException(format("Failed to download recipe for machine %s. Recipe url %s. Error: %s", machineConfig.getName(), location, e.getLocalizedMessage())); } finally { if (file != null && !file.delete()) { LOG.error(String.format("Removal of recipe file %s failed.", file.getAbsolutePath())); } } }
RecipeImpl function(MachineConfig machineConfig) throws MachineException { URL recipeUrl; File file = null; final String location = machineConfig.getSource().getLocation(); try { UriBuilder targetUriBuilder = UriBuilder.fromUri(location); final String apiEndPointHost = apiEndpoint.getHost(); final String host = targetUriBuilder.build().getHost(); if (apiEndPointHost.equals(host)) { if (EnvironmentContext.getCurrent().getSubject() != null && EnvironmentContext.getCurrent().getSubject().getToken() != null) { targetUriBuilder.queryParam("token", EnvironmentContext.getCurrent().getSubject().getToken()); } } recipeUrl = targetUriBuilder.build().toURL(); file = IoUtil.downloadFileWithRedirect(null, STR, null, recipeUrl); return new RecipeImpl().withType(machineConfig.getSource().getType()) .withScript(IoUtil.readAndCloseQuietly(new FileInputStream(file))); } catch (IOException IllegalArgumentException e) { throw new MachineException(format(STR, machineConfig.getName(), location, e.getLocalizedMessage())); } finally { if (file != null && !file.delete()) { LOG.error(String.format(STR, file.getAbsolutePath())); } } }
/** * Downloads recipe by location from {@link MachineSource#getLocation()}. * * @param machineConfig * config used to get recipe location * @return recipe with set content and type * @throws MachineException * if any error occurs */
Downloads recipe by location from <code>MachineSource#getLocation()</code>
getRecipe
{ "repo_name": "Mirage20/che", "path": "wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/util/RecipeDownloader.java", "license": "epl-1.0", "size": 5574 }
[ "java.io.File", "java.io.FileInputStream", "java.io.IOException", "java.lang.String", "javax.ws.rs.core.UriBuilder", "org.eclipse.che.api.core.model.machine.MachineConfig", "org.eclipse.che.api.machine.server.exception.MachineException", "org.eclipse.che.api.machine.server.recipe.RecipeImpl", "org.eclipse.che.commons.env.EnvironmentContext", "org.eclipse.che.commons.lang.IoUtil" ]
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.String; import javax.ws.rs.core.UriBuilder; import org.eclipse.che.api.core.model.machine.MachineConfig; import org.eclipse.che.api.machine.server.exception.MachineException; import org.eclipse.che.api.machine.server.recipe.RecipeImpl; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.lang.IoUtil;
import java.io.*; import java.lang.*; import javax.ws.rs.core.*; import org.eclipse.che.api.core.model.machine.*; import org.eclipse.che.api.machine.server.exception.*; import org.eclipse.che.api.machine.server.recipe.*; import org.eclipse.che.commons.env.*; import org.eclipse.che.commons.lang.*;
[ "java.io", "java.lang", "javax.ws", "org.eclipse.che" ]
java.io; java.lang; javax.ws; org.eclipse.che;
450,465
public static AuthHandler selectAuthHandler(byte[] secTypes, CapabilityContainer authCapabilities) throws UnsupportedSecurityTypeException { AuthHandler typeSelected = null; // Tigh Authentication first for (byte type : secTypes) { if (SecurityType.TIGHT_AUTHENTICATION.getId() == (0xff & type)) { typeSelected = SecurityType.implementedSecurityTypes .get(SecurityType.TIGHT_AUTHENTICATION.getId()); if (typeSelected != null) return typeSelected; } } for (byte type : secTypes) { typeSelected = SecurityType.implementedSecurityTypes.get(0xff & type); if (typeSelected != null && authCapabilities.isSupported(typeSelected.getId())) return typeSelected; } throw new UnsupportedSecurityTypeException( "No security types supported. Server sent '" + Strings.toString(secTypes) + "' security types, but we do not support any of their."); }
static AuthHandler function(byte[] secTypes, CapabilityContainer authCapabilities) throws UnsupportedSecurityTypeException { AuthHandler typeSelected = null; for (byte type : secTypes) { if (SecurityType.TIGHT_AUTHENTICATION.getId() == (0xff & type)) { typeSelected = SecurityType.implementedSecurityTypes .get(SecurityType.TIGHT_AUTHENTICATION.getId()); if (typeSelected != null) return typeSelected; } } for (byte type : secTypes) { typeSelected = SecurityType.implementedSecurityTypes.get(0xff & type); if (typeSelected != null && authCapabilities.isSupported(typeSelected.getId())) return typeSelected; } throw new UnsupportedSecurityTypeException( STR + Strings.toString(secTypes) + STR); }
/** * Select apropriate security type we supporded from types which server sent * * @param secTypes - byte array with security types server supported * @param authCapabilities * @return {@link AuthHandler} of selected type * @throws UnsupportedSecurityTypeException when no security types server sent we support */
Select apropriate security type we supporded from types which server sent
selectAuthHandler
{ "repo_name": "XVManage/Panel", "path": "VNC/src/main/java/com/glavsoft/rfb/protocol/state/SecurityTypeState.java", "license": "agpl-3.0", "size": 3825 }
[ "com.glavsoft.exceptions.UnsupportedSecurityTypeException", "com.glavsoft.rfb.CapabilityContainer", "com.glavsoft.rfb.protocol.auth.AuthHandler", "com.glavsoft.rfb.protocol.auth.SecurityType", "com.glavsoft.utils.Strings" ]
import com.glavsoft.exceptions.UnsupportedSecurityTypeException; import com.glavsoft.rfb.CapabilityContainer; import com.glavsoft.rfb.protocol.auth.AuthHandler; import com.glavsoft.rfb.protocol.auth.SecurityType; import com.glavsoft.utils.Strings;
import com.glavsoft.exceptions.*; import com.glavsoft.rfb.*; import com.glavsoft.rfb.protocol.auth.*; import com.glavsoft.utils.*;
[ "com.glavsoft.exceptions", "com.glavsoft.rfb", "com.glavsoft.utils" ]
com.glavsoft.exceptions; com.glavsoft.rfb; com.glavsoft.utils;
454,282
public static Object createSerializableProxy(Object target, boolean proxyTargetClass, boolean useMemoryCache, ConfigurableListableBeanFactory beanFactory, String targetBeanName) { if (target instanceof SerializableAopProxy) return target; if (log.isDebugEnabled()) log.debug("Creating serializable proxy for target bean [" + targetBeanName + "]"); SerializableReference reference = new SerializableReference(target, proxyTargetClass, useMemoryCache, beanFactory, targetBeanName); return createSerializableProxy(target, reference); }
static Object function(Object target, boolean proxyTargetClass, boolean useMemoryCache, ConfigurableListableBeanFactory beanFactory, String targetBeanName) { if (target instanceof SerializableAopProxy) return target; if (log.isDebugEnabled()) log.debug(STR + targetBeanName + "]"); SerializableReference reference = new SerializableReference(target, proxyTargetClass, useMemoryCache, beanFactory, targetBeanName); return createSerializableProxy(target, reference); }
/** * Create a new Serializable proxy for the given target * @param target target to proxy * @param proxyTargetClass true to force CGLIB proxies * @param useMemoryCache if true keep a reference to target object in memory * @param beanFactory beanFactory to use. * @param targetBeanName name of target bean * @return a new serializable proxy * */
Create a new Serializable proxy for the given target
createSerializableProxy
{ "repo_name": "chelu/jdal", "path": "aop/src/main/java/org/jdal/aop/SerializableProxyUtils.java", "license": "apache-2.0", "size": 7366 }
[ "org.springframework.beans.factory.config.ConfigurableListableBeanFactory" ]
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.*;
[ "org.springframework.beans" ]
org.springframework.beans;
1,381,492
@Test public void testDecodeBindResponseServerSASLEmptyCredentialsWithControls() { Asn1Decoder ldapDecoder = new Asn1Decoder(); ByteBuffer stream = ByteBuffer.allocate( 0x2D ); stream.put( new byte[] { 0x30, 0x2B, // LDAPMessage ::=SEQUENCE { 0x02, 0x01, 0x01, // messageID MessageID 0x61, 0x09, // CHOICE { ..., bindResponse BindResponse, ... // BindResponse ::= APPLICATION[1] SEQUENCE { // COMPONENTS OF LDAPResult, 0x0A, 0x01, 0x00, // LDAPResult ::= SEQUENCE { // resultCode ENUMERATED { // success (0), ... // }, 0x04, 0x00, // matchedDN LDAPDN, 0x04, 0x00, // errorMessage LDAPString, // referral [3] Referral OPTIONAL } ( byte ) 0x87, 0x00, // serverSaslCreds [7] OCTET STRING // OPTIONAL } ( byte ) 0xA0, 0x1B, // A control 0x30, 0x19, 0x04, 0x17, 0x32, 0x2E, 0x31, 0x36, 0x2E, 0x38, 0x34, 0x30, 0x2E, 0x31, 0x2E, 0x31, 0x31, 0x33, 0x37, 0x33, 0x30, 0x2E, 0x33, 0x2E, 0x34, 0x2E, 0x32 } ); String decodedPdu = Strings.dumpBytes( stream.array() ); stream.flip(); // Allocate a LdapMessage Container LdapMessageContainer<BindResponseDecorator> container = new LdapMessageContainer<BindResponseDecorator>( codec ); // Decode the BindResponse PDU try { ldapDecoder.decode( stream, container ); } catch ( DecoderException de ) { de.printStackTrace(); fail( de.getMessage() ); } // Check the decoded BindResponse BindResponse bindResponse = container.getMessage(); assertEquals( 1, bindResponse.getMessageId() ); assertEquals( ResultCodeEnum.SUCCESS, bindResponse.getLdapResult().getResultCode() ); assertEquals( "", bindResponse.getLdapResult().getMatchedDn().getName() ); assertEquals( "", bindResponse.getLdapResult().getDiagnosticMessage() ); assertEquals( "", Strings.utf8ToString( bindResponse.getServerSaslCreds() ) ); // Check the Control Map<String, Control> controls = bindResponse.getControls(); assertEquals( 1, controls.size() ); @SuppressWarnings("unchecked") CodecControl<Control> control = ( org.apache.directory.api.ldap.codec.api.CodecControl<Control> ) controls .get( "2.16.840.1.113730.3.4.2" ); assertEquals( "2.16.840.1.113730.3.4.2", control.getOid() ); assertEquals( "", Strings.dumpBytes( ( byte[] ) control.getValue() ) ); // Check the encoding try { ByteBuffer bb = encoder.encodeMessage( bindResponse ); // Check the length assertEquals( 0x2D, bb.limit() ); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { ee.printStackTrace(); fail( ee.getMessage() ); } }
void function() { Asn1Decoder ldapDecoder = new Asn1Decoder(); ByteBuffer stream = ByteBuffer.allocate( 0x2D ); stream.put( new byte[] { 0x30, 0x2B, 0x02, 0x01, 0x01, 0x61, 0x09, 0x0A, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00, ( byte ) 0x87, 0x00, ( byte ) 0xA0, 0x1B, 0x30, 0x19, 0x04, 0x17, 0x32, 0x2E, 0x31, 0x36, 0x2E, 0x38, 0x34, 0x30, 0x2E, 0x31, 0x2E, 0x31, 0x31, 0x33, 0x37, 0x33, 0x30, 0x2E, 0x33, 0x2E, 0x34, 0x2E, 0x32 } ); String decodedPdu = Strings.dumpBytes( stream.array() ); stream.flip(); LdapMessageContainer<BindResponseDecorator> container = new LdapMessageContainer<BindResponseDecorator>( codec ); try { ldapDecoder.decode( stream, container ); } catch ( DecoderException de ) { de.printStackTrace(); fail( de.getMessage() ); } BindResponse bindResponse = container.getMessage(); assertEquals( 1, bindResponse.getMessageId() ); assertEquals( ResultCodeEnum.SUCCESS, bindResponse.getLdapResult().getResultCode() ); assertEquals( STRSTRSTRuncheckedSTR2.16.840.1.113730.3.4.2STR2.16.840.1.113730.3.4.2STR", Strings.dumpBytes( ( byte[] ) control.getValue() ) ); try { ByteBuffer bb = encoder.encodeMessage( bindResponse ); assertEquals( 0x2D, bb.limit() ); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { ee.printStackTrace(); fail( ee.getMessage() ); } }
/** * Test the decoding of a BindResponse with an empty credentials with * controls */
Test the decoding of a BindResponse with an empty credentials with controls
testDecodeBindResponseServerSASLEmptyCredentialsWithControls
{ "repo_name": "darranl/directory-shared", "path": "ldap/codec/core/src/test/java/org/apache/directory/api/ldap/codec/bind/BindResponseTest.java", "license": "apache-2.0", "size": 19296 }
[ "java.nio.ByteBuffer", "org.apache.directory.api.asn1.DecoderException", "org.apache.directory.api.asn1.EncoderException", "org.apache.directory.api.asn1.ber.Asn1Decoder", "org.apache.directory.api.ldap.codec.api.LdapMessageContainer", "org.apache.directory.api.ldap.codec.decorators.BindResponseDecorator", "org.apache.directory.api.ldap.model.message.BindResponse", "org.apache.directory.api.ldap.model.message.ResultCodeEnum", "org.apache.directory.api.util.Strings", "org.junit.Assert" ]
import java.nio.ByteBuffer; import org.apache.directory.api.asn1.DecoderException; import org.apache.directory.api.asn1.EncoderException; import org.apache.directory.api.asn1.ber.Asn1Decoder; import org.apache.directory.api.ldap.codec.api.LdapMessageContainer; import org.apache.directory.api.ldap.codec.decorators.BindResponseDecorator; import org.apache.directory.api.ldap.model.message.BindResponse; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; import org.apache.directory.api.util.Strings; import org.junit.Assert;
import java.nio.*; import org.apache.directory.api.asn1.*; import org.apache.directory.api.asn1.ber.*; import org.apache.directory.api.ldap.codec.api.*; import org.apache.directory.api.ldap.codec.decorators.*; import org.apache.directory.api.ldap.model.message.*; import org.apache.directory.api.util.*; import org.junit.*;
[ "java.nio", "org.apache.directory", "org.junit" ]
java.nio; org.apache.directory; org.junit;
2,504,433
public static void retry(Predicate<Integer> action, String label, int times, long delay) throws TooManyRetriesException { if (times < 1) { throw new IllegalArgumentException("Retry block must try at least 1 time"); } if (delay < 1) { throw new IllegalArgumentException("Must have at least 1 ms delay"); } label = label == null ? "retry block" : label; int tries = 0; for (; times > tries; ++tries) { try { if (action.test(tries)) return; } catch (Exception e) { LOGGER.warn("Attempted to perform {}, but got exception", label, e); } try { Thread.sleep(delay); } catch (InterruptedException e) { LOGGER.warn("Couldn't sleep while testing {}", label, e); } } throw new TooManyRetriesException(String.format("Retried too many times (%d of %d): %s", tries, times, label)); } public static class TooManyRetriesException extends Exception { TooManyRetriesException(String message) { super(message); } }
static void function(Predicate<Integer> action, String label, int times, long delay) throws TooManyRetriesException { if (times < 1) { throw new IllegalArgumentException(STR); } if (delay < 1) { throw new IllegalArgumentException(STR); } label = label == null ? STR : label; int tries = 0; for (; times > tries; ++tries) { try { if (action.test(tries)) return; } catch (Exception e) { LOGGER.warn(STR, label, e); } try { Thread.sleep(delay); } catch (InterruptedException e) { LOGGER.warn(STR, label, e); } } throw new TooManyRetriesException(String.format(STR, tries, times, label)); } public static class TooManyRetriesException extends Exception { TooManyRetriesException(String message) { super(message); } }
/** * Simple retry logic with constant delay period, which retries until {@link Predicate} returns true. If you require * a backoff instead of static delay, it should be very easy to implement. * * @param action {@link Predicate<Integer>} defining the action to perform, taking the attempt number as input * @param label a user-defined {@link String} describing the action * @param times the number of times to try * @param delay the period, in milliseconds, to wait between tries * @throws TooManyRetriesException when all tries have been performed */
Simple retry logic with constant delay period, which retries until <code>Predicate</code> returns true. If you require a backoff instead of static delay, it should be very easy to implement
retry
{ "repo_name": "varshavaradarajan/gocd", "path": "server/src/main/java/com/thoughtworks/go/server/util/Retryable.java", "license": "apache-2.0", "size": 3015 }
[ "java.util.function.Predicate" ]
import java.util.function.Predicate;
import java.util.function.*;
[ "java.util" ]
java.util;
2,126,713
public static Label createLabel(Composite parent, String text, int hspan) { Label l = new Label(parent, SWT.NONE); l.setFont(parent.getFont()); l.setText(text); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = hspan; gd.grabExcessHorizontalSpace = false; l.setLayoutData(gd); return l; }
static Label function(Composite parent, String text, int hspan) { Label l = new Label(parent, SWT.NONE); l.setFont(parent.getFont()); l.setText(text); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = hspan; gd.grabExcessHorizontalSpace = false; l.setLayoutData(gd); return l; }
/** * Creates a new label widget * @param parent the parent composite to add this label widget to * @param text the text for the label * @param hspan the horizontal span to take up in the parent composite * @return the new label * @since 3.2 * */
Creates a new label widget
createLabel
{ "repo_name": "ceylon/ceylon-ide-eclipse", "path": "plugins/org.eclipse.ceylon.ide.eclipse.ui/src/org/eclipse/ceylon/ide/eclipse/core/launch/SWTFactory.java", "license": "epl-1.0", "size": 27101 }
[ "org.eclipse.swt.layout.GridData", "org.eclipse.swt.widgets.Composite", "org.eclipse.swt.widgets.Label" ]
import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
118,372
public void test_getDoubleWithExponential() { Exception ex = null; try { System.setProperty("org.apache.wink.common.model.json.factory.impl", "org.apache.wink.json4j.compat.impl.ApacheJSONFactory"); JSONFactory factory = JSONFactory.newInstance(); JSONObject jObject = factory.createJSONObject("{\"double\":100959e-3}"); assertTrue(jObject.getDouble("double") == 100.959); } catch (Exception ex1) { ex = ex1; ex.printStackTrace(); } assertTrue(ex == null); }
void function() { Exception ex = null; try { System.setProperty(STR, STR); JSONFactory factory = JSONFactory.newInstance(); JSONObject jObject = factory.createJSONObject("{\"double\STR); assertTrue(jObject.getDouble(STR) == 100.959); } catch (Exception ex1) { ex = ex1; ex.printStackTrace(); } assertTrue(ex == null); }
/** * Test a basic JSON Object construction and helper 'get' function */
Test a basic JSON Object construction and helper 'get' function
test_getDoubleWithExponential
{ "repo_name": "apache/wink", "path": "wink-json4j/src/test/java/org/apache/wink/json4j/compat/tests/ApacheJSONObjectTest.java", "license": "apache-2.0", "size": 39515 }
[ "org.apache.wink.json4j.compat.JSONFactory", "org.apache.wink.json4j.compat.JSONObject" ]
import org.apache.wink.json4j.compat.JSONFactory; import org.apache.wink.json4j.compat.JSONObject;
import org.apache.wink.json4j.compat.*;
[ "org.apache.wink" ]
org.apache.wink;
2,846,361
public void setParticipantsAndMessageFlows(Choreography choreography, Map<String,BPMNElement> bpmnElements, Diagram2BpmnConverter converter) { List<Message> messagesToRemove = new ArrayList<Message>(); List<Association> associationsToRemove = new ArrayList<Association>(); for(FlowElement flowEl : this.getFlowElement()) { if(flowEl instanceof Association) { Association association = (Association) flowEl; if((association.getSourceRef() instanceof ChoreographyActivity && association.getTargetRef() instanceof Message) || (association.getSourceRef() instanceof Message && association.getTargetRef() instanceof ChoreographyActivity)) { converter.handleMessageAssociationOnChoreographyActivity(association); } } if(flowEl instanceof Message) { messagesToRemove.add((Message) flowEl); Association msgAssociation = ((Message) flowEl).getDataConnectingAssociation(); if(msgAssociation != null) { associationsToRemove.add(msgAssociation); } } if(flowEl instanceof ChoreographyActivity) { choreography.getParticipant().addAll(((ChoreographyActivity) flowEl).getParticipantRef()); } if(flowEl instanceof ChoreographyTask) { ((ChoreographyTask) flowEl).createMessageFlows(choreography); } else if(flowEl instanceof SubChoreography) { ((SubChoreography) flowEl).setParticipantsAndMessageFlows(choreography, bpmnElements, converter); } } this.getFlowElement().removeAll(messagesToRemove); for(Association msgAssociation : associationsToRemove) { bpmnElements.remove(msgAssociation.getId()); } this.getFlowElement().removeAll(associationsToRemove); }
void function(Choreography choreography, Map<String,BPMNElement> bpmnElements, Diagram2BpmnConverter converter) { List<Message> messagesToRemove = new ArrayList<Message>(); List<Association> associationsToRemove = new ArrayList<Association>(); for(FlowElement flowEl : this.getFlowElement()) { if(flowEl instanceof Association) { Association association = (Association) flowEl; if((association.getSourceRef() instanceof ChoreographyActivity && association.getTargetRef() instanceof Message) (association.getSourceRef() instanceof Message && association.getTargetRef() instanceof ChoreographyActivity)) { converter.handleMessageAssociationOnChoreographyActivity(association); } } if(flowEl instanceof Message) { messagesToRemove.add((Message) flowEl); Association msgAssociation = ((Message) flowEl).getDataConnectingAssociation(); if(msgAssociation != null) { associationsToRemove.add(msgAssociation); } } if(flowEl instanceof ChoreographyActivity) { choreography.getParticipant().addAll(((ChoreographyActivity) flowEl).getParticipantRef()); } if(flowEl instanceof ChoreographyTask) { ((ChoreographyTask) flowEl).createMessageFlows(choreography); } else if(flowEl instanceof SubChoreography) { ((SubChoreography) flowEl).setParticipantsAndMessageFlows(choreography, bpmnElements, converter); } } this.getFlowElement().removeAll(messagesToRemove); for(Association msgAssociation : associationsToRemove) { bpmnElements.remove(msgAssociation.getId()); } this.getFlowElement().removeAll(associationsToRemove); }
/** * Copies all participant references of sub-choreographies recursively to * the choreography and creates the message flow of the choreography tasks. * * @param choreography */
Copies all participant references of sub-choreographies recursively to the choreography and creates the message flow of the choreography tasks
setParticipantsAndMessageFlows
{ "repo_name": "padmaragl/activiti-karaf", "path": "bpmn-webui-components/bpmn-webui-bpmn20-model/src/main/java/de/hpi/bpmn2_0/model/choreography/SubChoreography.java", "license": "apache-2.0", "size": 13592 }
[ "de.hpi.bpmn2_0.factory.BPMNElement", "de.hpi.bpmn2_0.model.FlowElement", "de.hpi.bpmn2_0.model.connector.Association", "de.hpi.bpmn2_0.model.data_object.Message", "de.hpi.bpmn2_0.transformation.Diagram2BpmnConverter", "java.util.ArrayList", "java.util.List", "java.util.Map" ]
import de.hpi.bpmn2_0.factory.BPMNElement; import de.hpi.bpmn2_0.model.FlowElement; import de.hpi.bpmn2_0.model.connector.Association; import de.hpi.bpmn2_0.model.data_object.Message; import de.hpi.bpmn2_0.transformation.Diagram2BpmnConverter; import java.util.ArrayList; import java.util.List; import java.util.Map;
import de.hpi.bpmn2_0.factory.*; import de.hpi.bpmn2_0.model.*; import de.hpi.bpmn2_0.model.connector.*; import de.hpi.bpmn2_0.model.data_object.*; import de.hpi.bpmn2_0.transformation.*; import java.util.*;
[ "de.hpi.bpmn2_0", "java.util" ]
de.hpi.bpmn2_0; java.util;
1,789,302
public static final SourceModel.Expr isFileOrDirectoryHidden(SourceModel.Expr fileName) { return SourceModel.Expr.Application.make( new SourceModel.Expr[] {SourceModel.Expr.Var.make(Functions.isFileOrDirectoryHidden), fileName}); } public static final QualifiedName isFileOrDirectoryHidden = QualifiedName.make(CAL_File.MODULE_NAME, "isFileOrDirectoryHidden");
static final SourceModel.Expr function(SourceModel.Expr fileName) { return SourceModel.Expr.Application.make( new SourceModel.Expr[] {SourceModel.Expr.Var.make(Functions.isFileOrDirectoryHidden), fileName}); } static final QualifiedName function = QualifiedName.make(CAL_File.MODULE_NAME, STR);
/** * Returns whether the specified file or directory is hidden. (The semantics of * being hidden is platform specific: on Windows this means having the 'hidden' * attribute set, on UNIX this means the path of the file begins with a <code>'.'</code>.) * @param fileName (CAL type: <code>Cal.IO.File.FileName</code>) * the path to check. * @return (CAL type: <code>Cal.Core.Prelude.Boolean</code>) * <code>Cal.Core.Prelude.True</code> if the specified path refers to a hidden file or directory; <code>Cal.Core.Prelude.False</code> otherwise. */
Returns whether the specified file or directory is hidden. (The semantics of being hidden is platform specific: on Windows this means having the 'hidden' attribute set, on UNIX this means the path of the file begins with a <code>'.'</code>.)
isFileOrDirectoryHidden
{ "repo_name": "levans/Open-Quark", "path": "src/CAL_Libraries/src/org/openquark/cal/module/Cal/IO/CAL_File.java", "license": "bsd-3-clause", "size": 59940 }
[ "org.openquark.cal.compiler.QualifiedName", "org.openquark.cal.compiler.SourceModel" ]
import org.openquark.cal.compiler.QualifiedName; import org.openquark.cal.compiler.SourceModel;
import org.openquark.cal.compiler.*;
[ "org.openquark.cal" ]
org.openquark.cal;
2,610,829
@Test public void testSetBackTracking() { try (RootAllocator allocator = new RootAllocator(10_000_000)) { final MaterializedField field = MaterializedField.create("stringCol", Types.required(TypeProtos.MinorType.VARCHAR)); final VarCharVector vector = new VarCharVector(field, allocator); vector.allocateNew(); try { final int size = 1000; final int fluffSize = 10000; final VarCharVector.Mutator mutator = vector.getMutator(); final VarCharVector.Accessor accessor = vector.getAccessor(); setSafeIndexStrings("", 0, size, mutator); setSafeIndexStrings("first cut ", size, fluffSize, mutator); setSafeIndexStrings("redone cut ", size, fluffSize, mutator); mutator.setValueCount(fluffSize); Assert.assertEquals(fluffSize, accessor.getValueCount()); checkIndexStrings("", 0, size, accessor); checkIndexStrings("redone cut ", size, fluffSize, accessor); } finally { vector.clear(); } } }
void function() { try (RootAllocator allocator = new RootAllocator(10_000_000)) { final MaterializedField field = MaterializedField.create(STR, Types.required(TypeProtos.MinorType.VARCHAR)); final VarCharVector vector = new VarCharVector(field, allocator); vector.allocateNew(); try { final int size = 1000; final int fluffSize = 10000; final VarCharVector.Mutator mutator = vector.getMutator(); final VarCharVector.Accessor accessor = vector.getAccessor(); setSafeIndexStrings(STRfirst cut STRredone cut STRSTRredone cut ", size, fluffSize, accessor); } finally { vector.clear(); } } }
/** * Set 10000 values. Then go back and set new values starting at the 1001 the record. */
Set 10000 values. Then go back and set new values starting at the 1001 the record
testSetBackTracking
{ "repo_name": "kkhatua/drill", "path": "exec/vector/src/test/java/org/apache/drill/exec/vector/VariableLengthVectorTest.java", "license": "apache-2.0", "size": 5853 }
[ "org.apache.drill.common.types.TypeProtos", "org.apache.drill.common.types.Types", "org.apache.drill.exec.memory.RootAllocator", "org.apache.drill.exec.record.MaterializedField" ]
import org.apache.drill.common.types.TypeProtos; import org.apache.drill.common.types.Types; import org.apache.drill.exec.memory.RootAllocator; import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.common.types.*; import org.apache.drill.exec.memory.*; import org.apache.drill.exec.record.*;
[ "org.apache.drill" ]
org.apache.drill;
2,455,359
public synchronized void appendTextNodeComment(final INaviTextNode node, final Integer commentId) throws CouldntLoadDataException { Preconditions.checkNotNull(node, "IE02561: node argument can not be null"); appendComment(new TextNodeCommentingStrategy(node), commentId); }
synchronized void function(final INaviTextNode node, final Integer commentId) throws CouldntLoadDataException { Preconditions.checkNotNull(node, STR); appendComment(new TextNodeCommentingStrategy(node), commentId); }
/** * Appends a new text node comment to the list of comments associated with the given text node. * The comment id is used to load the comment from the database. * * @param node The {@link INaviTextNode} to associated the comment with. * @param commentId The comment id to load from the database. * * @throws CouldntLoadDataException if the comment could not be loaded from the database. */
Appends a new text node comment to the list of comments associated with the given text node. The comment id is used to load the comment from the database
appendTextNodeComment
{ "repo_name": "aeppert/binnavi", "path": "src/main/java/com/google/security/zynamics/binnavi/disassembly/CommentManager.java", "license": "apache-2.0", "size": 127063 }
[ "com.google.common.base.Preconditions", "com.google.security.zynamics.binnavi.Database" ]
import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.Database;
import com.google.common.base.*; import com.google.security.zynamics.binnavi.*;
[ "com.google.common", "com.google.security" ]
com.google.common; com.google.security;
2,333,479
@Override public Iterator<Row> iterator() { return new StreamingIterator(); }
Iterator<Row> function() { return new StreamingIterator(); }
/** * Returns a new streaming iterator to loop through rows. This iterator is not * guaranteed to have all rows in memory, and any particular iteration may * trigger a load from disk to read in new data. * * @return the streaming iterator */
Returns a new streaming iterator to loop through rows. This iterator is not guaranteed to have all rows in memory, and any particular iteration may trigger a load from disk to read in new data
iterator
{ "repo_name": "nyer/excel-streaming-reader", "path": "src/main/java/com/monitorjbl/xlsx/StreamingReader.java", "license": "gpl-2.0", "size": 12699 }
[ "java.util.Iterator", "org.apache.poi.ss.usermodel.Row" ]
import java.util.Iterator; import org.apache.poi.ss.usermodel.Row;
import java.util.*; import org.apache.poi.ss.usermodel.*;
[ "java.util", "org.apache.poi" ]
java.util; org.apache.poi;
2,427,680
public static ByteBuffer toByteBuffer(INDArray arr) { //subset and get rid of 1 off non 1 element wise stride cases if (arr.isView()) arr = arr.dup(); if (!arr.isCompressed()) { ByteBuffer b3 = ByteBuffer.allocateDirect(byteBufferSizeFor(arr)).order(ByteOrder.nativeOrder()); doByteBufferPutUnCompressed(arr, b3, true); return b3; } //compressed array else { ByteBuffer b3 = ByteBuffer.allocateDirect(byteBufferSizeFor(arr)).order(ByteOrder.nativeOrder()); doByteBufferPutCompressed(arr, b3, true); return b3; } }
static ByteBuffer function(INDArray arr) { if (arr.isView()) arr = arr.dup(); if (!arr.isCompressed()) { ByteBuffer b3 = ByteBuffer.allocateDirect(byteBufferSizeFor(arr)).order(ByteOrder.nativeOrder()); doByteBufferPutUnCompressed(arr, b3, true); return b3; } else { ByteBuffer b3 = ByteBuffer.allocateDirect(byteBufferSizeFor(arr)).order(ByteOrder.nativeOrder()); doByteBufferPutCompressed(arr, b3, true); return b3; } }
/** * Convert an ndarray to an unsafe buffer * for use by aeron * @param arr the array to convert * @return the unsafebuffer representation of this array */
Convert an ndarray to an unsafe buffer for use by aeron
toByteBuffer
{ "repo_name": "huitseeker/nd4j", "path": "nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/serde/binary/BinarySerde.java", "license": "apache-2.0", "size": 12298 }
[ "java.nio.ByteBuffer", "java.nio.ByteOrder", "org.nd4j.linalg.api.ndarray.INDArray" ]
import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.nd4j.linalg.api.ndarray.INDArray;
import java.nio.*; import org.nd4j.linalg.api.ndarray.*;
[ "java.nio", "org.nd4j.linalg" ]
java.nio; org.nd4j.linalg;
561,928
protected GetFeature createGetFeatureRequest( FeatureTemplate ft, String version, QualifiedName ftName, QualifiedName gtName, GetFeature.RESULT_TYPE resultType ) throws PortalException { // read base context HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true ); ViewContext vc = (ViewContext) session.getAttribute( Constants.CURRENTMAPCONTEXT ); String srcName = vc.getGeneral().getBoundingBox()[0].getCoordinateSystem().getIdentifier(); GetFeature gfr = null; try { Geometry geom = GeometryFactory.createSurface( ft.getEnvelope(), ft.getEnvelope().getCoordinateSystem() ); Operation op = new SpatialOperation( OperationDefines.BBOX, new PropertyName( gtName ), geom ); Filter filter = new ComplexFilter( op ); IDGenerator idg = IDGenerator.getInstance(); // create WFS GetFeature request for either HITS or RESULTS Query query = Query.create( null, null, null, null, version, new QualifiedName[] { ftName }, null, srcName, filter, -1, 0, resultType ); gfr = GetFeature.create( "1.1.0", "" + idg.generateUniqueID(), resultType, "text/xml; subtype=gml/3.1.1", null, -1, 0, -1, 0, new Query[] { query } ); } catch ( Exception e ) { LOG.logError( e.getMessage(), e ); throw new PortalException( Messages.get( "IGEO_STD_CNTXT_ERROR_CREATE_GETFEATURE", ft.getTitle(), ft.getEnvelope() ) ); } return gfr; } // ///////////////////////////////////////////////////////////////////////// // inner class // // ///////////////////////////////////////////////////////////////////////// private class LoadController extends Thread { private ArrayList<RequestBean> gfrbl = null; private String errorFeatures = null; private String errorHitsException = null; private String format = "SHP"; LoadController( ArrayList<RequestBean> gfrl, String format ) { this.gfrbl = gfrl; this.format = format; }
GetFeature function( FeatureTemplate ft, String version, QualifiedName ftName, QualifiedName gtName, GetFeature.RESULT_TYPE resultType ) throws PortalException { HttpSession session = ( (HttpServletRequest) this.getRequest() ).getSession( true ); ViewContext vc = (ViewContext) session.getAttribute( Constants.CURRENTMAPCONTEXT ); String srcName = vc.getGeneral().getBoundingBox()[0].getCoordinateSystem().getIdentifier(); GetFeature gfr = null; try { Geometry geom = GeometryFactory.createSurface( ft.getEnvelope(), ft.getEnvelope().getCoordinateSystem() ); Operation op = new SpatialOperation( OperationDefines.BBOX, new PropertyName( gtName ), geom ); Filter filter = new ComplexFilter( op ); IDGenerator idg = IDGenerator.getInstance(); Query query = Query.create( null, null, null, null, version, new QualifiedName[] { ftName }, null, srcName, filter, -1, 0, resultType ); gfr = GetFeature.create( "1.1.0", STRtext/xml; subtype=gml/3.1.1STRIGEO_STD_CNTXT_ERROR_CREATE_GETFEATURESTRSHP"; LoadController( ArrayList<RequestBean> gfrl, String format ) { this.gfrbl = gfrl; this.format = format; }
/** * creates a GetFeature request considering the feature type (ID) and the bounding box encapsulated in the passed * <tt>FeatureTemplate</tt> * * @param ft * FeatureTemplate * @param ftName * a Qualified Name representing the feature type name of the requested feature, ex: app:ZipCodes * @param gtName * a Qualified Name representing the geometry type name of the requested feature, ex: app:geometry * @param resultType * the type of result (GetFeature.RESULT_TYPE.HITS or GetFeature.RESULT_TYPE.RESULTS) * @return {@link GetFeature} request to access data for download * @throws PortalException */
creates a GetFeature request considering the feature type (ID) and the bounding box encapsulated in the passed FeatureTemplate
createGetFeatureRequest
{ "repo_name": "lat-lon/deegree2-base", "path": "deegree2-core/src/main/java/org/deegree/portal/standard/context/control/DownloadListener.java", "license": "lgpl-2.1", "size": 52264 }
[ "java.util.ArrayList", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpSession", "org.deegree.datatypes.QualifiedName", "org.deegree.framework.util.IDGenerator", "org.deegree.model.filterencoding.ComplexFilter", "org.deegree.model.filterencoding.Filter", "org.deegree.model.filterencoding.Operation", "org.deegree.model.filterencoding.OperationDefines", "org.deegree.model.filterencoding.PropertyName", "org.deegree.model.filterencoding.SpatialOperation", "org.deegree.model.spatialschema.Geometry", "org.deegree.model.spatialschema.GeometryFactory", "org.deegree.ogcwebservices.wfs.operation.GetFeature", "org.deegree.ogcwebservices.wfs.operation.Query", "org.deegree.portal.Constants", "org.deegree.portal.PortalException", "org.deegree.portal.context.ViewContext" ]
import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.deegree.datatypes.QualifiedName; import org.deegree.framework.util.IDGenerator; import org.deegree.model.filterencoding.ComplexFilter; import org.deegree.model.filterencoding.Filter; import org.deegree.model.filterencoding.Operation; import org.deegree.model.filterencoding.OperationDefines; import org.deegree.model.filterencoding.PropertyName; import org.deegree.model.filterencoding.SpatialOperation; import org.deegree.model.spatialschema.Geometry; import org.deegree.model.spatialschema.GeometryFactory; import org.deegree.ogcwebservices.wfs.operation.GetFeature; import org.deegree.ogcwebservices.wfs.operation.Query; import org.deegree.portal.Constants; import org.deegree.portal.PortalException; import org.deegree.portal.context.ViewContext;
import java.util.*; import javax.servlet.http.*; import org.deegree.datatypes.*; import org.deegree.framework.util.*; import org.deegree.model.filterencoding.*; import org.deegree.model.spatialschema.*; import org.deegree.ogcwebservices.wfs.operation.*; import org.deegree.portal.*; import org.deegree.portal.context.*;
[ "java.util", "javax.servlet", "org.deegree.datatypes", "org.deegree.framework", "org.deegree.model", "org.deegree.ogcwebservices", "org.deegree.portal" ]
java.util; javax.servlet; org.deegree.datatypes; org.deegree.framework; org.deegree.model; org.deegree.ogcwebservices; org.deegree.portal;
1,402,434
public void setSubject( String subject ) { annot.setString( COSName.SUBJ, subject ); }
void function( String subject ) { annot.setString( COSName.SUBJ, subject ); }
/** * A short description of the annotation. * * @param subject The annotation subject. */
A short description of the annotation
setSubject
{ "repo_name": "myrridin/qz-print", "path": "pdfbox_1.8.4_qz/src/org/apache/pdfbox/pdmodel/fdf/FDFAnnotation.java", "license": "lgpl-2.1", "size": 15414 }
[ "org.apache.pdfbox.cos.COSName" ]
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.*;
[ "org.apache.pdfbox" ]
org.apache.pdfbox;
992,227
protected IAttributeDefinition getParentRelation() { return parentRelation; }
IAttributeDefinition function() { return parentRelation; }
/** * The the AttributeDefinition * * @return IAttributedefinition used in query */
The the AttributeDefinition
getParentRelation
{ "repo_name": "minhhai2209/VersionOne.SDK.Java.APIClient", "path": "src/main/java/com/versionone/apiclient/Query.java", "license": "bsd-3-clause", "size": 6278 }
[ "com.versionone.apiclient.interfaces.IAttributeDefinition" ]
import com.versionone.apiclient.interfaces.IAttributeDefinition;
import com.versionone.apiclient.interfaces.*;
[ "com.versionone.apiclient" ]
com.versionone.apiclient;
2,877,744
public void testModelMultipleExplicit() throws Exception { DefDescriptor<T> compDesc = addSourceAutoCleanup(getDefClass(), String.format(baseTag, "model='java://org.auraframework.components.test.java.model.TestModel,js://test.jsModel'", "")); try { definitionService.getDefinition(compDesc); fail("Should not be able to load component with multiple models"); } catch (QuickFixException e) { checkExceptionFull(e, InvalidDefinitionException.class, "Invalid Descriptor Format: java://org.auraframework.components.test.java.model.TestModel,js://test.jsModel[MODEL]"); } }
void function() throws Exception { DefDescriptor<T> compDesc = addSourceAutoCleanup(getDefClass(), String.format(baseTag, STRSTRShould not be able to load component with multiple modelsSTRInvalid Descriptor Format: java: } }
/** * Multiple models are not allowed. */
Multiple models are not allowed
testModelMultipleExplicit
{ "repo_name": "badlogicmanpreet/aura", "path": "aura-impl/src/test/java/org/auraframework/impl/root/component/BaseComponentDefTest.java", "license": "apache-2.0", "size": 99025 }
[ "org.auraframework.def.DefDescriptor" ]
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.*;
[ "org.auraframework.def" ]
org.auraframework.def;
1,618,577
public void setStateSignalName(String stateSignalName) { this.stateSignalName = stateSignalName; } public static final class Bus { private final String busName; private final ArrayList<String> signalNames; private Bus(String busName, ArrayList<String> signalNames) { this.busName = busName; this.signalNames = signalNames; }
void function(String stateSignalName) { this.stateSignalName = stateSignalName; } public static final class Bus { private final String busName; private final ArrayList<String> signalNames; private Bus(String busName, ArrayList<String> signalNames) { this.busName = busName; this.signalNames = signalNames; }
/** * Sets the state variable name * * @param stateSignalName the state variable name */
Sets the state variable name
setStateSignalName
{ "repo_name": "hneemann/Digital", "path": "src/main/java/de/neemann/digital/analyse/ModelAnalyserInfo.java", "license": "gpl-3.0", "size": 5532 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
2,752,566
//----------------------------------------------------------------------- @Override public Currency getCurrency() { return currency; }
Currency function() { return currency; }
/** * Gets the currency of the index. * @return the value of the property, not null */
Gets the currency of the index
getCurrency
{ "repo_name": "jmptrader/Strata", "path": "modules/basics/src/main/java/com/opengamma/strata/basics/index/ImmutablePriceIndex.java", "license": "apache-2.0", "size": 17306 }
[ "com.opengamma.strata.basics.currency.Currency" ]
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.*;
[ "com.opengamma.strata" ]
com.opengamma.strata;
2,856,950
@ApiModelProperty(value = "") public String getIndustry() { return industry; }
@ApiModelProperty(value = "") String function() { return industry; }
/** * Get industry * @return industry **/
Get industry
getIndustry
{ "repo_name": "LogSentinel/logsentinel-java-client", "path": "src/main/java/com/logsentinel/model/UserRegistrationRequest.java", "license": "mit", "size": 13170 }
[ "io.swagger.annotations.ApiModelProperty" ]
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
[ "io.swagger.annotations" ]
io.swagger.annotations;
701,507
private static void injectContentView(Activity activity) { Class<? extends Activity> clazz = activity.getClass(); ContentView contentView = clazz.getAnnotation(ContentView.class); if (contentView != null) { int contentViewLayoutId = contentView.value(); try { Method method = clazz.getMethod(METHOD_SET_CONTENTVIEW, int.class); method.setAccessible(true); method.invoke(activity, contentViewLayoutId); } catch (Exception e) { e.printStackTrace(); } } }
static void function(Activity activity) { Class<? extends Activity> clazz = activity.getClass(); ContentView contentView = clazz.getAnnotation(ContentView.class); if (contentView != null) { int contentViewLayoutId = contentView.value(); try { Method method = clazz.getMethod(METHOD_SET_CONTENTVIEW, int.class); method.setAccessible(true); method.invoke(activity, contentViewLayoutId); } catch (Exception e) { e.printStackTrace(); } } }
/** * Inject layout * * @param activity */
Inject layout
injectContentView
{ "repo_name": "LLin233/Le-Android-Demo-Stack", "path": "viewinjectdemo/src/main/java/androidpath/ll/viewinjectdemo/lib/ViewInjectUtils.java", "license": "mit", "size": 4803 }
[ "android.app.Activity", "java.lang.reflect.Method" ]
import android.app.Activity; import java.lang.reflect.Method;
import android.app.*; import java.lang.reflect.*;
[ "android.app", "java.lang" ]
android.app; java.lang;
1,951,733
public static MozuClient<com.mozu.api.contracts.productadmin.Attribute> updateAttributeClient(com.mozu.api.contracts.productadmin.Attribute attribute, String attributeFQN) throws Exception { return updateAttributeClient( attribute, attributeFQN, null); }
static MozuClient<com.mozu.api.contracts.productadmin.Attribute> function(com.mozu.api.contracts.productadmin.Attribute attribute, String attributeFQN) throws Exception { return updateAttributeClient( attribute, attributeFQN, null); }
/** * Updates an existing attribute with attribute properties to set. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.Attribute> mozuClient=UpdateAttributeClient( attribute, attributeFQN); * client.setBaseAddress(url); * client.executeRequest(); * Attribute attribute = client.Result(); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param dataViewMode DataViewMode * @param attribute Properties of an attribute used to describe customers or orders. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Attribute> * @see com.mozu.api.contracts.productadmin.Attribute * @see com.mozu.api.contracts.productadmin.Attribute */
Updates an existing attribute with attribute properties to set. <code><code> MozuClient mozuClient=UpdateAttributeClient( attribute, attributeFQN); client.setBaseAddress(url); client.executeRequest(); Attribute attribute = client.Result(); </code></code>
updateAttributeClient
{ "repo_name": "lakshmi-nair/mozu-java", "path": "mozu-javaasync-core/src/main/java/com/mozu/api/clients/commerce/catalog/admin/attributedefinition/AttributeClient.java", "license": "mit", "size": 12562 }
[ "com.mozu.api.MozuClient" ]
import com.mozu.api.MozuClient;
import com.mozu.api.*;
[ "com.mozu.api" ]
com.mozu.api;
2,600,238
void enterReturnStatement(@NotNull ECMAScriptParser.ReturnStatementContext ctx); void exitReturnStatement(@NotNull ECMAScriptParser.ReturnStatementContext ctx);
void enterReturnStatement(@NotNull ECMAScriptParser.ReturnStatementContext ctx); void exitReturnStatement(@NotNull ECMAScriptParser.ReturnStatementContext ctx);
/** * Exit a parse tree produced by {@link ECMAScriptParser#returnStatement}. * @param ctx the parse tree */
Exit a parse tree produced by <code>ECMAScriptParser#returnStatement</code>
exitReturnStatement
{ "repo_name": "IsThisThePayneResidence/intellidots", "path": "src/main/java/ua/edu/hneu/ast/parsers/ECMAScriptListener.java", "license": "gpl-3.0", "size": 39591 }
[ "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;
44,088
public void loadImage(BufferedImage image){ this.image = image; if(image == null){ return; } setScale(this.getPreferredScale(image)); x = y = 0; repaint(); }
void function(BufferedImage image){ this.image = image; if(image == null){ return; } setScale(this.getPreferredScale(image)); x = y = 0; repaint(); }
/** * Loads the image * @param image The current image */
Loads the image
loadImage
{ "repo_name": "Skylion007/java-manga-reader", "path": "src/org/skylion/mangareader/util/ImagePanel.java", "license": "gpl-3.0", "size": 12203 }
[ "java.awt.image.BufferedImage" ]
import java.awt.image.BufferedImage;
import java.awt.image.*;
[ "java.awt" ]
java.awt;
2,239,477
private ScanCostReport estimateCost(final IScaleOutClientIndex ndx) { final String name = ndx.getIndexMetadata().getName(); final AbstractClient<?> client = ndx.getFederation().getClient(); // maximum parallelization by the client : @todo not used yet. final int maxParallel = client.getMaxParallelTasksPerRequest(); // the metadata index for that scale-out index. final IMetadataIndex mdi = ndx.getFederation().getMetadataIndex(name, timestamp); if (mdi == null) throw new NoSuchIndexException("name=" + name + "@" + TimestampUtility.toString(timestamp)); // #of index partitions to be scanned. final long partitionCount = mdi.rangeCount(fromKey, toKey); if (partitionCount == 0) { return new ScanCostReport(0L, partitionCount, 100); // // throw new AssertionError(); } // fast range count (may be cached by the access path). final long rangeCount = rangeCount(false); if (partitionCount == 1) { return (ScanCostReport) ndx.submit( fromKey == null ? BytesUtil.EMPTY : fromKey, new EstimateShardScanCost(rangeCount, fromKey, toKey)); } // one journal per shard. final int njournals = 1; // two segments per shard. final int nsegments = 2; final long rangeCountOnJournal = rangeCount / (partitionCount * (njournals + nsegments)); final double costPerJournal = new BTreeCostModel(diskCostModel) .rangeScan(rangeCountOnJournal, // mdi.getIndexMetadata().getBranchingFactor(), // 5,// height (SWAG) 70// leafUtilization (percent, SWAG). ); final double costPerSegment = diskCostModel.seekTime + Bytes.megabyte * 100; final double costPerShard = costPerJournal + 2 * costPerSegment; // @todo ignores potential parallelism. final double cost = costPerShard * partitionCount; return new ScanCostReport(rangeCount, partitionCount, cost); } private static final class EstimateShardScanCost implements ISimpleIndexProcedure<ScanCostReport> { private static final long serialVersionUID = 1L; private final long rangeCount; private final byte[] fromKey; private final byte[] toKey; public EstimateShardScanCost(final long rangeCount, final byte[] fromKey, final byte[] toKey) { this.rangeCount = rangeCount; this.fromKey = fromKey; this.toKey = toKey; }
ScanCostReport function(final IScaleOutClientIndex ndx) { final String name = ndx.getIndexMetadata().getName(); final AbstractClient<?> client = ndx.getFederation().getClient(); final int maxParallel = client.getMaxParallelTasksPerRequest(); final IMetadataIndex mdi = ndx.getFederation().getMetadataIndex(name, timestamp); if (mdi == null) throw new NoSuchIndexException("name=" + name + "@" + TimestampUtility.toString(timestamp)); final long partitionCount = mdi.rangeCount(fromKey, toKey); if (partitionCount == 0) { return new ScanCostReport(0L, partitionCount, 100); } final long rangeCount = rangeCount(false); if (partitionCount == 1) { return (ScanCostReport) ndx.submit( fromKey == null ? BytesUtil.EMPTY : fromKey, new EstimateShardScanCost(rangeCount, fromKey, toKey)); } final int njournals = 1; final int nsegments = 2; final long rangeCountOnJournal = rangeCount / (partitionCount * (njournals + nsegments)); final double costPerJournal = new BTreeCostModel(diskCostModel) .rangeScan(rangeCountOnJournal, 5, 70 ); final double costPerSegment = diskCostModel.seekTime + Bytes.megabyte * 100; final double costPerShard = costPerJournal + 2 * costPerSegment; final double cost = costPerShard * partitionCount; return new ScanCostReport(rangeCount, partitionCount, cost); } private static final class EstimateShardScanCost implements ISimpleIndexProcedure<ScanCostReport> { private static final long serialVersionUID = 1L; private final long rangeCount; private final byte[] fromKey; private final byte[] toKey; public EstimateShardScanCost(final long rangeCount, final byte[] fromKey, final byte[] toKey) { this.rangeCount = rangeCount; this.fromKey = fromKey; this.toKey = toKey; }
/** * Return the estimated cost of a key-range scan on a remote view of a * scale-out index. * * @param ndx * The scale-out index. * * @return * * @todo Remote scans can be parallelized. If flags includes PARALLEL then * the cost can be as little as the cost of scanning one shard. * However, the {@link IClientIndex} has a configuration value which * specifies the maximum parallelism of any given operation (this is * self-reported if we cast to the implementation class). Further, * even if we assume that the shards are evenly distributed over the * nodes, when the #of shards is significantly larger than the #of * nodes then the scan can interfere with itself. Finally, this should * include an estimate of the RMI overhead. */
Return the estimated cost of a key-range scan on a remote view of a scale-out index
estimateCost
{ "repo_name": "blazegraph/database", "path": "bigdata-core/bigdata/src/java/com/bigdata/relation/accesspath/AccessPath.java", "license": "gpl-2.0", "size": 60814 }
[ "com.bigdata.bop.cost.BTreeCostModel", "com.bigdata.bop.cost.ScanCostReport", "com.bigdata.btree.proc.ISimpleIndexProcedure", "com.bigdata.journal.NoSuchIndexException", "com.bigdata.journal.TimestampUtility", "com.bigdata.mdi.IMetadataIndex", "com.bigdata.service.AbstractClient", "com.bigdata.service.ndx.IScaleOutClientIndex", "com.bigdata.util.Bytes", "com.bigdata.util.BytesUtil" ]
import com.bigdata.bop.cost.BTreeCostModel; import com.bigdata.bop.cost.ScanCostReport; import com.bigdata.btree.proc.ISimpleIndexProcedure; import com.bigdata.journal.NoSuchIndexException; import com.bigdata.journal.TimestampUtility; import com.bigdata.mdi.IMetadataIndex; import com.bigdata.service.AbstractClient; import com.bigdata.service.ndx.IScaleOutClientIndex; import com.bigdata.util.Bytes; import com.bigdata.util.BytesUtil;
import com.bigdata.bop.cost.*; import com.bigdata.btree.proc.*; import com.bigdata.journal.*; import com.bigdata.mdi.*; import com.bigdata.service.*; import com.bigdata.service.ndx.*; import com.bigdata.util.*;
[ "com.bigdata.bop", "com.bigdata.btree", "com.bigdata.journal", "com.bigdata.mdi", "com.bigdata.service", "com.bigdata.util" ]
com.bigdata.bop; com.bigdata.btree; com.bigdata.journal; com.bigdata.mdi; com.bigdata.service; com.bigdata.util;
2,194,904
@Test public void testCreate() throws SQLException { ExtensionsUtils.testCreate(geoPackage); }
void function() throws SQLException { ExtensionsUtils.testCreate(geoPackage); }
/** * Test creating * * @throws SQLException */
Test creating
testCreate
{ "repo_name": "ngageoint/geopackage-java", "path": "src/test/java/mil/nga/geopackage/extension/ExtensionsCreateTest.java", "license": "mit", "size": 1088 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
2,395,028
private void setVisibleCalculculationResult(SunriseSunsetCalculator calculator) { mNightResult.setText(calculator.getNight()); mAstroDawnResult.setText(calculator.getAstroDawn()); mSunriseResult.setText(calculator.getSunrise()); mSunsetResult.setText(calculator.getSunset()); mCivilDawnResult.setText(calculator.getDawn()); mCivilDuskResult.setText(calculator.getDusk()); mNauticalDawnResult.setText(calculator.getNauticalDawn()); mNauticalDuskResult.setText(calculator.getNauticalDusk()); mAstroDuskResult.setText(calculator.getAstroDusk()); mSolarNoonResult.setText(calculator.getSolarNoon()); mGoldenHourDawnResult.setText(calculator.getGoldenHourDawn()); mGoldenHourDuskResult.setText(calculator.getGoldenHourDusk()); mLinearLayoutCalculationResult.setVisibility(View.VISIBLE); }
void function(SunriseSunsetCalculator calculator) { mNightResult.setText(calculator.getNight()); mAstroDawnResult.setText(calculator.getAstroDawn()); mSunriseResult.setText(calculator.getSunrise()); mSunsetResult.setText(calculator.getSunset()); mCivilDawnResult.setText(calculator.getDawn()); mCivilDuskResult.setText(calculator.getDusk()); mNauticalDawnResult.setText(calculator.getNauticalDawn()); mNauticalDuskResult.setText(calculator.getNauticalDusk()); mAstroDuskResult.setText(calculator.getAstroDusk()); mSolarNoonResult.setText(calculator.getSolarNoon()); mGoldenHourDawnResult.setText(calculator.getGoldenHourDawn()); mGoldenHourDuskResult.setText(calculator.getGoldenHourDusk()); mLinearLayoutCalculationResult.setVisibility(View.VISIBLE); }
/** * Sets visible calculation result scrollView * * @param calculator */
Sets visible calculation result scrollView
setVisibleCalculculationResult
{ "repo_name": "yankovskiy/PhotoTools", "path": "photoTools/src/main/java/ru/neverdark/phototools/fragments/SunsetFragment.java", "license": "gpl-3.0", "size": 26770 }
[ "android.view.View", "ru.neverdark.sunmooncalc.SunriseSunsetCalculator" ]
import android.view.View; import ru.neverdark.sunmooncalc.SunriseSunsetCalculator;
import android.view.*; import ru.neverdark.sunmooncalc.*;
[ "android.view", "ru.neverdark.sunmooncalc" ]
android.view; ru.neverdark.sunmooncalc;
2,284,902
public List<Service> getServices() { return services; }
List<Service> function() { return services; }
/** * Get the list of the discovery services. * * @return the discovery services */
Get the list of the discovery services
getServices
{ "repo_name": "bbrinkus/neo4j-eureka-plugin", "path": "src/main/java/com/brinkus/labs/neo4j/eureka/type/config/Configuration.java", "license": "gpl-3.0", "size": 1957 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,076,055
@SuppressWarnings("unchecked") private @Nullable BigDecimal commandToRoundedTemperature(Command command, Unit<Temperature> unit) throws IllegalArgumentException { QuantityType<Temperature> quantity; if (command instanceof QuantityType) { quantity = (QuantityType<Temperature>) command; } else { quantity = new QuantityType<Temperature>(new BigDecimal(command.toString()), unit); } QuantityType<Temperature> temparatureQuantity = quantity.toUnit(unit); if (temparatureQuantity == null) { return null; } BigDecimal value = temparatureQuantity.toBigDecimal(); BigDecimal increment = CELSIUS == unit ? new BigDecimal("0.5") : new BigDecimal("1"); BigDecimal divisor = value.divide(increment, 0, RoundingMode.HALF_UP); return divisor.multiply(increment); }
@SuppressWarnings(STR) @Nullable BigDecimal function(Command command, Unit<Temperature> unit) throws IllegalArgumentException { QuantityType<Temperature> quantity; if (command instanceof QuantityType) { quantity = (QuantityType<Temperature>) command; } else { quantity = new QuantityType<Temperature>(new BigDecimal(command.toString()), unit); } QuantityType<Temperature> temparatureQuantity = quantity.toUnit(unit); if (temparatureQuantity == null) { return null; } BigDecimal value = temparatureQuantity.toBigDecimal(); BigDecimal increment = CELSIUS == unit ? new BigDecimal("0.5") : new BigDecimal("1"); BigDecimal divisor = value.divide(increment, 0, RoundingMode.HALF_UP); return divisor.multiply(increment); }
/** * inspired by the openHAB Nest thermostat binding */
inspired by the openHAB Nest thermostat binding
commandToRoundedTemperature
{ "repo_name": "Snickermicker/openhab2", "path": "bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/handler/IAqualinkHandler.java", "license": "epl-1.0", "size": 22206 }
[ "java.math.BigDecimal", "java.math.RoundingMode", "javax.measure.Unit", "javax.measure.quantity.Temperature", "org.eclipse.jdt.annotation.Nullable", "org.eclipse.smarthome.core.library.types.QuantityType", "org.eclipse.smarthome.core.types.Command" ]
import java.math.BigDecimal; import java.math.RoundingMode; import javax.measure.Unit; import javax.measure.quantity.Temperature; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.library.types.QuantityType; import org.eclipse.smarthome.core.types.Command;
import java.math.*; import javax.measure.*; import javax.measure.quantity.*; import org.eclipse.jdt.annotation.*; import org.eclipse.smarthome.core.library.types.*; import org.eclipse.smarthome.core.types.*;
[ "java.math", "javax.measure", "org.eclipse.jdt", "org.eclipse.smarthome" ]
java.math; javax.measure; org.eclipse.jdt; org.eclipse.smarthome;
1,059,450
public ContactInfoJson getContactInfo(final String user) { return getContactInfo(user, null); }
ContactInfoJson function(final String user) { return getContactInfo(user, null); }
/** * DOCUMENT ME! * * @param user DOCUMENT ME! * * @return DOCUMENT ME! */
DOCUMENT ME
getContactInfo
{ "repo_name": "cismet/verdis-server", "path": "src/main/java/de/cismet/verdis/server/utils/AenderungsanfrageUtils.java", "license": "lgpl-3.0", "size": 89795 }
[ "de.cismet.verdis.server.json.ContactInfoJson" ]
import de.cismet.verdis.server.json.ContactInfoJson;
import de.cismet.verdis.server.json.*;
[ "de.cismet.verdis" ]
de.cismet.verdis;
241,326
public int executeUpdateBySql(Connection connection,String sql,Object[] parameters) throws QueryException{ PreparedStatement preparedStatement=null; int updateResult=0; try{ sql=DatabaseMappingUtil.parseSql(sql); logger.info(sql); preparedStatement=connection.prepareStatement(sql); if(parameters!=null){ int index=1; for(Object parameter:parameters){ this.sqlProcessor.statementProcess(preparedStatement, index, parameter); index++; } } updateResult=preparedStatement.executeUpdate(); }catch(Exception e){ throw new QueryException(e); }finally{ if(preparedStatement!=null){ try { preparedStatement.close(); } catch (Exception e) { throw new QueryException(e); } } } return updateResult; }
int function(Connection connection,String sql,Object[] parameters) throws QueryException{ PreparedStatement preparedStatement=null; int updateResult=0; try{ sql=DatabaseMappingUtil.parseSql(sql); logger.info(sql); preparedStatement=connection.prepareStatement(sql); if(parameters!=null){ int index=1; for(Object parameter:parameters){ this.sqlProcessor.statementProcess(preparedStatement, index, parameter); index++; } } updateResult=preparedStatement.executeUpdate(); }catch(Exception e){ throw new QueryException(e); }finally{ if(preparedStatement!=null){ try { preparedStatement.close(); } catch (Exception e) { throw new QueryException(e); } } } return updateResult; }
/** * <p>Method: execute update by sql statement</p> * @param connection * @param sql include insert delete update * @param parameters * @return int * @throws QueryException */
Method: execute update by sql statement
executeUpdateBySql
{ "repo_name": "oneliang/frame-common-java", "path": "src/main/java/com/oneliang/frame/jdbc/BaseQueryImpl.java", "license": "apache-2.0", "size": 27188 }
[ "java.sql.Connection", "java.sql.PreparedStatement" ]
import java.sql.Connection; import java.sql.PreparedStatement;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,897,081
protected void installKeyboardActions() { SwingUtilities.replaceUIInputMap(comboBox, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, (InputMap) UIManager.get("ComboBox.ancestorInputMap")); // Install any action maps here. }
void function() { SwingUtilities.replaceUIInputMap(comboBox, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, (InputMap) UIManager.get(STR)); }
/** * Installs the keyboard actions for the {@link JComboBox} as specified * by the look and feel. */
Installs the keyboard actions for the <code>JComboBox</code> as specified by the look and feel
installKeyboardActions
{ "repo_name": "taciano-perez/JamVM-PH", "path": "src/classpath/javax/swing/plaf/basic/BasicComboBoxUI.java", "license": "gpl-2.0", "size": 40740 }
[ "javax.swing.InputMap", "javax.swing.JComponent", "javax.swing.SwingUtilities", "javax.swing.UIManager" ]
import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.UIManager;
import javax.swing.*;
[ "javax.swing" ]
javax.swing;
1,670,216
Set<String> listProviders();
Set<String> listProviders();
/** * get a Set containing the id of all registered ICapabilityProviders. * @return Set containing the IDs of all registered providers */
get a Set containing the id of all registered ICapabilityProviders
listProviders
{ "repo_name": "candentira/pentaho-osgi-bundles", "path": "pentaho-capability-manager/src/main/java/org/pentaho/capabilities/api/ICapabilityManager.java", "license": "apache-2.0", "size": 752 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,875,526
private void drawDurationString(Graphics2D g2) { Duration dur = m_item.getDuration(); String duration = makeDurationString(dur); FontMetrics fm = g2.getFontMetrics(m_durationStringFont); g2.setFont(m_durationStringFont); g2.setColor(m_durationColor); g2.drawString(duration, getWidth() - fm.stringWidth(duration) - 10, 25); }
void function(Graphics2D g2) { Duration dur = m_item.getDuration(); String duration = makeDurationString(dur); FontMetrics fm = g2.getFontMetrics(m_durationStringFont); g2.setFont(m_durationStringFont); g2.setColor(m_durationColor); g2.drawString(duration, getWidth() - fm.stringWidth(duration) - 10, 25); }
/** * draw the duratation in the pane (like "2 hours, 1 minute") * @param g2 the graphics to draw with */
draw the duratation in the pane (like "2 hours, 1 minute")
drawDurationString
{ "repo_name": "MartijnTheunissen/PLNR", "path": "src/psopv/taskplanner/views/jcomponents/ListViewTaskInfoPane.java", "license": "gpl-2.0", "size": 6152 }
[ "java.awt.FontMetrics", "java.awt.Graphics2D", "java.time.Duration" ]
import java.awt.FontMetrics; import java.awt.Graphics2D; import java.time.Duration;
import java.awt.*; import java.time.*;
[ "java.awt", "java.time" ]
java.awt; java.time;
245,325
private int calculateRetryAttemptsCount(JdbcThinTcpIo stickyIo, JdbcRequest req) { if (!partitionAwareness) return NO_RETRIES; if (stickyIo != null) return NO_RETRIES; if (req.type() == JdbcRequest.META_TABLES || req.type() == JdbcRequest.META_COLUMNS || req.type() == JdbcRequest.META_INDEXES || req.type() == JdbcRequest.META_PARAMS || req.type() == JdbcRequest.META_PRIMARY_KEYS || req.type() == JdbcRequest.META_SCHEMAS || req.type() == JdbcRequest.CACHE_PARTITIONS) return DFLT_RETRIES_CNT; if (req.type() == JdbcRequest.QRY_EXEC) { JdbcQueryExecuteRequest qryExecReq = (JdbcQueryExecuteRequest)req; String trimmedQry = qryExecReq.sqlQuery().trim(); // Last symbol is ignored. for (int i = 0; i < trimmedQry.length() - 1; i++) { if (trimmedQry.charAt(i) == ';') return NO_RETRIES; } return trimmedQry.toUpperCase().startsWith("SELECT") ? DFLT_RETRIES_CNT : NO_RETRIES; } return NO_RETRIES; } private class RequestTimeoutTask implements Runnable { private final long reqId; private final JdbcThinTcpIo stickyIO; private int remainingQryTimeout; private AtomicBoolean expired; RequestTimeoutTask(long reqId, JdbcThinTcpIo stickyIO, int initReqTimeout) { this.reqId = reqId; this.stickyIO = stickyIO; remainingQryTimeout = initReqTimeout; expired = new AtomicBoolean(false); }
int function(JdbcThinTcpIo stickyIo, JdbcRequest req) { if (!partitionAwareness) return NO_RETRIES; if (stickyIo != null) return NO_RETRIES; if (req.type() == JdbcRequest.META_TABLES req.type() == JdbcRequest.META_COLUMNS req.type() == JdbcRequest.META_INDEXES req.type() == JdbcRequest.META_PARAMS req.type() == JdbcRequest.META_PRIMARY_KEYS req.type() == JdbcRequest.META_SCHEMAS req.type() == JdbcRequest.CACHE_PARTITIONS) return DFLT_RETRIES_CNT; if (req.type() == JdbcRequest.QRY_EXEC) { JdbcQueryExecuteRequest qryExecReq = (JdbcQueryExecuteRequest)req; String trimmedQry = qryExecReq.sqlQuery().trim(); for (int i = 0; i < trimmedQry.length() - 1; i++) { if (trimmedQry.charAt(i) == ';') return NO_RETRIES; } return trimmedQry.toUpperCase().startsWith(STR) ? DFLT_RETRIES_CNT : NO_RETRIES; } return NO_RETRIES; } private class RequestTimeoutTask implements Runnable { private final long reqId; private final JdbcThinTcpIo stickyIO; private int remainingQryTimeout; private AtomicBoolean expired; RequestTimeoutTask(long reqId, JdbcThinTcpIo stickyIO, int initReqTimeout) { this.reqId = reqId; this.stickyIO = stickyIO; remainingQryTimeout = initReqTimeout; expired = new AtomicBoolean(false); }
/** * Calculates query retries count for given {@param req}. * * @param stickyIo sticky connection, if any. * @param req Jdbc request. * @return retries count. */
Calculates query retries count for given req
calculateRetryAttemptsCount
{ "repo_name": "nizhikov/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcThinConnection.java", "license": "apache-2.0", "size": 85291 }
[ "java.util.concurrent.atomic.AtomicBoolean", "org.apache.ignite.internal.processors.odbc.jdbc.JdbcQueryExecuteRequest", "org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest" ]
import java.util.concurrent.atomic.AtomicBoolean; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcQueryExecuteRequest; import org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest;
import java.util.concurrent.atomic.*; import org.apache.ignite.internal.processors.odbc.jdbc.*;
[ "java.util", "org.apache.ignite" ]
java.util; org.apache.ignite;
2,737,208
//----------------------------------------------------------------------------------- @Override protected Cursor OpenCursor(Query Search) throws PDException { if (PDLog.isDebug()) PDLog.Debug("DriverRemote.OpenCursor:"+Search); Node N=ReadWrite(S_SELECT, "<OPD><Query>"+Search.toXML()+"</Query></OPD>"); Vector Res=new Vector(); NodeList RecLst = N.getChildNodes(); for (int i = 0; i < RecLst.getLength(); i++) { Node Rec = RecLst.item(i); Record R; R=Record.CreateFromXML(Rec); R.initList(); for (int j = 0; j < R.NumAttr(); j++) { Attribute Attr=R.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } Res.add(R); } Record RF=Search.getRetrieveFields(); RF.initList(); for (int j = 0; j < RF.NumAttr(); j++) { Attribute Attr=RF.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } return(StoreCursor(Res, RF)); }
Cursor function(Query Search) throws PDException { if (PDLog.isDebug()) PDLog.Debug(STR+Search); Node N=ReadWrite(S_SELECT, STR+Search.toXML()+STR); Vector Res=new Vector(); NodeList RecLst = N.getChildNodes(); for (int i = 0; i < RecLst.getLength(); i++) { Node Rec = RecLst.item(i); Record R; R=Record.CreateFromXML(Rec); R.initList(); for (int j = 0; j < R.NumAttr(); j++) { Attribute Attr=R.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } Res.add(R); } Record RF=Search.getRetrieveFields(); RF.initList(); for (int j = 0; j < RF.NumAttr(); j++) { Attribute Attr=RF.nextAttr(); if (Attr.getName().contains("."+PDDocs.fVERSION)) Attr.setName(PDDocs.fVERSION); else if (Attr.getName().contains("."+PDDocs.fPDID)) Attr.setName(PDDocs.fPDID); } return(StoreCursor(Res, RF)); }
/** * Opens a cursor * @param Search * @return String identifier of the cursor * @throws PDException */
Opens a cursor
OpenCursor
{ "repo_name": "JHierrot/openprodoc", "path": "Prodoc/src/prodoc/DriverRemote.java", "license": "agpl-3.0", "size": 21408 }
[ "java.util.Vector", "org.w3c.dom.Node", "org.w3c.dom.NodeList" ]
import java.util.Vector; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
import java.util.*; import org.w3c.dom.*;
[ "java.util", "org.w3c.dom" ]
java.util; org.w3c.dom;
257,124
public void setDateFromString(String date) { this.date = WAKDateParser.parse(date); } public Mail() { } public Mail(String id, String title, String sender, String body, Calendar date) { super(); this.id = id; this.title = title; this.sender = sender; this.body = body; this.date = date; }
void function(String date) { this.date = WAKDateParser.parse(date); } public Mail() { } public Mail(String id, String title, String sender, String body, Calendar date) { super(); this.id = id; this.title = title; this.sender = sender; this.body = body; this.date = date; }
/** * Helper method to set the date from the Date string given on the * web site. * @param date */
Helper method to set the date from the Date string given on the web site
setDateFromString
{ "repo_name": "passy/WAKiMail", "path": "WAKiMail/src/main/java/net/rdrei/android/wakimail/wak/Mail.java", "license": "mit", "size": 1788 }
[ "java.util.Calendar" ]
import java.util.Calendar;
import java.util.*;
[ "java.util" ]
java.util;
178,795
public static <T> CompletableFuture<T> orTimeout( CompletableFuture<T> future, long timeout, TimeUnit timeUnit, Executor timeoutFailExecutor, @Nullable String timeoutMsg) { if (!future.isDone()) { final ScheduledFuture<?> timeoutFuture = Delayer.delay( () -> timeoutFailExecutor.execute(new Timeout(future, timeoutMsg)), timeout, timeUnit); future.whenComplete( (T value, Throwable throwable) -> { if (!timeoutFuture.isDone()) { timeoutFuture.cancel(false); } }); } return future; } // ------------------------------------------------------------------------ // Future actions // ------------------------------------------------------------------------
static <T> CompletableFuture<T> function( CompletableFuture<T> future, long timeout, TimeUnit timeUnit, Executor timeoutFailExecutor, @Nullable String timeoutMsg) { if (!future.isDone()) { final ScheduledFuture<?> timeoutFuture = Delayer.delay( () -> timeoutFailExecutor.execute(new Timeout(future, timeoutMsg)), timeout, timeUnit); future.whenComplete( (T value, Throwable throwable) -> { if (!timeoutFuture.isDone()) { timeoutFuture.cancel(false); } }); } return future; }
/** * Times the given future out after the timeout. * * @param future to time out * @param timeout after which the given future is timed out * @param timeUnit time unit of the timeout * @param timeoutFailExecutor executor that will complete the future exceptionally after the * timeout is reached * @param timeoutMsg timeout message for exception * @param <T> type of the given future * @return The timeout enriched future */
Times the given future out after the timeout
orTimeout
{ "repo_name": "kl0u/flink", "path": "flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java", "license": "apache-2.0", "size": 57033 }
[ "java.util.concurrent.CompletableFuture", "java.util.concurrent.Executor", "java.util.concurrent.ScheduledFuture", "java.util.concurrent.TimeUnit", "javax.annotation.Nullable" ]
import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable;
import java.util.concurrent.*; import javax.annotation.*;
[ "java.util", "javax.annotation" ]
java.util; javax.annotation;
2,400,256
public HttpServletResponse getResponse() { return response; }
HttpServletResponse function() { return response; }
/** * the HttpServletResponse the handler is writing to. */
the HttpServletResponse the handler is writing to
getResponse
{ "repo_name": "lummyare/lummyare-lummy", "path": "java/server/src/org/openqa/grid/web/servlet/handler/RequestHandler.java", "license": "apache-2.0", "size": 9643 }
[ "javax.servlet.http.HttpServletResponse" ]
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
[ "javax.servlet" ]
javax.servlet;
850,986
public void copy(int srcIdx, ByteBuf dst, int dstIdx, int length) { if (dst == null) { throw new NullPointerException("dst"); } final byte[] value = this.value; final int thisLen = value.length; if (srcIdx < 0 || length > thisLen - srcIdx) { throw new IndexOutOfBoundsException("expected: " + "0 <= srcIdx(" + srcIdx + ") <= srcIdx + length(" + length + ") <= srcLen(" + thisLen + ')'); } dst.setBytes(dstIdx, value, srcIdx, length); }
void function(int srcIdx, ByteBuf dst, int dstIdx, int length) { if (dst == null) { throw new NullPointerException("dst"); } final byte[] value = this.value; final int thisLen = value.length; if (srcIdx < 0 length > thisLen - srcIdx) { throw new IndexOutOfBoundsException(STR + STR + srcIdx + STR + length + STR + thisLen + ')'); } dst.setBytes(dstIdx, value, srcIdx, length); }
/** * Copies the content of this string to a {@link ByteBuf} using {@link ByteBuf#writeBytes(byte[], int, int)}. * * @param srcIdx * the starting offset of characters to copy. * @param dst * the destination byte array. * @param dstIdx * the starting offset in the destination byte array. * @param length * the number of characters to copy. */
Copies the content of this string to a <code>ByteBuf</code> using <code>ByteBuf#writeBytes(byte[], int, int)</code>
copy
{ "repo_name": "sunng87/netty", "path": "codec/src/main/java/io/netty/handler/codec/AsciiString.java", "license": "apache-2.0", "size": 49215 }
[ "io.netty.buffer.ByteBuf" ]
import io.netty.buffer.ByteBuf;
import io.netty.buffer.*;
[ "io.netty.buffer" ]
io.netty.buffer;
134,658
public Map<String, ObjectiveFunctionParameterType> getObjectiveFunctionParameterTypes(String ofID) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { Class<? extends IObjectiveFunction> ofKlazz = mapObjectiveFunctions.get(ofID); Object untypedObj = ofKlazz.newInstance(); IObjectiveFunction of = IObjectiveFunction.class.cast(untypedObj); Map<String, ObjectiveFunctionParameterType> types = (Map<String, ObjectiveFunctionParameterType>) of.mandatoryParameters(); return types; }
Map<String, ObjectiveFunctionParameterType> function(String ofID) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { Class<? extends IObjectiveFunction> ofKlazz = mapObjectiveFunctions.get(ofID); Object untypedObj = ofKlazz.newInstance(); IObjectiveFunction of = IObjectiveFunction.class.cast(untypedObj); Map<String, ObjectiveFunctionParameterType> types = (Map<String, ObjectiveFunctionParameterType>) of.mandatoryParameters(); return types; }
/** * Reflective method to return the parameter types of a given objective * function * * @param ofID the key (identifier) of a registered objective function * @return * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws InstantiationException */
Reflective method to return the parameter types of a given objective function
getObjectiveFunctionParameterTypes
{ "repo_name": "MEWorkbench/mewcore", "path": "src/main/java/pt/uminho/ceb/biosystems/mew/core/strainoptimization/objectivefunctions/ObjectiveFunctionsFactory.java", "license": "lgpl-2.1", "size": 7593 }
[ "java.lang.reflect.InvocationTargetException", "java.util.Map" ]
import java.lang.reflect.InvocationTargetException; import java.util.Map;
import java.lang.reflect.*; import java.util.*;
[ "java.lang", "java.util" ]
java.lang; java.util;
2,856,659
public void testInvalidEnum() { String example = "dD_oN"; try { DriverDistractionState temp = DriverDistractionState.valueForString(example); assertNull("Result of valueForString should be null.", temp); } catch (IllegalArgumentException exception) { fail("Invalid enum throws IllegalArgumentException."); } }
void function() { String example = "dD_oN"; try { DriverDistractionState temp = DriverDistractionState.valueForString(example); assertNull(STR, temp); } catch (IllegalArgumentException exception) { fail(STR); } }
/** * Verifies that an invalid assignment is null. */
Verifies that an invalid assignment is null
testInvalidEnum
{ "repo_name": "smartdevicelink/sdl_android", "path": "android/sdl_android/src/androidTest/java/com/smartdevicelink/test/rpc/enums/DriverDistractionStateTests.java", "license": "bsd-3-clause", "size": 2426 }
[ "com.smartdevicelink.proxy.rpc.enums.DriverDistractionState" ]
import com.smartdevicelink.proxy.rpc.enums.DriverDistractionState;
import com.smartdevicelink.proxy.rpc.enums.*;
[ "com.smartdevicelink.proxy" ]
com.smartdevicelink.proxy;
221,669
public boolean isExpired() { if (expiration != null && expiration.before(new Date())) { return true; } else { return false; } }
boolean function() { if (expiration != null && expiration.before(new Date())) { return true; } else { return false; } }
/** * Will return false if expiration not set ie never expires * * @return true if cache should be expired */
Will return false if expiration not set ie never expires
isExpired
{ "repo_name": "mbrevoort/Confluence-Socialcast-Plugin", "path": "src/main/java/com/avalonconsult/confluence/plugins/socialcast/CachedObjectWrapper.java", "license": "bsd-3-clause", "size": 1879 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
1,437,336
private void processNotificationMessage(ThriftNotificationMessage message) { ActorRef applicationActor = getOrCreateApplicationActor(message.getAppToken()); applicationActor.tell(message, self()); }
void function(ThriftNotificationMessage message) { ActorRef applicationActor = getOrCreateApplicationActor(message.getAppToken()); applicationActor.tell(message, self()); }
/** * Process notification message. * * @param message * the message */
Process notification message
processNotificationMessage
{ "repo_name": "vzhukovskyi/kaa", "path": "server/operations/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/TenantActor.java", "license": "apache-2.0", "size": 12332 }
[ "org.kaaproject.kaa.server.operations.service.akka.messages.core.notification.ThriftNotificationMessage" ]
import org.kaaproject.kaa.server.operations.service.akka.messages.core.notification.ThriftNotificationMessage;
import org.kaaproject.kaa.server.operations.service.akka.messages.core.notification.*;
[ "org.kaaproject.kaa" ]
org.kaaproject.kaa;
535,282
public void setFile(File file) { this.file = file; }
void function(File file) { this.file = file; }
/** * Set the source file. * * @param file the source file. */
Set the source file
setFile
{ "repo_name": "Mayo-WE01051879/mayosapp", "path": "Build/src/main/org/apache/tools/ant/taskdefs/Javadoc.java", "license": "mit", "size": 84218 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
719,793
public void normalize(){ // // ways // long baseWayId = - Long.MAX_VALUE; for (OSMWay way : ways) baseWayId = Math.max(baseWayId, way.getId()); for (OSMWay way : ways) way.setId(baseWayId- way.getId()); // // nodes // long baseNodeId = - Long.MAX_VALUE; for (OSMNode node : nodes.values()) baseNodeId = Math.max(baseNodeId, node.getId()); Map<Long,OSMNode> _nodes = new HashMap<Long,OSMNode> (); for (OSMNode node : nodes.values()) { node.setId(baseNodeId- node.getId()); _nodes.put(node.getId(), node); } nodes.clear(); nodes = _nodes; }
void function(){ long baseWayId = - Long.MAX_VALUE; for (OSMWay way : ways) baseWayId = Math.max(baseWayId, way.getId()); for (OSMWay way : ways) way.setId(baseWayId- way.getId()); long baseNodeId = - Long.MAX_VALUE; for (OSMNode node : nodes.values()) baseNodeId = Math.max(baseNodeId, node.getId()); Map<Long,OSMNode> _nodes = new HashMap<Long,OSMNode> (); for (OSMNode node : nodes.values()) { node.setId(baseNodeId- node.getId()); _nodes.put(node.getId(), node); } nodes.clear(); nodes = _nodes; }
/** * * Find max wayId and set new wayId as a difference between maxWayId and the init wayId. * * Then make the same procedure with nodes. * */
Find max wayId and set new wayId as a difference between maxWayId and the init wayId. Then make the same procedure with nodes
normalize
{ "repo_name": "iusaspb/EmpiricalGeoCoordConverter", "path": "src/main/java/ru/spb/iusa/transport/egcc/osm/OSMData.java", "license": "cc0-1.0", "size": 6217 }
[ "java.util.HashMap", "java.util.Map" ]
import java.util.HashMap; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,482,594
public Graph sequence_two(){ GraphImpl graph = new GraphImpl( "sequence_two", 1 ); Node node1 = createRecordPathNode( 1 ); Node node2 = createRecordPathNode( 2 ); graph.setStartNode( node1 ); graph.addNode( node2 ); graph.addTransition( new TransitionImpl( node1, node2 ) ); return graph; }
Graph function(){ GraphImpl graph = new GraphImpl( STR, 1 ); Node node1 = createRecordPathNode( 1 ); Node node2 = createRecordPathNode( 2 ); graph.setStartNode( node1 ); graph.addNode( node2 ); graph.addTransition( new TransitionImpl( node1, node2 ) ); return graph; }
/** * <pre> * [1]--[2] * </pre> */
<code> [1]--[2] </code>
sequence_two
{ "repo_name": "zutnop/telekom-workflow-engine", "path": "telekom-workflow-engine/src/test/java/ee/telekom/workflow/graph/GraphFactory.java", "license": "mit", "size": 74501 }
[ "ee.telekom.workflow.graph.core.GraphImpl", "ee.telekom.workflow.graph.core.TransitionImpl" ]
import ee.telekom.workflow.graph.core.GraphImpl; import ee.telekom.workflow.graph.core.TransitionImpl;
import ee.telekom.workflow.graph.core.*;
[ "ee.telekom.workflow" ]
ee.telekom.workflow;
2,092,213
@InterfaceAudience.Private public boolean isOpen() { return open; }
@InterfaceAudience.Private boolean function() { return open; }
/** * Is the database open? */
Is the database open
isOpen
{ "repo_name": "Spotme/couchbase-lite-java-core", "path": "src/main/java/com/couchbase/lite/Database.java", "license": "apache-2.0", "size": 87852 }
[ "com.couchbase.lite.internal.InterfaceAudience" ]
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.*;
[ "com.couchbase.lite" ]
com.couchbase.lite;
2,172,213
public void setPermissions(final EnumSet<SharedAccessFilePermissions> permissions) { this.permissions = permissions; }
void function(final EnumSet<SharedAccessFilePermissions> permissions) { this.permissions = permissions; }
/** * Sets the permissions for a shared access signature associated with this shared access policy. * * @param permissions * The permissions, represented by a <code>java.util.EnumSet</code> object that contains * {@link SharedAccessFilePermissions} values, to set for the shared access signature. */
Sets the permissions for a shared access signature associated with this shared access policy
setPermissions
{ "repo_name": "iterate-ch/azure-storage-java", "path": "microsoft-azure-storage/src/com/microsoft/azure/storage/file/SharedAccessFilePolicy.java", "license": "apache-2.0", "size": 4691 }
[ "java.util.EnumSet" ]
import java.util.EnumSet;
import java.util.*;
[ "java.util" ]
java.util;
2,137,239
private void refreshProject(final List<EditorPartPresenter> openedEditors) { eventBus.fireEvent(new RefreshProjectTreeEvent()); for (EditorPartPresenter partPresenter : openedEditors) { final VirtualFile file = partPresenter.getEditorInput().getFile(); eventBus.fireEvent(new FileEvent(file, FileEvent.FileOperation.CLOSE)); } }
void function(final List<EditorPartPresenter> openedEditors) { eventBus.fireEvent(new RefreshProjectTreeEvent()); for (EditorPartPresenter partPresenter : openedEditors) { final VirtualFile file = partPresenter.getEditorInput().getFile(); eventBus.fireEvent(new FileEvent(file, FileEvent.FileOperation.CLOSE)); } }
/** * Refresh project. * * @param openedEditors * editors that corresponds to open files */
Refresh project
refreshProject
{ "repo_name": "sunix/che-plugins", "path": "plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/branch/BranchPresenter.java", "license": "epl-1.0", "size": 12356 }
[ "java.util.List", "org.eclipse.che.ide.api.editor.EditorPartPresenter", "org.eclipse.che.ide.api.event.FileEvent", "org.eclipse.che.ide.api.event.RefreshProjectTreeEvent", "org.eclipse.che.ide.api.project.tree.VirtualFile" ]
import java.util.List; import org.eclipse.che.ide.api.editor.EditorPartPresenter; import org.eclipse.che.ide.api.event.FileEvent; import org.eclipse.che.ide.api.event.RefreshProjectTreeEvent; import org.eclipse.che.ide.api.project.tree.VirtualFile;
import java.util.*; import org.eclipse.che.ide.api.editor.*; import org.eclipse.che.ide.api.event.*; import org.eclipse.che.ide.api.project.tree.*;
[ "java.util", "org.eclipse.che" ]
java.util; org.eclipse.che;
109,627
void decorateRead(InterceptorContext context, Span span);
void decorateRead(InterceptorContext context, Span span);
/** * Decorate spans by outgoing object. * * @param context * @param span */
Decorate spans by outgoing object
decorateRead
{ "repo_name": "opentracing-contrib/java-jaxrs", "path": "opentracing-jaxrs2/src/main/java/io/opentracing/contrib/jaxrs2/serialization/InterceptorSpanDecorator.java", "license": "apache-2.0", "size": 1053 }
[ "io.opentracing.Span", "javax.ws.rs.ext.InterceptorContext" ]
import io.opentracing.Span; import javax.ws.rs.ext.InterceptorContext;
import io.opentracing.*; import javax.ws.rs.ext.*;
[ "io.opentracing", "javax.ws" ]
io.opentracing; javax.ws;
1,096,252
ReadAvailableModulesResponse readAvailableModulesResponse = new ReadAvailableModulesResponse(); ErrorResponse errorResponse = null; ObjectMapper mapper = JsonObjectMapper.getMapper(); String jsonRequest = new String(); String jsonResponse = new String(); try { Map<String, Object> requestData = new LinkedHashMap<String, Object>(); requestData.put("session", sessionId); requestData.put("filter", "all"); String jsonRequestData = mapper.writeValueAsString(requestData); Map<String, Object> request = new LinkedHashMap<String, Object>(); request.put("method", "get_available_modules"); request.put("input_type", "json"); request.put("response_type", "json"); request.put("rest_data", requestData); jsonRequest = mapper.writeValueAsString(request); request.put("rest_data", jsonRequestData); HttpResponse response = Unirest.post(url) .fields(request) .asJson(); if (response == null) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); errorResponse = ErrorResponse.format("An error has occurred!", "No data returned."); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); readAvailableModulesResponse.setError(errorResponse); } else { jsonResponse = response.getBody().toString(); if (StringUtils.isNotBlank(jsonResponse)) { // First check if we have an error errorResponse = ErrorResponse.fromJson(jsonResponse); if (errorResponse == null) { readAvailableModulesResponse = mapper.readValue(jsonResponse, ReadAvailableModulesResponse.class); } } if (readAvailableModulesResponse == null) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); readAvailableModulesResponse.setError(errorResponse); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_OK); if (errorResponse != null) { readAvailableModulesResponse.setStatusCode(errorResponse.getStatusCode()); } } else { readAvailableModulesResponse.setStatusCode(HttpStatus.SC_OK); } } } catch (Exception exception) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); errorResponse = ErrorResponse.format(exception, exception.getMessage()); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); readAvailableModulesResponse.setError(errorResponse); } readAvailableModulesResponse.setJsonRawRequest(jsonRequest); readAvailableModulesResponse.setJsonRawResponse(jsonResponse); return readAvailableModulesResponse; }
ReadAvailableModulesResponse readAvailableModulesResponse = new ReadAvailableModulesResponse(); ErrorResponse errorResponse = null; ObjectMapper mapper = JsonObjectMapper.getMapper(); String jsonRequest = new String(); String jsonResponse = new String(); try { Map<String, Object> requestData = new LinkedHashMap<String, Object>(); requestData.put(STR, sessionId); requestData.put(STR, "all"); String jsonRequestData = mapper.writeValueAsString(requestData); Map<String, Object> request = new LinkedHashMap<String, Object>(); request.put(STR, STR); request.put(STR, "json"); request.put(STR, "json"); request.put(STR, requestData); jsonRequest = mapper.writeValueAsString(request); request.put(STR, jsonRequestData); HttpResponse response = Unirest.post(url) .fields(request) .asJson(); if (response == null) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); errorResponse = ErrorResponse.format(STR, STR); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); readAvailableModulesResponse.setError(errorResponse); } else { jsonResponse = response.getBody().toString(); if (StringUtils.isNotBlank(jsonResponse)) { errorResponse = ErrorResponse.fromJson(jsonResponse); if (errorResponse == null) { readAvailableModulesResponse = mapper.readValue(jsonResponse, ReadAvailableModulesResponse.class); } } if (readAvailableModulesResponse == null) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); readAvailableModulesResponse.setError(errorResponse); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_OK); if (errorResponse != null) { readAvailableModulesResponse.setStatusCode(errorResponse.getStatusCode()); } } else { readAvailableModulesResponse.setStatusCode(HttpStatus.SC_OK); } } } catch (Exception exception) { readAvailableModulesResponse = new ReadAvailableModulesResponse(); errorResponse = ErrorResponse.format(exception, exception.getMessage()); readAvailableModulesResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); readAvailableModulesResponse.setError(errorResponse); } readAvailableModulesResponse.setJsonRawRequest(jsonRequest); readAvailableModulesResponse.setJsonRawResponse(jsonResponse); return readAvailableModulesResponse; }
/** * Gets available module names [SugarCRM REST method - get_available_modules]. * * @param url REST API Url. * @param sessionId Session identifier. * @return ReadAvailableModulesResponse object. * @throws Exception */
Gets available module names [SugarCRM REST method - get_available_modules]
run
{ "repo_name": "Frankst2/SugarOnRest", "path": "sugaronrest/src/main/java/com/sugaronrest/restapicalls/methodcalls/GetAvailableModules.java", "license": "mit", "size": 5210 }
[ "com.fasterxml.jackson.databind.ObjectMapper", "com.mashape.unirest.http.HttpResponse", "com.mashape.unirest.http.Unirest", "com.sugaronrest.ErrorResponse", "com.sugaronrest.restapicalls.responses.ReadAvailableModulesResponse", "com.sugaronrest.utils.JsonObjectMapper", "java.util.LinkedHashMap", "java.util.Map", "org.apache.commons.lang.StringUtils", "org.apache.http.HttpStatus" ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.sugaronrest.ErrorResponse; import com.sugaronrest.restapicalls.responses.ReadAvailableModulesResponse; import com.sugaronrest.utils.JsonObjectMapper; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus;
import com.fasterxml.jackson.databind.*; import com.mashape.unirest.http.*; import com.sugaronrest.*; import com.sugaronrest.restapicalls.responses.*; import com.sugaronrest.utils.*; import java.util.*; import org.apache.commons.lang.*; import org.apache.http.*;
[ "com.fasterxml.jackson", "com.mashape.unirest", "com.sugaronrest", "com.sugaronrest.restapicalls", "com.sugaronrest.utils", "java.util", "org.apache.commons", "org.apache.http" ]
com.fasterxml.jackson; com.mashape.unirest; com.sugaronrest; com.sugaronrest.restapicalls; com.sugaronrest.utils; java.util; org.apache.commons; org.apache.http;
200,402
RedisFuture<String> save();
RedisFuture<String> save();
/** * Synchronously save the dataset to disk. * * @return String simple-string-reply The commands returns OK on success. */
Synchronously save the dataset to disk
save
{ "repo_name": "lettuce-io/lettuce-core", "path": "src/main/java/io/lettuce/core/api/async/RedisServerAsyncCommands.java", "license": "apache-2.0", "size": 12930 }
[ "io.lettuce.core.RedisFuture" ]
import io.lettuce.core.RedisFuture;
import io.lettuce.core.*;
[ "io.lettuce.core" ]
io.lettuce.core;
1,732,133
protected void updateAERSeris(DatasetsAndTrials agentData){ if(!this.metricsSet.contains(PerformanceMetric.AVERAGEEPISODEREWARD)){ return ; } int n = agentData.getLatestTrial().averageEpisodeReward.size(); for(int i = this.lastEpisode; i < n; i++){ agentData.datasets.averageEpisodeRewardSeries.add((double)i, agentData.getLatestTrial().averageEpisodeReward.get(i), false); } if(n > this.lastEpisode){ agentData.datasets.averageEpisodeRewardSeries.fireSeriesChanged(); } }
void function(DatasetsAndTrials agentData){ if(!this.metricsSet.contains(PerformanceMetric.AVERAGEEPISODEREWARD)){ return ; } int n = agentData.getLatestTrial().averageEpisodeReward.size(); for(int i = this.lastEpisode; i < n; i++){ agentData.datasets.averageEpisodeRewardSeries.add((double)i, agentData.getLatestTrial().averageEpisodeReward.get(i), false); } if(n > this.lastEpisode){ agentData.datasets.averageEpisodeRewardSeries.fireSeriesChanged(); } }
/** * Updates the average reward by episode series. Does nothing if that metric is not being plotted. */
Updates the average reward by episode series. Does nothing if that metric is not being plotted
updateAERSeris
{ "repo_name": "gauravpuri/MDP_Repp", "path": "src/burlap/behavior/stochasticgames/auxiliary/performance/MultiAgentPerformancePlotter.java", "license": "lgpl-3.0", "size": 41844 }
[ "burlap.behavior.singleagent.auxiliary.performance.PerformanceMetric" ]
import burlap.behavior.singleagent.auxiliary.performance.PerformanceMetric;
import burlap.behavior.singleagent.auxiliary.performance.*;
[ "burlap.behavior.singleagent" ]
burlap.behavior.singleagent;
2,007,145
public void setModel(Model model) { this.model = model; }
void function(Model model) { this.model = model; }
/** * Sets the model * * @param model the model used to check the number of children of a node */
Sets the model
setModel
{ "repo_name": "zaproxy/zaproxy", "path": "zap/src/main/java/org/zaproxy/zap/spider/filters/MaxChildrenFetchFilter.java", "license": "apache-2.0", "size": 1838 }
[ "org.parosproxy.paros.model.Model" ]
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.*;
[ "org.parosproxy.paros" ]
org.parosproxy.paros;
2,565,237
public static <V extends VertexProgram> V createVertexProgram(final Graph graph, final Configuration configuration) { try { final Class<V> vertexProgramClass = (Class) Class.forName(configuration.getString(VERTEX_PROGRAM)); final Constructor<V> constructor = vertexProgramClass.getDeclaredConstructor(); constructor.setAccessible(true); final V vertexProgram = constructor.newInstance(); vertexProgram.loadState(graph, configuration); return vertexProgram; } catch (final Exception e) { throw new IllegalStateException(e.getMessage(), e); } } public interface Builder {
static <V extends VertexProgram> V function(final Graph graph, final Configuration configuration) { try { final Class<V> vertexProgramClass = (Class) Class.forName(configuration.getString(VERTEX_PROGRAM)); final Constructor<V> constructor = vertexProgramClass.getDeclaredConstructor(); constructor.setAccessible(true); final V vertexProgram = constructor.newInstance(); vertexProgram.loadState(graph, configuration); return vertexProgram; } catch (final Exception e) { throw new IllegalStateException(e.getMessage(), e); } } public interface Builder {
/** * A helper method to construct a {@link VertexProgram} given the content of the supplied configuration. * The class of the VertexProgram is read from the {@link VertexProgram#VERTEX_PROGRAM} static configuration key. * Once the VertexProgram is constructed, {@link VertexProgram#loadState} method is called with the provided graph and configuration. * * @param graph The graph that the vertex program will execute against * @param configuration A configuration with requisite information to build a vertex program * @param <V> The vertex program type * @return the newly constructed vertex program */
A helper method to construct a <code>VertexProgram</code> given the content of the supplied configuration. The class of the VertexProgram is read from the <code>VertexProgram#VERTEX_PROGRAM</code> static configuration key. Once the VertexProgram is constructed, <code>VertexProgram#loadState</code> method is called with the provided graph and configuration
createVertexProgram
{ "repo_name": "samiunn/incubator-tinkerpop", "path": "gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/VertexProgram.java", "license": "apache-2.0", "size": 13228 }
[ "java.lang.reflect.Constructor", "org.apache.commons.configuration.Configuration", "org.apache.tinkerpop.gremlin.structure.Graph" ]
import java.lang.reflect.Constructor; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.structure.Graph;
import java.lang.reflect.*; import org.apache.commons.configuration.*; import org.apache.tinkerpop.gremlin.structure.*;
[ "java.lang", "org.apache.commons", "org.apache.tinkerpop" ]
java.lang; org.apache.commons; org.apache.tinkerpop;
1,756,638
public Collection<BasicBlock> getBlocks(BitSet labelSet) { LinkedList<BasicBlock> result = new LinkedList<BasicBlock>(); for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) { BasicBlock block = i.next(); if (labelSet.get(block.getLabel())) result.add(block); } return result; }
Collection<BasicBlock> function(BitSet labelSet) { LinkedList<BasicBlock> result = new LinkedList<BasicBlock>(); for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) { BasicBlock block = i.next(); if (labelSet.get(block.getLabel())) result.add(block); } return result; }
/** * Get Collection of basic blocks whose IDs are specified by * given BitSet. * * @param labelSet BitSet of block labels * @return a Collection containing the blocks whose IDs are given */
Get Collection of basic blocks whose IDs are specified by given BitSet
getBlocks
{ "repo_name": "optivo-org/fingbugs-1.3.9-optivo", "path": "src/java/edu/umd/cs/findbugs/ba/CFG.java", "license": "lgpl-2.1", "size": 15813 }
[ "java.util.BitSet", "java.util.Collection", "java.util.Iterator", "java.util.LinkedList" ]
import java.util.BitSet; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList;
import java.util.*;
[ "java.util" ]
java.util;
1,414,512
protected void drawToPostscriptAsSquare(EPSOutputPrintStream pw, PositionTransformation pt, double size, Color c) { pt.translateToGUIPosition(getPosition()); pw.setColor(c.getRed(), c.getGreen(), c.getBlue()); pw.drawFilledRectangle(pt.guiXDouble - (size / 2.0), pt.guiYDouble - (size / 2.0), size, size); }
void function(EPSOutputPrintStream pw, PositionTransformation pt, double size, Color c) { pt.translateToGUIPosition(getPosition()); pw.setColor(c.getRed(), c.getGreen(), c.getBlue()); pw.drawFilledRectangle(pt.guiXDouble - (size / 2.0), pt.guiYDouble - (size / 2.0), size, size); }
/** * Draw this node in PS as a square. * * @param pw * The PS stream to write the commands for this line to * @param pt * Transformation object to obtain GUI coordinates of the * endpoints of this edge. * @param size * The side-length of the square, e.g. drawingSizeInPixels * @param c * The color to draw this square with */
Draw this node in PS as a square
drawToPostscriptAsSquare
{ "repo_name": "gabrsar/Leach---Sinalgo", "path": "src/sinalgo/nodes/Node.java", "license": "bsd-3-clause", "size": 61591 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
711,955
public Properties getProperties() { return props; }
Properties function() { return props; }
/** * Returns the Properties object associated with this Session * * @return Properties object */
Returns the Properties object associated with this Session
getProperties
{ "repo_name": "arthurzaczek/kolab-android", "path": "javamail/javax/mail/Session.java", "license": "gpl-3.0", "size": 44684 }
[ "java.util.Properties" ]
import java.util.Properties;
import java.util.*;
[ "java.util" ]
java.util;
653,371
public static PendingIntent readPendingIntentOrNullFromParcel(Parcel in) { IBinder b = in.readStrongBinder(); return b != null ? new PendingIntent(b) : null; } PendingIntent(IIntentSender target) { mTarget = target; } PendingIntent(IBinder target) { mTarget = IIntentSender.Stub.asInterface(target); }
static PendingIntent function(Parcel in) { IBinder b = in.readStrongBinder(); return b != null ? new PendingIntent(b) : null; } PendingIntent(IIntentSender target) { mTarget = target; } PendingIntent(IBinder target) { mTarget = IIntentSender.Stub.asInterface(target); }
/** * Convenience function for reading either a Messenger or null pointer from * a Parcel. You must have previously written the Messenger with * {@link #writePendingIntentOrNullToParcel}. * * @param in The Parcel containing the written Messenger. * * @return Returns the Messenger read from the Parcel, or null if null had * been written. */
Convenience function for reading either a Messenger or null pointer from a Parcel. You must have previously written the Messenger with <code>#writePendingIntentOrNullToParcel</code>
readPendingIntentOrNullFromParcel
{ "repo_name": "JSDemos/android-sdk-20", "path": "src/android/app/PendingIntent.java", "license": "apache-2.0", "size": 43269 }
[ "android.content.IIntentSender", "android.os.IBinder", "android.os.Parcel" ]
import android.content.IIntentSender; import android.os.IBinder; import android.os.Parcel;
import android.content.*; import android.os.*;
[ "android.content", "android.os" ]
android.content; android.os;
1,716,664
public static void verifyAllLogsGotReferenced(FileSystem fs, Path logsDir, Set<String> serverNames, SnapshotDescription snapshot, Path snapshotLogDir) throws IOException { assertTrue(snapshot, "Logs directory doesn't exist in snapshot", fs.exists(logsDir)); // for each of the server log dirs, make sure it matches the main directory Multimap<String, String> snapshotLogs = getMapOfServersAndLogs(fs, snapshotLogDir, serverNames); Multimap<String, String> realLogs = getMapOfServersAndLogs(fs, logsDir, serverNames); if (realLogs != null) { assertNotNull(snapshot, "No server logs added to snapshot", snapshotLogs); } else { assertNull(snapshot, "Snapshotted server logs that don't exist", snapshotLogs); } // check the number of servers Set<Entry<String, Collection<String>>> serverEntries = realLogs.asMap().entrySet(); Set<Entry<String, Collection<String>>> snapshotEntries = snapshotLogs.asMap().entrySet(); assertEquals(snapshot, "Not the same number of snapshot and original server logs directories", serverEntries.size(), snapshotEntries.size()); // verify we snapshotted each of the log files for (Entry<String, Collection<String>> serverLogs : serverEntries) { // if the server is not the snapshot, skip checking its logs if (!serverNames.contains(serverLogs.getKey())) continue; Collection<String> snapshotServerLogs = snapshotLogs.get(serverLogs.getKey()); assertNotNull(snapshot, "Snapshots missing logs for server:" + serverLogs.getKey(), snapshotServerLogs); // check each of the log files assertEquals(snapshot, "Didn't reference all the log files for server:" + serverLogs.getKey(), serverLogs .getValue().size(), snapshotServerLogs.size()); for (String log : serverLogs.getValue()) { assertTrue(snapshot, "Snapshot logs didn't include " + log, snapshotServerLogs.contains(log)); } } }
static void function(FileSystem fs, Path logsDir, Set<String> serverNames, SnapshotDescription snapshot, Path snapshotLogDir) throws IOException { assertTrue(snapshot, STR, fs.exists(logsDir)); Multimap<String, String> snapshotLogs = getMapOfServersAndLogs(fs, snapshotLogDir, serverNames); Multimap<String, String> realLogs = getMapOfServersAndLogs(fs, logsDir, serverNames); if (realLogs != null) { assertNotNull(snapshot, STR, snapshotLogs); } else { assertNull(snapshot, STR, snapshotLogs); } Set<Entry<String, Collection<String>>> serverEntries = realLogs.asMap().entrySet(); Set<Entry<String, Collection<String>>> snapshotEntries = snapshotLogs.asMap().entrySet(); assertEquals(snapshot, STR, serverEntries.size(), snapshotEntries.size()); for (Entry<String, Collection<String>> serverLogs : serverEntries) { if (!serverNames.contains(serverLogs.getKey())) continue; Collection<String> snapshotServerLogs = snapshotLogs.get(serverLogs.getKey()); assertNotNull(snapshot, STR + serverLogs.getKey(), snapshotServerLogs); assertEquals(snapshot, STR + serverLogs.getKey(), serverLogs .getValue().size(), snapshotServerLogs.size()); for (String log : serverLogs.getValue()) { assertTrue(snapshot, STR + log, snapshotServerLogs.contains(log)); } } }
/** * Verify that all the expected logs got referenced * @param fs filesystem where the logs live * @param logsDir original logs directory * @param serverNames names of the servers that involved in the snapshot * @param snapshot description of the snapshot being taken * @param snapshotLogDir directory for logs in the snapshot * @throws IOException */
Verify that all the expected logs got referenced
verifyAllLogsGotReferenced
{ "repo_name": "throughsky/lywebank", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/snapshot/TakeSnapshotUtils.java", "license": "apache-2.0", "size": 13006 }
[ "com.google.common.collect.Multimap", "java.io.IOException", "java.util.Collection", "java.util.Map", "java.util.Set", "org.apache.hadoop.fs.FileSystem", "org.apache.hadoop.fs.Path", "org.apache.hadoop.hbase.protobuf.generated.HBaseProtos" ]
import com.google.common.collect.Multimap; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
import com.google.common.collect.*; import java.io.*; import java.util.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hbase.protobuf.generated.*;
[ "com.google.common", "java.io", "java.util", "org.apache.hadoop" ]
com.google.common; java.io; java.util; org.apache.hadoop;
1,802,280
@Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { switch (type) { case ENTITY: return true; case EQUIPPED: return true; case EQUIPPED_FIRST_PERSON: return true; case INVENTORY: return true; default: return false; } }
boolean function(ItemStack item, ItemRenderType type) { switch (type) { case ENTITY: return true; case EQUIPPED: return true; case EQUIPPED_FIRST_PERSON: return true; case INVENTORY: return true; default: return false; } }
/** * IItemRenderer implementation * */
IItemRenderer implementation
handleRenderType
{ "repo_name": "4Space/4Space-5", "path": "src/main/java/micdoodle8/mods/galacticraft/planets/asteroids/client/render/item/ItemRendererAstroMiner.java", "license": "gpl-3.0", "size": 5575 }
[ "net.minecraft.item.ItemStack" ]
import net.minecraft.item.ItemStack;
import net.minecraft.item.*;
[ "net.minecraft.item" ]
net.minecraft.item;
988,121
private void bindSession() { SessionFactory sessionFactory = (SessionFactory) getBean( "sessionFactory" ); Session session = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) ); }
void function() { SessionFactory sessionFactory = (SessionFactory) getBean( STR ); Session session = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) ); }
/** * Binds a Hibernate Session to the current thread. */
Binds a Hibernate Session to the current thread
bindSession
{ "repo_name": "vietnguyen/dhis2-core", "path": "dhis-2/dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/DhisTest.java", "license": "bsd-3-clause", "size": 5764 }
[ "org.hibernate.Session", "org.hibernate.SessionFactory", "org.springframework.orm.hibernate5.SessionHolder", "org.springframework.transaction.support.TransactionSynchronizationManager" ]
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate5.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.hibernate.*; import org.springframework.orm.hibernate5.*; import org.springframework.transaction.support.*;
[ "org.hibernate", "org.springframework.orm", "org.springframework.transaction" ]
org.hibernate; org.springframework.orm; org.springframework.transaction;
941,345
public List<Tool> getTools() { return tools; }
List<Tool> function() { return tools; }
/** * Gets the tools. * * @return the tools */
Gets the tools
getTools
{ "repo_name": "hibernate/hibernate-demos", "path": "hibernate-orm/core/Basic/src/main/java/org/hibernate/brmeyer/demo/entity/User.java", "license": "apache-2.0", "size": 7776 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,504,037
public double getUseLikelihood(Map<KeywordDefinition, Integer> insertedKeywords, Map<KeywordDefinition, Integer> removedKeywords, Map<KeywordDefinition, Integer> updatedKeywords, Map<KeywordDefinition, Integer> unchangedKeywords) { // Merge all maps Map<KeywordDefinition, Integer> mergedMap = new HashMap<KeywordDefinition, Integer>(); if (insertedKeywords != null) mergedMap.putAll(insertedKeywords); if (removedKeywords != null) mergedMap.putAll(removedKeywords); if (updatedKeywords != null) mergedMap.putAll(updatedKeywords); if (unchangedKeywords != null) mergedMap.putAll(unchangedKeywords); // Look if any of the keywords given as input is present on this API // not implemented yet return 1; }
double function(Map<KeywordDefinition, Integer> insertedKeywords, Map<KeywordDefinition, Integer> removedKeywords, Map<KeywordDefinition, Integer> updatedKeywords, Map<KeywordDefinition, Integer> unchangedKeywords) { Map<KeywordDefinition, Integer> mergedMap = new HashMap<KeywordDefinition, Integer>(); if (insertedKeywords != null) mergedMap.putAll(insertedKeywords); if (removedKeywords != null) mergedMap.putAll(removedKeywords); if (updatedKeywords != null) mergedMap.putAll(updatedKeywords); if (unchangedKeywords != null) mergedMap.putAll(unchangedKeywords); return 1; }
/** * Computes the likelihood that the function being repaired uses the API. * @param keywords A map of the keywords that were found in the function. * The key for the map is the keyword and the value for the * map is the number of occurrences of the keyword. * @return A likelihood between 0 and 1. */
Computes the likelihood that the function being repaired uses the API
getUseLikelihood
{ "repo_name": "saltlab/Pangor", "path": "js-learning/src/ca/ubc/ece/salt/pangor/learning/apis/AbstractAPI.java", "license": "apache-2.0", "size": 6775 }
[ "java.util.HashMap", "java.util.Map" ]
import java.util.HashMap; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
721,323
public static void removePreviousSiblingText(Element element) { while (true) { Node sibling = element.getPreviousSibling(); if (sibling instanceof Text) { detach(sibling); } else { break; } } }
static void function(Element element) { while (true) { Node sibling = element.getPreviousSibling(); if (sibling instanceof Text) { detach(sibling); } else { break; } } }
/** * Removes any previous siblings text nodes */
Removes any previous siblings text nodes
removePreviousSiblingText
{ "repo_name": "janstey/fuse", "path": "common-util/src/main/java/org/fusesource/common/util/DomHelper.java", "license": "apache-2.0", "size": 3664 }
[ "org.w3c.dom.Element", "org.w3c.dom.Node", "org.w3c.dom.Text" ]
import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text;
import org.w3c.dom.*;
[ "org.w3c.dom" ]
org.w3c.dom;
1,941,405
public static String toString(final Reader reader) throws IOException { CharArrayWriter charArrayWriter = new CharArrayWriter(); copy(reader, charArrayWriter); return charArrayWriter.toString(); }
static String function(final Reader reader) throws IOException { CharArrayWriter charArrayWriter = new CharArrayWriter(); copy(reader, charArrayWriter); return charArrayWriter.toString(); }
/** * Convert Reader to String. * * @param reader reader * @return result of the String type * @throws IOException IOException */
Convert Reader to String
toString
{ "repo_name": "dangdangdotcom/elastic-job", "path": "elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/util/IOUtils.java", "license": "apache-2.0", "size": 2397 }
[ "java.io.CharArrayWriter", "java.io.IOException", "java.io.Reader" ]
import java.io.CharArrayWriter; import java.io.IOException; import java.io.Reader;
import java.io.*;
[ "java.io" ]
java.io;
2,250,999
IView getView();
IView getView();
/** * Return the IView object associated with this presenter * @return */
Return the IView object associated with this presenter
getView
{ "repo_name": "ufoscout/jpattern", "path": "gwt/src/main/java/com/jpattern/gwt/client/presenter/IPresenter.java", "license": "apache-2.0", "size": 6645 }
[ "com.jpattern.gwt.client.view.IView" ]
import com.jpattern.gwt.client.view.IView;
import com.jpattern.gwt.client.view.*;
[ "com.jpattern.gwt" ]
com.jpattern.gwt;
1,718,276
protected void performUpdate(final WidgetHelperService service) { final RemoteViews views = new RemoteViews(service.getPackageName(), R.layout.widget_simple); performUpdate(views, service); }
void function(final WidgetHelperService service) { final RemoteViews views = new RemoteViews(service.getPackageName(), R.layout.widget_simple); performUpdate(views, service); }
/** * Update all active widget instances by pushing changes */
Update all active widget instances by pushing changes
performUpdate
{ "repo_name": "jcnoir/dmix", "path": "MPDroid/src/main/java/com/namelessdev/mpdroid/widgets/SimpleWidgetProvider.java", "license": "apache-2.0", "size": 5644 }
[ "android.widget.RemoteViews" ]
import android.widget.RemoteViews;
import android.widget.*;
[ "android.widget" ]
android.widget;
1,275,104
public void parse(String[] argv) throws Exception { CommandLine cl = parser.parse(options, argv); if ( cl.hasOption("h") ) { printUsage(true); } if (cl.hasOption("f")) { String files[] = cl.getOptionValues("f"); for (int i=0; i<files.length; i++) { infiles.add(new File(files[i])); } } // Interpret extra arguments as input files. if (cl.getArgList() != null) { for (Object o : cl.getArgList()) { String s = (String)o; infiles.add(new File(s)); } } if ( infiles.size() == 0 ) { printUsage(true); } if (cl.hasOption("M")) { major = Integer.parseInt(cl.getOptionValue("M")); } if (cl.hasOption("m")) { minor = Integer.parseInt(cl.getOptionValue("m")); } if (cl.hasOption("n")) { ntoread = Integer.parseInt(cl.getOptionValue("n")); } }
void function(String[] argv) throws Exception { CommandLine cl = parser.parse(options, argv); if ( cl.hasOption("h") ) { printUsage(true); } if (cl.hasOption("f")) { String files[] = cl.getOptionValues("f"); for (int i=0; i<files.length; i++) { infiles.add(new File(files[i])); } } if (cl.getArgList() != null) { for (Object o : cl.getArgList()) { String s = (String)o; infiles.add(new File(s)); } } if ( infiles.size() == 0 ) { printUsage(true); } if (cl.hasOption("M")) { major = Integer.parseInt(cl.getOptionValue("M")); } if (cl.hasOption("m")) { minor = Integer.parseInt(cl.getOptionValue("m")); } if (cl.hasOption("n")) { ntoread = Integer.parseInt(cl.getOptionValue("n")); } }
/** * Parse the commandline options for the validate command. */
Parse the commandline options for the validate command
parse
{ "repo_name": "iLCSoft/LCIO", "path": "src/java/hep/lcio/util/ValidateCommandHandler.java", "license": "bsd-3-clause", "size": 2633 }
[ "java.io.File", "org.apache.commons.cli.CommandLine" ]
import java.io.File; import org.apache.commons.cli.CommandLine;
import java.io.*; import org.apache.commons.cli.*;
[ "java.io", "org.apache.commons" ]
java.io; org.apache.commons;
1,049,818
public List<User> getAcceptions(){ if(acceptions == null){ acceptions = new ArrayList<User>(); } return acceptions; }
List<User> function(){ if(acceptions == null){ acceptions = new ArrayList<User>(); } return acceptions; }
/** * Get acceptions list. * Return a list of driver accepted the request * * @return the list */
Get acceptions list. Return a list of driver accepted the request
getAcceptions
{ "repo_name": "CMPUT301F16T06/RideNGo", "path": "RideNGo/app/src/main/java/assignment1/ridengo/RideRequest.java", "license": "gpl-3.0", "size": 7544 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,534,016
private void buildTextDoc( File dir, String docID ) throws AeseException { try { writeSplitCortexToDir( dir, docID ); writeSplitCorcodeToDir( dir, docID ); } catch ( Exception e ) { throw new AeseException( e ); } }
void function( File dir, String docID ) throws AeseException { try { writeSplitCortexToDir( dir, docID ); writeSplitCorcodeToDir( dir, docID ); } catch ( Exception e ) { throw new AeseException( e ); } }
/** * Split an MVD into its components versions * @param dir the directory to store everythign in * @param docID the docID of the cortex and corcodes */
Split an MVD into its components versions
buildTextDoc
{ "repo_name": "AustESE-Infrastructure/calliope", "path": "src/calliope/export/PDEFArchive.java", "license": "gpl-2.0", "size": 25952 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
50,214
private void parseArguments(String[] args) throws PrismException { int i, j; String sw, s; PrismLog log; constSwitch = ""; paramSwitch = ""; for (i = 0; i < args.length; i++) { // if is a switch... if (args[i].length() > 0 && args[i].charAt(0) == '-') { // Remove "-" sw = args[i].substring(1); if (sw.length() == 0) { errorAndExit("Invalid empty switch"); } // Remove optional second "-" (i.e. we allow switches of the form --sw too) if (sw.charAt(0) == '-') sw = sw.substring(1); // Note: the order of these switches should match the -help output (just to help keep track of things). // But: processing of "PRISM" options is done elsewhere in PrismSettings // Any "hidden" options, i.e. not in -help text/manual, are indicated as such. // print help if (sw.equals("help") || sw.equals("?")) { // see if userg requested help for a specific switch, e.g. -help simpath // note: this is one of the few places where a second argument is optional, // which is possible here because -help should usually be the only switch provided if (i < args.length - 1) { printHelpSwitch(args[++i]); } else { printHelp(); } exit(); } // java max mem else if (sw.equals("javamaxmem")) { i++; // ignore - this is dealt with before java is launched } // timeout else if (sw.equals("timeout")) { if (i < args.length - 1) { int timeout = PrismUtils.convertTimeStringtoSeconds(args[++i]); if (timeout < 0) { errorAndExit("Negative timeout value \"" + timeout + "\" for -" + sw + " switch"); } if (timeout > 0) { setTimeout(timeout); } // timeout == 0 -> no timeout } else { errorAndExit("Missing timeout value for -" + sw + " switch"); } } // print version else if (sw.equals("version")) { printVersion(); exit(); } // load settings else if (sw.equals("settings")) { if (i < args.length - 1) { settingsFilename = args[++i].trim(); } else { errorAndExit("Incomplete -" + sw + " switch"); } } // print a list of all keywords (hidden option) else if (sw.equals("keywords")) { printListOfKeywords(); exit(); } // property/properties given in command line else if (sw.equals("pf") || sw.equals("pctl") || sw.equals("csl")) { if (i < args.length - 1) { propertyString = args[++i]; } else { errorAndExit("No property specified for -" + sw + " switch"); } } // which property to check (int index or string name) else if (sw.equals("prop") || sw.equals("property")) { if (i < args.length - 1) { try { propertyToCheck = Integer.parseInt(args[++i]); } catch (NumberFormatException e) { propertyToCheck = args[i]; } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // definition of undefined constants else if (sw.equals("const")) { if (i < args.length - 1) { // store argument for later use (append if already partially specified) if ("".equals(constSwitch)) constSwitch = args[++i].trim(); else constSwitch += "," + args[++i].trim(); } else { errorAndExit("Incomplete -" + sw + " switch"); } } // defining a parameter else if (sw.equals("param")) { param = true; if (i < args.length - 1) { // store argument for later use (append if already partially specified) if ("".equals(paramSwitch)) { paramSwitch = args[++i].trim(); } else { paramSwitch += "," + args[++i].trim(); } } else { errorAndExit("Incomplete -" + sw + " switch"); } } // do steady-state probability computation else if (sw.equals("steadystate") || sw.equals("ss")) { steadystate = true; } // do transient probability computation else if (sw.equals("transient") || sw.equals("tr")) { if (i < args.length - 1) { dotransient = true; transientTime = args[++i]; } else { errorAndExit("No value specified for -" + sw + " switch"); } } // generate random path with simulator else if (sw.equals("simpath")) { if (i < args.length - 2) { simpath = true; simpathDetails = args[++i]; simpathFilename = args[++i]; } else { errorAndExit("The -" + sw + " switch requires two arguments (path details, filename)"); } } // disable model construction else if (sw.equals("nobuild")) { nobuild = true; } // enable "testing" mode else if (sw.equals("test")) { test = true; } // enable "test all" mode (don't stop on errors) // (overrides -test switch) else if (sw.equals("testall")) { test = true; testExitsOnFail = false; } else if (sw.equals("dddebug")) { jdd.DebugJDD.enable(); } else if (sw.equals("ddtrace")) { if (i < args.length - 1) { String idString = args[++i]; try { int id = Integer.parseInt(idString); jdd.DebugJDD.enableTracingForID(id); } catch (NumberFormatException e) { errorAndExit("The -" + sw + " switch requires an integer argument (JDDNode ID)"); } } else { errorAndExit("The -" + sw + " switch requires an additional argument (JDDNode ID)"); } } // IMPORT OPTIONS: // change model type to pepa else if (sw.equals("importpepa")) { importpepa = true; } // Import model from PRISM preprocessor (hidden option) else if (sw.equals("importprismpp")) { if (i < args.length - 1) { importprismpp = true; prismppParams = args[++i]; } else { errorAndExit("No parameters specified for -" + sw + " switch"); } } // import model from explicit file(s) else if (sw.equals("importmodel")) { if (i < args.length - 1) { processImportModelSwitch(args[++i]); } else { errorAndExit("No file/options specified for -" + sw + " switch"); } } // import transition matrix from explicit format else if (sw.equals("importtrans")) { importtrans = true; } // import states for explicit model import else if (sw.equals("importstates")) { if (i < args.length - 1) { importstates = true; importStatesFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // import labels for explicit model import else if (sw.equals("importlabels")) { if (i < args.length - 1) { importlabels = true; importLabelsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // import initial distribution e.g. for transient probability distribution else if (sw.equals("importinitdist")) { if (i < args.length - 1) { importinitdist = true; importInitDistFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // override model type to dtmc else if (sw.equals("dtmc")) { typeOverride = ModelType.DTMC; } // override model type to mdp else if (sw.equals("mdp")) { typeOverride = ModelType.MDP; } // override model type to ctmc else if (sw.equals("ctmc")) { typeOverride = ModelType.CTMC; } // EXPORT OPTIONS: // export results else if (sw.equals("exportresults")) { if (i < args.length - 1) { exportresults = true; // Parse filename/options s = args[++i]; // Assume use of : to split filename/options but check for , if : not found // (this was the old notation) String halves[] = splitFilesAndOptions(s); if (halves[1].length() == 0 && halves[0].indexOf(',') > -1) { int comma = halves[0].indexOf(','); halves[1] = halves[0].substring(comma + 1); halves[0] = halves[0].substring(0, comma); } exportResultsFilename = halves[0]; String ss[] = halves[1].split(","); exportResultsFormat = "plain"; for (j = 0; j < ss.length; j++) { if (ss[j].equals("")) { } else if (ss[j].equals("csv")) exportResultsFormat = "csv"; else if (ss[j].equals("matrix")) exportresultsmatrix = true; else if (ss[j].equals("comment")) exportResultsFormat = "comment"; else errorAndExit("Unknown option \"" + ss[j] + "\" for -" + sw + " switch"); } } else { errorAndExit("No file/options specified for -" + sw + " switch"); } } // export model to explicit file(s) else if (sw.equals("exportmodel")) { if (i < args.length - 1) { processExportModelSwitch(args[++i]); } else { errorAndExit("No file/options specified for -" + sw + " switch"); } } // export transition matrix to file else if (sw.equals("exporttrans")) { if (i < args.length - 1) { exporttrans = true; exportTransFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export state rewards to file else if (sw.equals("exportstaterewards")) { if (i < args.length - 1) { exportstaterewards = true; exportStateRewardsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export transition rewards to file else if (sw.equals("exporttransrewards")) { if (i < args.length - 1) { exporttransrewards = true; exportTransRewardsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export both state/transition rewards to file else if (sw.equals("exportrewards")) { if (i < args.length - 2) { exportstaterewards = true; exporttransrewards = true; exportStateRewardsFilename = args[++i]; exportTransRewardsFilename = args[++i]; } else { errorAndExit("Two files must be specified for -" + sw + " switch"); } } // export states else if (sw.equals("exportstates")) { if (i < args.length - 1) { exportstates = true; exportStatesFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export labels/states else if (sw.equals("exportlabels")) { if (i < args.length - 1) { exportlabels = true; exportLabelsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // switch export mode to "matlab" else if (sw.equals("exportmatlab")) { exportType = Prism.EXPORT_MATLAB; } // switch export mode to "mrmc" else if (sw.equals("exportmrmc")) { exportType = Prism.EXPORT_MRMC; } // switch export mode to "rows" else if (sw.equals("exportrows")) { exportType = Prism.EXPORT_ROWS; } // exported matrix entries are ordered else if (sw.equals("exportordered") || sw.equals("ordered")) { exportordered = true; } // exported matrix entries are unordered else if (sw.equals("exportunordered") || sw.equals("unordered")) { exportordered = false; } // export transition matrix graph to dot file else if (sw.equals("exporttransdot")) { if (i < args.length - 1) { exporttransdot = true; exportTransDotFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export transition matrix graph to dot file (with states) else if (sw.equals("exporttransdotstates")) { if (i < args.length - 1) { exporttransdotstates = true; exportTransDotStatesFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export transition matrix graph to dot file and view it else if (sw.equals("exportmodeldotview")) { exportmodeldotview = true; } // export transition matrix MTBDD to dot file else if (sw.equals("exportdot")) { if (i < args.length - 1) { exportdot = true; exportDotFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export sccs to file else if (sw.equals("exportsccs")) { if (i < args.length - 1) { exportsccs = true; exportSCCsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export bsccs to file else if (sw.equals("exportbsccs")) { if (i < args.length - 1) { exportbsccs = true; exportBSCCsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export mecs to file else if (sw.equals("exportmecs")) { if (i < args.length - 1) { exportmecs = true; exportMECsFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export steady-state probs (as opposed to displaying on screen) else if (sw.equals("exportsteadystate") || sw.equals("exportss")) { if (i < args.length - 1) { exportSteadyStateFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export transient probs (as opposed to displaying on screen) else if (sw.equals("exporttransient") || sw.equals("exporttr")) { if (i < args.length - 1) { exportTransientFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export strategy else if (sw.equals("exportstrat")) { if (i < args.length - 1) { processExportStratSwitch(args[++i]); } else { errorAndExit("No file/options specified for -" + sw + " switch"); } } // export prism model to file else if (sw.equals("exportprism")) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals("stdout")) ? null : new File(filename); prism.setExportPrism(true); prism.setExportPrismFile(f); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export prism model to file (with consts expanded) else if (sw.equals("exportprismconst")) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals("stdout")) ? null : new File(filename); prism.setExportPrismConst(true); prism.setExportPrismConstFile(f); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export digital clocks translation prism model to file else if (sw.equals("exportdigital")) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals("stdout")) ? null : new File(filename); prism.setExportDigital(true); prism.setExportDigitalFile(f); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export reachability target info to file (hidden option) else if (sw.equals("exporttarget")) { if (i < args.length - 1) { prism.setExportTarget(true); prism.setExportTargetFilename(args[++i]); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export product transition matrix to file (hidden option) else if (sw.equals("exportprodtrans")) { if (i < args.length - 1) { prism.setExportProductTrans(true); prism.setExportProductTransFilename(args[++i]); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export product states to file (hidden option) else if (sw.equals("exportprodstates")) { if (i < args.length - 1) { prism.setExportProductStates(true); prism.setExportProductStatesFilename(args[++i]); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export product vector to file (hidden option) else if (sw.equals("exportprodvector")) { if (i < args.length - 1) { prism.setExportProductVector(true); prism.setExportProductVectorFilename(args[++i]); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export model to plain text file (deprecated option so hidden) else if (sw.equals("exportplain")) { if (i < args.length - 1) { exporttrans = true; exportType = Prism.EXPORT_PLAIN; exportTransFilename = args[++i]; exportPlainDeprecated = true; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // export to spy file (hidden option) else if (sw.equals("exportspy")) { if (i < args.length - 1) { exportspy = true; exportSpyFilename = args[++i]; } else { errorAndExit("No file specified for -" + sw + " switch"); } } // NB: Following the ordering of the -help text, more options go here, // but these are processed in the PrismSettings class; see below // SIMULATION OPTIONS: // use simulator for approximate/statistical model checking else if (sw.equals("sim")) { simulate = true; } // simulation-based model checking methods else if (sw.equals("simmethod")) { if (i < args.length - 1) { s = args[++i]; if (s.equals("ci") || s.equals("aci") || s.equals("apmc") || s.equals("sprt")) simMethodName = s; else errorAndExit("Unrecognised option for -" + sw + " switch (options are: ci, aci, apmc, sprt)"); } else { errorAndExit("No parameter specified for -" + sw + " switch"); } } // simulation number of samples else if (sw.equals("simsamples")) { if (i < args.length - 1) { try { simNumSamples = Integer.parseInt(args[++i]); if (simNumSamples <= 0) throw new NumberFormatException(""); simNumSamplesGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // simulation confidence parameter else if (sw.equals("simconf")) { if (i < args.length - 1) { try { simConfidence = Double.parseDouble(args[++i]); if (simConfidence <= 0 || simConfidence >= 1) throw new NumberFormatException(""); simConfidenceGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // simulation confidence interval width else if (sw.equals("simwidth")) { if (i < args.length - 1) { try { simWidth = Double.parseDouble(args[++i]); if (simWidth <= 0) throw new NumberFormatException(""); simWidthGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // simulation approximation parameter else if (sw.equals("simapprox")) { if (i < args.length - 1) { try { simApprox = Double.parseDouble(args[++i]); if (simApprox <= 0) throw new NumberFormatException(""); simApproxGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // use the number of iterations given instead of automatically deciding whether the variance is null ot not else if (sw.equals("simmanual")) { simManual = true; } // simulation number of samples to conclude S^2=0 or not else if (sw.equals("simvar")) { if (i < args.length - 1) { try { reqIterToConclude = Integer.parseInt(args[++i]); if (reqIterToConclude <= 0) throw new NumberFormatException(""); reqIterToConcludeGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // maximum value of reward else if (sw.equals("simmaxrwd")) { if (i < args.length - 1) { try { simMaxReward = Double.parseDouble(args[++i]); if (simMaxReward <= 0.0) throw new NumberFormatException(""); simMaxRewardGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // simulation max path length else if (sw.equals("simpathlen")) { if (i < args.length - 1) { try { simMaxPath = Long.parseLong(args[++i]); if (simMaxPath <= 0) throw new NumberFormatException(""); simMaxPathGiven = true; } catch (NumberFormatException e) { errorAndExit("Invalid value for -" + sw + " switch"); } } else { errorAndExit("No value specified for -" + sw + " switch"); } } // FURTHER OPTIONS - NEED TIDYING/FIXING // zero-reward loops check on else if (sw.equals("zerorewardcheck")) { prism.setCheckZeroLoops(true); } // explicit-state model construction else if (sw.equals("explicitbuild")) { explicitbuild = true; } // (hidden) option for testing of prototypical explicit-state model construction else if (sw.equals("explicitbuildtest")) { explicitbuildtest = true; } // MISCELLANEOUS UNDOCUMENTED/UNUSED OPTIONS: // specify main log (hidden option) else if (sw.equals("mainlog")) { if (i < args.length - 1) { mainLogFilename = args[++i]; // use temporary storage because an error would go to the old log log = new PrismFileLog(mainLogFilename); if (!log.ready()) { errorAndExit("Couldn't open log file \"" + mainLogFilename + "\""); } mainLog = log; prism.setMainLog(mainLog); } else { errorAndExit("No file specified for -" + sw + " switch"); } } // mtbdd construction method (hidden option) else if (sw.equals("c1")) { prism.setConstruction(1); } else if (sw.equals("c2")) { prism.setConstruction(2); } else if (sw.equals("c3")) { prism.setConstruction(3); } // mtbdd variable ordering (hidden option) else if (sw.equals("o1")) { prism.setOrdering(1); orderingOverride = true; } else if (sw.equals("o2")) { } else if (sw.equals("o2")) { prism.setOrdering(2); orderingOverride = true; } else if (sw.equals("o2")) { } // reachability off (hidden option) else if (sw.equals("noreach")) { prism.setDoReach(false); } // no bscc computation (hidden option) else if (sw.equals("nobscc")) { prism.setBSCCComp(false); } // reachability options (hidden options) else if (sw.equals("frontier")) { prism.setReachMethod(Prism.REACH_FRONTIER); } else if (sw.equals("bfs")) { prism.setReachMethod(Prism.REACH_BFS); } // enable bisimulation minimisation before model checking (hidden option) else if (sw.equals("bisim")) { prism.setDoBisim(true); } // Other switches - pass to PrismSettings else { i = prism.getSettings().setFromCommandLineSwitch(args, i) - 1; } } // otherwise argument must be a filename else if (modelFilename == null) { modelFilename = args[i]; } else if (propertiesFilename == null) { propertiesFilename = args[i]; } // anything else - must be something wrong with command line syntax else { errorAndExit("Invalid argument syntax"); } } }
void function(String[] args) throws PrismException { int i, j; String sw, s; PrismLog log; constSwitch = STRSTRInvalid empty switchSTRhelpSTR?STRjavamaxmemSTRtimeoutSTRNegative timeout value \STR\STR + sw + STR); } if (timeout > 0) { setTimeout(timeout); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { printVersion(); exit(); } else if (sw.equals(STR)) { if (i < args.length - 1) { settingsFilename = args[++i].trim(); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { printListOfKeywords(); exit(); } else if (sw.equals("pfSTRpctlSTRcsl")) { if (i < args.length - 1) { propertyString = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("propSTRproperty")) { if (i < args.length - 1) { try { propertyToCheck = Integer.parseInt(args[++i]); } catch (NumberFormatException e) { propertyToCheck = args[i]; } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("const")) { if (i < args.length - 1) { if (STR," + args[++i].trim(); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("paramSTRSTR," + args[++i].trim(); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("steadystateSTRssSTRtransientSTRtr")) { if (i < args.length - 1) { dotransient = true; transientTime = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simpathSTRThe -STR switch requires two arguments (path details, filename)STRnobuildSTRtestSTRtestallSTRdddebugSTRddtraceSTRThe -STR switch requires an integer argument (JDDNode ID)STRThe -STR switch requires an additional argument (JDDNode ID)STRimportpepaSTRimportprismppSTRNo parameters specified for -" + sw + STR); } } else if (sw.equals("importmodelSTRNo file/options specified for -" + sw + STR); } } else if (sw.equals("importtransSTRimportstatesSTRNo file specified for -" + sw + STR); } } else if (sw.equals("importlabelsSTRNo file specified for -" + sw + STR); } } else if (sw.equals("importinitdistSTRNo file specified for -" + sw + STR); } } else if (sw.equals("dtmcSTRmdpSTRctmcSTRexportresultsSTR,STRplainSTRSTRcsvSTRcsvSTRmatrixSTRcommentSTRcommentSTRUnknown option \STR\STR + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { processExportModelSwitch(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exporttrans = true; exportTransFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportstaterewards = true; exportStateRewardsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exporttransrewards = true; exportTransRewardsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 2) { exportstaterewards = true; exporttransrewards = true; exportStateRewardsFilename = args[++i]; exportTransRewardsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportstates = true; exportStatesFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportlabels = true; exportLabelsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { exportType = Prism.EXPORT_MATLAB; } else if (sw.equals(STR)) { exportType = Prism.EXPORT_MRMC; } else if (sw.equals(STR)) { exportType = Prism.EXPORT_ROWS; } else if (sw.equals("exportorderedSTRordered")) { exportordered = true; } else if (sw.equals("exportunorderedSTRunordered")) { exportordered = false; } else if (sw.equals(STR)) { if (i < args.length - 1) { exporttransdot = true; exportTransDotFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exporttransdotstates = true; exportTransDotStatesFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { exportmodeldotview = true; } else if (sw.equals(STR)) { if (i < args.length - 1) { exportdot = true; exportDotFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportsccs = true; exportSCCsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportbsccs = true; exportBSCCsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportmecs = true; exportMECsFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("exportsteadystateSTRexportss")) { if (i < args.length - 1) { exportSteadyStateFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("exporttransientSTRexporttr")) { if (i < args.length - 1) { exportTransientFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { processExportStratSwitch(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals(STR)) ? null : new File(filename); prism.setExportPrism(true); prism.setExportPrismFile(f); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals(STR)) ? null : new File(filename); prism.setExportPrismConst(true); prism.setExportPrismConstFile(f); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { String filename = args[++i]; File f = (filename.equals(STR)) ? null : new File(filename); prism.setExportDigital(true); prism.setExportDigitalFile(f); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { prism.setExportTarget(true); prism.setExportTargetFilename(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { prism.setExportProductTrans(true); prism.setExportProductTransFilename(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { prism.setExportProductStates(true); prism.setExportProductStatesFilename(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { prism.setExportProductVector(true); prism.setExportProductVectorFilename(args[++i]); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exporttrans = true; exportType = Prism.EXPORT_PLAIN; exportTransFilename = args[++i]; exportPlainDeprecated = true; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { exportspy = true; exportSpyFilename = args[++i]; } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("sim")) { simulate = true; } else if (sw.equals(STR)) { if (i < args.length - 1) { s = args[++i]; if (s.equals("ci") s.equals("aci") s.equals("apmc") s.equals("sprt")) simMethodName = s; else errorAndExit("Unrecognised option for -STR switch (options are: ci, aci, apmc, sprt)"); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals(STR)) { if (i < args.length - 1) { try { simNumSamples = Integer.parseInt(args[++i]); if (simNumSamples <= 0) throw new NumberFormatException(STRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simconfSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simwidthSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simapproxSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simmanualSTRsimvarSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simmaxrwdSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("simpathlenSTRSTRInvalid value for -" + sw + STR); } } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("zerorewardcheckSTRexplicitbuildSTRexplicitbuildtestSTRmainlogSTRCouldn't open log file \STR\""); } mainLog = log; prism.setMainLog(mainLog); } else { errorAndExit(STR + sw + STR); } } else if (sw.equals("c1STRc2STRc3STRo1STRo2STRo2STRo2STRnoreachSTRnobsccSTRfrontierSTRbfsSTRbisimSTRInvalid argument syntax"); } } }
/** * Process command-line arguments/switches. */
Process command-line arguments/switches
parseArguments
{ "repo_name": "nicodelpiano/prism", "path": "src/prism/PrismCL.java", "license": "gpl-2.0", "size": 86449 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
1,673,693
@OneToOne(cascade=CascadeType.ALL) @PrimaryKeyJoinColumn public PublishReady getPublishReady() { return publishReady; }
@OneToOne(cascade=CascadeType.ALL) PublishReady function() { return publishReady; }
/** * getPublishReady * * Get the associated ready for publish information * * <pre> * Version Date Developer Description * 0.2 24/07/2012 Genevieve Turner(GT) Initial * </pre> * * @return the publishReady */
getPublishReady Get the associated ready for publish information <code> Version Date Developer Description 0.2 24/07/2012 Genevieve Turner(GT) Initial </code>
getPublishReady
{ "repo_name": "anu-doi/anudc", "path": "DataCommons/src/main/java/au/edu/anu/datacommons/data/db/model/FedoraObject.java", "license": "gpl-3.0", "size": 11147 }
[ "javax.persistence.CascadeType", "javax.persistence.OneToOne" ]
import javax.persistence.CascadeType; import javax.persistence.OneToOne;
import javax.persistence.*;
[ "javax.persistence" ]
javax.persistence;
1,242,703
@Override public void addOOVRules(int sourceWord, List<FeatureFunction> featureFunctions) { // TODO: _OOV shouldn't be outright added, since the word might not be OOV for the LM (but now // almost // certainly is) final int targetWord = this.joshuaConfiguration.mark_oovs ? Vocabulary.id(Vocabulary .word(sourceWord) + "_OOV") : sourceWord; int[] sourceWords = { sourceWord }; int[] targetWords = { targetWord }; final String oovAlignment = "0-0"; if (this.joshuaConfiguration.oovList != null && this.joshuaConfiguration.oovList.size() != 0) { for (OOVItem item : this.joshuaConfiguration.oovList) { Rule oovRule = new Rule(Vocabulary.id(item.label), sourceWords, targetWords, "", 0, oovAlignment); addRule(oovRule); oovRule.estimateRuleCost(featureFunctions); } } else { int nt_i = Vocabulary.id(this.joshuaConfiguration.default_non_terminal); Rule oovRule = new Rule(nt_i, sourceWords, targetWords, "", 0, oovAlignment); addRule(oovRule); oovRule.estimateRuleCost(featureFunctions); } }
void function(int sourceWord, List<FeatureFunction> featureFunctions) { final int targetWord = this.joshuaConfiguration.mark_oovs ? Vocabulary.id(Vocabulary .word(sourceWord) + "_OOV") : sourceWord; int[] sourceWords = { sourceWord }; int[] targetWords = { targetWord }; final String oovAlignment = "0-0"; if (this.joshuaConfiguration.oovList != null && this.joshuaConfiguration.oovList.size() != 0) { for (OOVItem item : this.joshuaConfiguration.oovList) { Rule oovRule = new Rule(Vocabulary.id(item.label), sourceWords, targetWords, STR", 0, oovAlignment); addRule(oovRule); oovRule.estimateRuleCost(featureFunctions); } }
/*** * Takes an input word and creates an OOV rule in the current grammar for that word. * * @param sourceWord integer representation of word * @param featureFunctions {@link java.util.List} of {@link org.apache.joshua.decoder.ff.FeatureFunction}'s */
Takes an input word and creates an OOV rule in the current grammar for that word
addOOVRules
{ "repo_name": "fhieber/incubator-joshua", "path": "src/main/java/org/apache/joshua/decoder/ff/tm/hash_based/MemoryBasedBatchGrammar.java", "license": "apache-2.0", "size": 9849 }
[ "java.util.List", "org.apache.joshua.corpus.Vocabulary", "org.apache.joshua.decoder.JoshuaConfiguration", "org.apache.joshua.decoder.ff.FeatureFunction", "org.apache.joshua.decoder.ff.tm.Rule" ]
import java.util.List; import org.apache.joshua.corpus.Vocabulary; import org.apache.joshua.decoder.JoshuaConfiguration; import org.apache.joshua.decoder.ff.FeatureFunction; import org.apache.joshua.decoder.ff.tm.Rule;
import java.util.*; import org.apache.joshua.corpus.*; import org.apache.joshua.decoder.*; import org.apache.joshua.decoder.ff.*; import org.apache.joshua.decoder.ff.tm.*;
[ "java.util", "org.apache.joshua" ]
java.util; org.apache.joshua;
1,441,058
MongoOptions options = new MongoOptions(); options.connectionsPerHost = getConnectionsPerHost(); options.connectTimeout = getConnectionTimeout(); options.maxWaitTime = getMaxWaitTime(); options.threadsAllowedToBlockForConnectionMultiplier = getThreadsAllowedToBlockForConnectionMultiplier(); options.autoConnectRetry = isAutoConnectRetry(); options.socketTimeout = getSocketTimeOut(); if (logger.isDebugEnabled()) { logger.debug("Mongo Options"); logger.debug("Connections per host :{}", options.connectionsPerHost); logger.debug("Connection timeout : {}", options.connectTimeout); logger.debug("Max wait timeout : {}", options.maxWaitTime); logger.debug("Threads allowed to block : {}", options.threadsAllowedToBlockForConnectionMultiplier); logger.debug("Autoconnect retry : {}", options.autoConnectRetry); logger.debug("Socket timeout : {}", options.socketTimeout); } return options; }
MongoOptions options = new MongoOptions(); options.connectionsPerHost = getConnectionsPerHost(); options.connectTimeout = getConnectionTimeout(); options.maxWaitTime = getMaxWaitTime(); options.threadsAllowedToBlockForConnectionMultiplier = getThreadsAllowedToBlockForConnectionMultiplier(); options.autoConnectRetry = isAutoConnectRetry(); options.socketTimeout = getSocketTimeOut(); if (logger.isDebugEnabled()) { logger.debug(STR); logger.debug(STR, options.connectionsPerHost); logger.debug(STR, options.connectTimeout); logger.debug(STR, options.maxWaitTime); logger.debug(STR, options.threadsAllowedToBlockForConnectionMultiplier); logger.debug(STR, options.autoConnectRetry); logger.debug(STR, options.socketTimeout); } return options; }
/** * Uses the configured parameters to create a MongoOptions instance. * * @return MongoOptions instance based on the configured properties */
Uses the configured parameters to create a MongoOptions instance
createMongoOptions
{ "repo_name": "AmyStorm/omnia-web", "path": "omnia-web-manage/src/main/java/org/axonframework/eventstore/mongo/MongoOptionsFactory.java", "license": "apache-2.0", "size": 6777 }
[ "com.mongodb.MongoOptions" ]
import com.mongodb.MongoOptions;
import com.mongodb.*;
[ "com.mongodb" ]
com.mongodb;
1,957,537
public void testWifiWatchdog() throws Exception { if (!WifiFeature.isWifiSupported(getContext())) { // skip the test if WiFi is not supported return; } // Make sure WiFi is enabled if (!mWifiManager.isWifiEnabled()) { setWifiEnabled(true); Thread.sleep(DURATION); } assertTrue(mWifiManager.isWifiEnabled()); int i = 0; for (; i < 15; i++) { // Wait for a WiFi connection connectWifi(); // Read TX packet counter int txcount1 = getTxPacketCount(); // Do some network operations HttpURLConnection connection = null; try { URL url = new URL("http://www.google.com/"); connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(TIMEOUT_MSEC); connection.setReadTimeout(TIMEOUT_MSEC); connection.setUseCaches(false); connection.getInputStream(); } catch (Exception e) { // ignore } finally { if (connection != null) connection.disconnect(); } // Read TX packet counter again and make sure it increases int txcount2 = getTxPacketCount(); if (txcount2 > txcount1) { break; } else { Thread.sleep(DURATION); } } assertTrue(i < 15); }
void function() throws Exception { if (!WifiFeature.isWifiSupported(getContext())) { return; } if (!mWifiManager.isWifiEnabled()) { setWifiEnabled(true); Thread.sleep(DURATION); } assertTrue(mWifiManager.isWifiEnabled()); int i = 0; for (; i < 15; i++) { connectWifi(); int txcount1 = getTxPacketCount(); HttpURLConnection connection = null; try { URL url = new URL("http: connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(TIMEOUT_MSEC); connection.setReadTimeout(TIMEOUT_MSEC); connection.setUseCaches(false); connection.getInputStream(); } catch (Exception e) { } finally { if (connection != null) connection.disconnect(); } int txcount2 = getTxPacketCount(); if (txcount2 > txcount1) { break; } else { Thread.sleep(DURATION); } } assertTrue(i < 15); }
/** * The new WiFi watchdog requires kernel/driver to export some packet loss * counters. This CTS tests whether those counters are correctly exported. * To pass this CTS test, a connected WiFi link is required. */
The new WiFi watchdog requires kernel/driver to export some packet loss counters. This CTS tests whether those counters are correctly exported. To pass this CTS test, a connected WiFi link is required
testWifiWatchdog
{ "repo_name": "s20121035/rk3288_android5.1_repo", "path": "cts/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java", "license": "gpl-3.0", "size": 20031 }
[ "java.net.HttpURLConnection" ]
import java.net.HttpURLConnection;
import java.net.*;
[ "java.net" ]
java.net;
1,929,958
@Test public void testCallbackThreadForSemaphoreIsolation() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder() .setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) {
void function() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder() .setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) {
/** * Test a successful command execution. */
Test a successful command execution
testCallbackThreadForSemaphoreIsolation
{ "repo_name": "davidkarlsen/Hystrix", "path": "hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandTest.java", "license": "apache-2.0", "size": 282697 }
[ "com.netflix.hystrix.HystrixCommandProperties", "java.util.concurrent.atomic.AtomicReference" ]
import com.netflix.hystrix.HystrixCommandProperties; import java.util.concurrent.atomic.AtomicReference;
import com.netflix.hystrix.*; import java.util.concurrent.atomic.*;
[ "com.netflix.hystrix", "java.util" ]
com.netflix.hystrix; java.util;
2,046,029