before stringlengths 33 3.21M | after stringlengths 63 3.21M | repo stringlengths 1 56 | type stringclasses 1
value | __index_level_0__ int64 0 442k |
|---|---|---|---|---|
@SuppressWarnings("unchecked")
private static void loadPlugin(File pluginDir, String reloadId) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
if (!pluginDir.isDirectory()) {
return;
}
String dir = pluginDir.getAbsolutePath();
PluginClassLoader classLoader = new PluginClassLoader();
super.addURL(new File(dir + "/classes/").toURI().toURL());
try {
URLConnection uc = new File(dir + "/classes/").toURI().toURL().openConnection();
if (uc instanceof JarURLConnection) {
uc.setUseCaches(true);
((JarURLConnection) uc).getManifest();
cachedJarFiles.add((JarURLConnection) uc);
}
} catch (IOException e) {
logger.error("failed to cache plugin jar file=" + new File(dir + "/classes/").toURI().toURL().toExternalForm(), e);
}
File jars = new File(dir + "/libs/");
if (!(jars.exists() && jars.isDirectory())) {
return;
}
File[] jarFiles = jars.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
if (jarFiles != null) {
for (File file : jarFiles) {
String path = file.toURI().toString() + "!/";
URL jarURL = new URL("jar", "", -1, path);
classLoader.addURL(jarURL);
}
}
File file = new File(dir + "/plugin.json");
if (!file.exists()) {
logger.info("can not find plugin.json in " + dir);
return;
}
if (!file.canRead()) {
logger.error("can not read plugin in " + dir);
return;
}
try (InputStream in = new FileInputStream(file)) {
String content = IOUtils.toString(in, Constants.UTF8.displayName());
List<PluginInfo> pluginInfos = JSON.parseObject(content, new TypeReference<List<PluginInfo>>() {
});
String currentVersion = ConfigUtils.getProperty("xyj.version");
for (PluginInfo pluginInfo : pluginInfos) {
if (reloadId != null) {
if (!reloadId.equals(pluginInfo.getId())) {
continue;
}
}
if (pluginInfo.getDependency() != null) {
Dependency dependency = pluginInfo.getDependency();
if (StringUtils.isNotBlank(dependency.getMin()) && dependency.getMin().compareTo(currentVersion) > 0) {
logger.error("the plugin {} Minimum dependent version {}, current version {}", pluginInfo.getId(), dependency.getMin(), currentVersion);
continue;
}
if (StringUtils.isNotBlank(dependency.getMax()) && dependency.getMax().compareTo(currentVersion) < 0) {
logger.error("the plugin {} Maxmum dependent version {}, current version {}", pluginInfo.getId(), dependency.getMin(), currentVersion);
continue;
}
}
Plugin plugin = (Plugin) classLoader.loadClass(pluginInfo.getClazz()).newInstance();
plugin.setPluginInfo(pluginInfo);
pluginInfo.setPlugin(plugin);
pluginInfo.setRuntimeFolder(pluginDir.getName());
pluginInfo.setRuntimeDirectory(pluginDir);
plugin.init();
PluginManager.getInstance().register(pluginInfo);
classLoaderMap.put(pluginInfo.getId(), classLoader);
}
} catch (Exception e) {
logger.error(file.getAbsolutePath(), e);
}
} | @SuppressWarnings("unchecked")
private static void loadPlugin(File pluginDir, String reloadId) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
if (!pluginDir.isDirectory()) {
return;
}
String dir = pluginDir.getAbsolutePath();
PluginClassLoader classLoader = new PluginClassLoader();
<DeepExtract>
super.addURL(new File(dir + "/classes/").toURI().toURL());
try {
URLConnection uc = new File(dir + "/classes/").toURI().toURL().openConnection();
if (uc instanceof JarURLConnection) {
uc.setUseCaches(true);
((JarURLConnection) uc).getManifest();
cachedJarFiles.add((JarURLConnection) uc);
}
} catch (IOException e) {
logger.error("failed to cache plugin jar file=" + new File(dir + "/classes/").toURI().toURL().toExternalForm(), e);
}
</DeepExtract>
File jars = new File(dir + "/libs/");
if (!(jars.exists() && jars.isDirectory())) {
return;
}
File[] jarFiles = jars.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
if (jarFiles != null) {
for (File file : jarFiles) {
String path = file.toURI().toString() + "!/";
URL jarURL = new URL("jar", "", -1, path);
classLoader.addURL(jarURL);
}
}
File file = new File(dir + "/plugin.json");
if (!file.exists()) {
logger.info("can not find plugin.json in " + dir);
return;
}
if (!file.canRead()) {
logger.error("can not read plugin in " + dir);
return;
}
try (InputStream in = new FileInputStream(file)) {
String content = IOUtils.toString(in, Constants.UTF8.displayName());
List<PluginInfo> pluginInfos = JSON.parseObject(content, new TypeReference<List<PluginInfo>>() {
});
String currentVersion = ConfigUtils.getProperty("xyj.version");
for (PluginInfo pluginInfo : pluginInfos) {
if (reloadId != null) {
if (!reloadId.equals(pluginInfo.getId())) {
continue;
}
}
if (pluginInfo.getDependency() != null) {
Dependency dependency = pluginInfo.getDependency();
if (StringUtils.isNotBlank(dependency.getMin()) && dependency.getMin().compareTo(currentVersion) > 0) {
logger.error("the plugin {} Minimum dependent version {}, current version {}", pluginInfo.getId(), dependency.getMin(), currentVersion);
continue;
}
if (StringUtils.isNotBlank(dependency.getMax()) && dependency.getMax().compareTo(currentVersion) < 0) {
logger.error("the plugin {} Maxmum dependent version {}, current version {}", pluginInfo.getId(), dependency.getMin(), currentVersion);
continue;
}
}
Plugin plugin = (Plugin) classLoader.loadClass(pluginInfo.getClazz()).newInstance();
plugin.setPluginInfo(pluginInfo);
pluginInfo.setPlugin(plugin);
pluginInfo.setRuntimeFolder(pluginDir.getName());
pluginInfo.setRuntimeDirectory(pluginDir);
plugin.init();
PluginManager.getInstance().register(pluginInfo);
classLoaderMap.put(pluginInfo.getId(), classLoader);
}
} catch (Exception e) {
logger.error(file.getAbsolutePath(), e);
}
} | xiaoyaoji | positive | 1,967 |
private void headerRefreshing() {
if (upAnimator != null) {
upAnimator.cancel();
}
mHeaderState = REFRESHING;
LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();
params.topMargin = 0;
mHeaderView.setLayoutParams(params);
invalidate();
mHeaderImageView.setVisibility(View.GONE);
mHeaderImageView.clearAnimation();
mHeaderImageView.setImageDrawable(null);
mHeaderProgressBar.setVisibility(View.VISIBLE);
mHeaderTextView.setText(R.string.pull_to_refresh_refreshing_label);
if (mOnHeaderRefreshListener != null) {
mOnHeaderRefreshListener.onHeaderRefresh(this);
}
} | private void headerRefreshing() {
if (upAnimator != null) {
upAnimator.cancel();
}
mHeaderState = REFRESHING;
<DeepExtract>
LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();
params.topMargin = 0;
mHeaderView.setLayoutParams(params);
invalidate();
</DeepExtract>
mHeaderImageView.setVisibility(View.GONE);
mHeaderImageView.clearAnimation();
mHeaderImageView.setImageDrawable(null);
mHeaderProgressBar.setVisibility(View.VISIBLE);
mHeaderTextView.setText(R.string.pull_to_refresh_refreshing_label);
if (mOnHeaderRefreshListener != null) {
mOnHeaderRefreshListener.onHeaderRefresh(this);
}
} | MyBlogDemo | positive | 1,968 |
@Override
public void set(PDU pdu, Target target, Object userHandle, ResponseListener listener) throws IOException {
pdu.setType(PDU.SET);
send(pdu, target, null, userHandle, listener);
} | @Override
public void set(PDU pdu, Target target, Object userHandle, ResponseListener listener) throws IOException {
pdu.setType(PDU.SET);
<DeepExtract>
send(pdu, target, null, userHandle, listener);
</DeepExtract>
} | tnm4j | positive | 1,969 |
@Override
StaticStructureElementInstance getElementInstance() {
return containerInstance;
} | @Override
StaticStructureElementInstance getElementInstance() {
<DeepExtract>
return containerInstance;
</DeepExtract>
} | dsl | positive | 1,970 |
private static File getDexDir(Context context, ApplicationInfo applicationInfo) throws IOException {
File cache = new File(applicationInfo.dataDir, CODE_CACHE_NAME);
try {
mkdirChecked(cache);
} catch (IOException e) {
cache = new File(context.getFilesDir(), CODE_CACHE_NAME);
mkdirChecked(cache);
}
File dexDir = new File(cache, CODE_CACHE_SECONDARY_FOLDER_NAME);
dexDir.mkdir();
if (!dexDir.isDirectory()) {
File parent = dexDir.getParentFile();
if (parent == null) {
Log.e(TAG, "Failed to create dir " + dexDir.getPath() + ". Parent file is null.");
} else {
Log.e(TAG, "Failed to create dir " + dexDir.getPath() + ". parent file is a dir " + parent.isDirectory() + ", a file " + parent.isFile() + ", exists " + parent.exists() + ", readable " + parent.canRead() + ", writable " + parent.canWrite());
}
throw new IOException("Failed to create directory " + dexDir.getPath());
}
return dexDir;
} | private static File getDexDir(Context context, ApplicationInfo applicationInfo) throws IOException {
File cache = new File(applicationInfo.dataDir, CODE_CACHE_NAME);
try {
mkdirChecked(cache);
} catch (IOException e) {
cache = new File(context.getFilesDir(), CODE_CACHE_NAME);
mkdirChecked(cache);
}
File dexDir = new File(cache, CODE_CACHE_SECONDARY_FOLDER_NAME);
<DeepExtract>
dexDir.mkdir();
if (!dexDir.isDirectory()) {
File parent = dexDir.getParentFile();
if (parent == null) {
Log.e(TAG, "Failed to create dir " + dexDir.getPath() + ". Parent file is null.");
} else {
Log.e(TAG, "Failed to create dir " + dexDir.getPath() + ". parent file is a dir " + parent.isDirectory() + ", a file " + parent.isFile() + ", exists " + parent.exists() + ", readable " + parent.canRead() + ", writable " + parent.canWrite());
}
throw new IOException("Failed to create directory " + dexDir.getPath());
}
</DeepExtract>
return dexDir;
} | fastdex | positive | 1,971 |
@Override
default float getOutlineTop() {
return getPadding().getTop();
} | @Override
default float getOutlineTop() {
<DeepExtract>
return getPadding().getTop();
</DeepExtract>
} | ph-pdf-layout | positive | 1,972 |
public void removeAllPlots() {
plots.clear();
if (linkedLegendPanel != null) {
linkedLegendPanel.updateLegends();
}
for (int i = 0; i < plots.size(); i++) {
getPlot(i).coordNoted = null;
}
repaint();
} | public void removeAllPlots() {
plots.clear();
if (linkedLegendPanel != null) {
linkedLegendPanel.updateLegends();
}
<DeepExtract>
for (int i = 0; i < plots.size(); i++) {
getPlot(i).coordNoted = null;
}
repaint();
</DeepExtract>
} | jmathplot | positive | 1,973 |
@Test
public void testUpdateFromSingleTable() {
when(db.update(anyString(), (ContentValues) anyObject(), anyString(), (String[]) anyObject())).thenReturn(2);
ContentValues values = new ContentValues();
values.put("test", "test");
provider.update(Uri.parse("content://" + "test.com/parent"), values, null, null);
provider.update(Uri.parse("content://" + eq("parent")), (ContentValues) anyObject(), anyString(), (String[]) anyObject());
} | @Test
public void testUpdateFromSingleTable() {
when(db.update(anyString(), (ContentValues) anyObject(), anyString(), (String[]) anyObject())).thenReturn(2);
ContentValues values = new ContentValues();
values.put("test", "test");
provider.update(Uri.parse("content://" + "test.com/parent"), values, null, null);
<DeepExtract>
provider.update(Uri.parse("content://" + eq("parent")), (ContentValues) anyObject(), anyString(), (String[]) anyObject());
</DeepExtract>
} | sqlite-provider | positive | 1,974 |
public final int findUri(int prefix) {
if (m_dataLength == 0) {
return -1;
}
int offset = m_dataLength - 1;
for (int i = m_depth; i != 0; --i) {
int count = m_data[offset];
offset -= 2;
for (; count != 0; --count) {
if (true) {
if (m_data[offset] == prefix) {
return m_data[offset + 1];
}
} else {
if (m_data[offset + 1] == prefix) {
return m_data[offset];
}
}
offset -= 2;
}
}
return -1;
} | public final int findUri(int prefix) {
<DeepExtract>
if (m_dataLength == 0) {
return -1;
}
int offset = m_dataLength - 1;
for (int i = m_depth; i != 0; --i) {
int count = m_data[offset];
offset -= 2;
for (; count != 0; --count) {
if (true) {
if (m_data[offset] == prefix) {
return m_data[offset + 1];
}
} else {
if (m_data[offset + 1] == prefix) {
return m_data[offset];
}
}
offset -= 2;
}
}
return -1;
</DeepExtract>
} | Xpatch | positive | 1,975 |
public void actionPerformed(java.awt.event.ActionEvent evt) {
assert SwingUtilities.isEventDispatchThread();
BacklogData data = BacklogData.create(issue.getRepository());
User myself = data.getMyself();
if (myself != null) {
setSelectedAssignee(myself);
}
} | public void actionPerformed(java.awt.event.ActionEvent evt) {
<DeepExtract>
assert SwingUtilities.isEventDispatchThread();
BacklogData data = BacklogData.create(issue.getRepository());
User myself = data.getMyself();
if (myself != null) {
setSelectedAssignee(myself);
}
</DeepExtract>
} | netbeans-backlog-plugin | positive | 1,976 |
@Test(timeout = 1000)
public void testOversizedInputs() {
List<String> c = IntStream.range(0, 100000).mapToObj(i -> "B/" + i).collect(toList());
testCase(c, c, null, true);
} | @Test(timeout = 1000)
public void testOversizedInputs() {
List<String> c = IntStream.range(0, 100000).mapToObj(i -> "B/" + i).collect(toList());
<DeepExtract>
testCase(c, c, null, true);
</DeepExtract>
} | search-extra | positive | 1,977 |
private int addStructTreeRootObject() throws Exception {
objOffset.add(byteCount);
append(objOffset.size());
append(" 0 obj\n");
append(Integer.toString("<<\n"));
append(Integer.toString("/Type /StructTreeRoot\n"));
append(Integer.toString("/ParentTree "));
append(Integer.toString(getObjNumber() + 1));
append(Integer.toString(" 0 R\n"));
append(Integer.toString("/K [\n"));
append(Integer.toString(getObjNumber() + 2));
append(Integer.toString(" 0 R\n"));
append(Integer.toString("]\n"));
append(Integer.toString(">>\n"));
append("endobj\n");
return objOffset.size();
} | private int addStructTreeRootObject() throws Exception {
objOffset.add(byteCount);
append(objOffset.size());
append(" 0 obj\n");
append(Integer.toString("<<\n"));
append(Integer.toString("/Type /StructTreeRoot\n"));
append(Integer.toString("/ParentTree "));
append(Integer.toString(getObjNumber() + 1));
append(Integer.toString(" 0 R\n"));
append(Integer.toString("/K [\n"));
append(Integer.toString(getObjNumber() + 2));
append(Integer.toString(" 0 R\n"));
append(Integer.toString("]\n"));
append(Integer.toString(">>\n"));
append("endobj\n");
<DeepExtract>
return objOffset.size();
</DeepExtract>
} | pdfjet | positive | 1,978 |
@Override
public MutablePair<Second, First> invert() {
return new MutablePair<First, Second>(second, first);
} | @Override
public MutablePair<Second, First> invert() {
<DeepExtract>
return new MutablePair<First, Second>(second, first);
</DeepExtract>
} | gdx-kiwi | positive | 1,979 |
@Override
public JsonGenerator writePropertyId(long id) throws JacksonException {
final String name = Long.toString(id);
if (!_streamWriteContext.writeName(name)) {
_reportError("Can not write a property name, expecting a value");
}
String ns = (_nextName == null) ? "" : _nextName.getNamespaceURI();
_nameToEncode.namespace = ns;
_nameToEncode.localPart = name;
_nameProcessor.encodeName(_nameToEncode);
setNextName(new QName(_nameToEncode.namespace, _nameToEncode.localPart));
return this;
} | @Override
public JsonGenerator writePropertyId(long id) throws JacksonException {
final String name = Long.toString(id);
<DeepExtract>
if (!_streamWriteContext.writeName(name)) {
_reportError("Can not write a property name, expecting a value");
}
String ns = (_nextName == null) ? "" : _nextName.getNamespaceURI();
_nameToEncode.namespace = ns;
_nameToEncode.localPart = name;
_nameProcessor.encodeName(_nameToEncode);
setNextName(new QName(_nameToEncode.namespace, _nameToEncode.localPart));
return this;
</DeepExtract>
} | jackson-dataformat-xml | positive | 1,980 |
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
if (value == null) {
throw new RuntimeException("Value for " + "id" + " cannot be null");
}
criteria.add(new Criterion("id >=", value));
return (Criteria) this;
} | public Criteria andIdGreaterThanOrEqualTo(Integer value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "id" + " cannot be null");
}
criteria.add(new Criterion("id >=", value));
</DeepExtract>
return (Criteria) this;
} | cloud | positive | 1,981 |
@Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
log.info(">>>> generating extra files...");
Map<String, String> map = new HashMap<>();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().toString());
log.info("property:[{}];value:[{}]", entry.getKey().toString(), entry.getValue().toString());
}
Table table = new Table(context, introspectedTable, map);
VelocityContext templateContext = new VelocityContext();
templateContext.put("table", table);
templateContext.put("projectDir.ss", projectDir);
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate("template/" + "test.vm", "UTF-8");
StringWriter sw = new StringWriter();
t.merge(templateContext, sw);
return sw.toString();
log.info("hierarchical table structure: {}", content);
List<TemplateConfig> configs = new Yaml().loadAs(scvxConfigYml, ConfigWrapper.class).getTemplateConfig();
for (TemplateConfig config : configs) {
String template = config.getTemplate();
String destDir = config.getDestDir().replaceAll("\\.", "/");
String destPackage = config.getDestPackage();
String destFileName = config.getDestFileName();
String absPath = (projectDir == null || projectDir.isEmpty() ? "" : projectDir + (projectDir.endsWith("/") || projectDir.endsWith("\\") ? "" : "/")) + destDir + "/" + destPackage.replace(".", "/") + "/" + destFileName;
absPath = absPath.replace("//", "/");
absPath = absPath.replace("${entityName}", table.getEntityName());
absPath = absPath.replace("${entityLowerCamel}", table.getEntityLowerCamel());
absPath = absPath.replace("${basePackage}", basePackage.replace(".", "/"));
log.info("generate file `{}` from template `{}`", absPath, template);
content = renderTemplateAsString(config.getTemplate(), templateContext);
try {
FileUtil.writeStringToFile(absPath, content);
} catch (IOException e) {
log.error(e.getMessage());
}
}
log.info("<<< generated extra files.");
return null;
} | @Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
log.info(">>>> generating extra files...");
Map<String, String> map = new HashMap<>();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().toString());
log.info("property:[{}];value:[{}]", entry.getKey().toString(), entry.getValue().toString());
}
Table table = new Table(context, introspectedTable, map);
VelocityContext templateContext = new VelocityContext();
templateContext.put("table", table);
templateContext.put("projectDir.ss", projectDir);
<DeepExtract>
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate("template/" + "test.vm", "UTF-8");
StringWriter sw = new StringWriter();
t.merge(templateContext, sw);
return sw.toString();
</DeepExtract>
log.info("hierarchical table structure: {}", content);
List<TemplateConfig> configs = new Yaml().loadAs(scvxConfigYml, ConfigWrapper.class).getTemplateConfig();
for (TemplateConfig config : configs) {
String template = config.getTemplate();
String destDir = config.getDestDir().replaceAll("\\.", "/");
String destPackage = config.getDestPackage();
String destFileName = config.getDestFileName();
String absPath = (projectDir == null || projectDir.isEmpty() ? "" : projectDir + (projectDir.endsWith("/") || projectDir.endsWith("\\") ? "" : "/")) + destDir + "/" + destPackage.replace(".", "/") + "/" + destFileName;
absPath = absPath.replace("//", "/");
absPath = absPath.replace("${entityName}", table.getEntityName());
absPath = absPath.replace("${entityLowerCamel}", table.getEntityLowerCamel());
absPath = absPath.replace("${basePackage}", basePackage.replace(".", "/"));
log.info("generate file `{}` from template `{}`", absPath, template);
content = renderTemplateAsString(config.getTemplate(), templateContext);
try {
FileUtil.writeStringToFile(absPath, content);
} catch (IOException e) {
log.error(e.getMessage());
}
}
log.info("<<< generated extra files.");
return null;
} | mybatis-generator-gui-extension | positive | 1,982 |
@Test
public void testSimpleOpenAPIImportJSON() {
OpenAPIImporter importer = null;
try {
importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.json", null);
} catch (IOException ioe) {
fail("Exception should not be thrown");
}
List<Service> services = null;
try {
services = importer.getServiceDefinitions();
} catch (MockRepositoryImportException e) {
fail("Exception should not be thrown");
}
assertEquals(1, services.size());
Service service = services.get(0);
assertEquals("OpenAPI Car API", service.getName());
Assert.assertEquals(ServiceType.REST, service.getType());
assertEquals("1.0.0", service.getVersion());
List<Resource> resources = importer.getResourceDefinitions(service);
assertEquals(1, resources.size());
assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType());
assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion()));
assertNotNull(resources.get(0).getContent());
assertEquals(3, service.getOperations().size());
for (Operation operation : service.getOperations()) {
if ("GET /owner/{owner}/car".equals(operation.getName())) {
assertEquals("GET", operation.getMethod());
assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher());
assertEquals("owner ?? page && limit", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(1, exchanges.size());
assertEquals(1, operation.getResourcePaths().size());
assertTrue(operation.getResourcePaths().contains("/owner/laurent/car"));
for (Exchange exchange : exchanges) {
if (exchange instanceof RequestResponsePair) {
RequestResponsePair entry = (RequestResponsePair) exchange;
Request request = entry.getRequest();
Response response = entry.getResponse();
assertNotNull(request);
assertNotNull(response);
assertEquals("laurent_cars", request.getName());
assertEquals("laurent_cars", response.getName());
assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria());
assertEquals("200", response.getStatus());
assertEquals("application/json", response.getMediaType());
assertNotNull(response.getContent());
} else {
fail("Exchange has the wrong type. Expecting RequestResponsePair");
}
}
} else if ("POST /owner/{owner}/car".equals(operation.getName())) {
assertEquals("POST", operation.getMethod());
assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher());
assertEquals("owner", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(1, exchanges.size());
assertEquals(1, operation.getResourcePaths().size());
assertTrue(operation.getResourcePaths().contains("/owner/laurent/car"));
for (Exchange exchange : exchanges) {
if (exchange instanceof RequestResponsePair) {
RequestResponsePair entry = (RequestResponsePair) exchange;
Request request = entry.getRequest();
Response response = entry.getResponse();
assertNotNull(request);
assertNotNull(response);
assertEquals("laurent_307", request.getName());
assertEquals("laurent_307", response.getName());
assertEquals("/owner=laurent", response.getDispatchCriteria());
assertEquals("201", response.getStatus());
assertEquals("application/json", response.getMediaType());
assertNotNull(response.getContent());
} else {
fail("Exchange has the wrong type. Expecting RequestResponsePair");
}
}
} else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) {
assertEquals("POST", operation.getMethod());
assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher());
assertEquals("owner && car", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(0, exchanges.size());
} else {
fail("Unknown operation name: " + operation.getName());
}
}
} | @Test
public void testSimpleOpenAPIImportJSON() {
OpenAPIImporter importer = null;
try {
importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.json", null);
} catch (IOException ioe) {
fail("Exception should not be thrown");
}
<DeepExtract>
List<Service> services = null;
try {
services = importer.getServiceDefinitions();
} catch (MockRepositoryImportException e) {
fail("Exception should not be thrown");
}
assertEquals(1, services.size());
Service service = services.get(0);
assertEquals("OpenAPI Car API", service.getName());
Assert.assertEquals(ServiceType.REST, service.getType());
assertEquals("1.0.0", service.getVersion());
List<Resource> resources = importer.getResourceDefinitions(service);
assertEquals(1, resources.size());
assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType());
assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion()));
assertNotNull(resources.get(0).getContent());
assertEquals(3, service.getOperations().size());
for (Operation operation : service.getOperations()) {
if ("GET /owner/{owner}/car".equals(operation.getName())) {
assertEquals("GET", operation.getMethod());
assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher());
assertEquals("owner ?? page && limit", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(1, exchanges.size());
assertEquals(1, operation.getResourcePaths().size());
assertTrue(operation.getResourcePaths().contains("/owner/laurent/car"));
for (Exchange exchange : exchanges) {
if (exchange instanceof RequestResponsePair) {
RequestResponsePair entry = (RequestResponsePair) exchange;
Request request = entry.getRequest();
Response response = entry.getResponse();
assertNotNull(request);
assertNotNull(response);
assertEquals("laurent_cars", request.getName());
assertEquals("laurent_cars", response.getName());
assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria());
assertEquals("200", response.getStatus());
assertEquals("application/json", response.getMediaType());
assertNotNull(response.getContent());
} else {
fail("Exchange has the wrong type. Expecting RequestResponsePair");
}
}
} else if ("POST /owner/{owner}/car".equals(operation.getName())) {
assertEquals("POST", operation.getMethod());
assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher());
assertEquals("owner", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(1, exchanges.size());
assertEquals(1, operation.getResourcePaths().size());
assertTrue(operation.getResourcePaths().contains("/owner/laurent/car"));
for (Exchange exchange : exchanges) {
if (exchange instanceof RequestResponsePair) {
RequestResponsePair entry = (RequestResponsePair) exchange;
Request request = entry.getRequest();
Response response = entry.getResponse();
assertNotNull(request);
assertNotNull(response);
assertEquals("laurent_307", request.getName());
assertEquals("laurent_307", response.getName());
assertEquals("/owner=laurent", response.getDispatchCriteria());
assertEquals("201", response.getStatus());
assertEquals("application/json", response.getMediaType());
assertNotNull(response.getContent());
} else {
fail("Exchange has the wrong type. Expecting RequestResponsePair");
}
}
} else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) {
assertEquals("POST", operation.getMethod());
assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher());
assertEquals("owner && car", operation.getDispatcherRules());
List<Exchange> exchanges = null;
try {
exchanges = importer.getMessageDefinitions(service, operation);
} catch (Exception e) {
fail("No exception should be thrown when importing message definitions.");
}
assertEquals(0, exchanges.size());
} else {
fail("Unknown operation name: " + operation.getName());
}
}
</DeepExtract>
} | microcks | positive | 1,983 |
public Criteria andGoodsnameNotEqualTo(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "goodsname" + " cannot be null");
}
criteria.add(new Criterion("goodsName <>", value));
return (Criteria) this;
} | public Criteria andGoodsnameNotEqualTo(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "goodsname" + " cannot be null");
}
criteria.add(new Criterion("goodsName <>", value));
</DeepExtract>
return (Criteria) this;
} | garbage-collection | positive | 1,984 |
public StateListBuilder<V, T> longPressable(V value) {
states.add(android.R.attr.state_long_pressable);
values.add(value);
return this;
} | public StateListBuilder<V, T> longPressable(V value) {
<DeepExtract>
states.add(android.R.attr.state_long_pressable);
values.add(value);
return this;
</DeepExtract>
} | relight | positive | 1,986 |
@Override
public void actionPerformed(ActionEvent e) {
linkBuilder = new ImageViewerLinkBuilder(true);
imageList = new ImageViewerImageList(this, linkBuilder);
imageListScrollpane.setViewportView(imageList);
if (imageList.getModel().getSize() > 0) {
imageList.setSelectedIndex(0);
}
} | @Override
public void actionPerformed(ActionEvent e) {
<DeepExtract>
linkBuilder = new ImageViewerLinkBuilder(true);
imageList = new ImageViewerImageList(this, linkBuilder);
imageListScrollpane.setViewportView(imageList);
</DeepExtract>
if (imageList.getModel().getSize() > 0) {
imageList.setSelectedIndex(0);
}
} | SnippingToolPlusPlus | positive | 1,987 |
public static void main(String[] args) {
Outputer outputer = new Outputer();
new Thread(new MyRunnable("llllllllll", outputer)).start();
new Thread(new MyRunnable("oooooooooo", outputer)).start();
} | public static void main(String[] args) {
<DeepExtract>
Outputer outputer = new Outputer();
new Thread(new MyRunnable("llllllllll", outputer)).start();
new Thread(new MyRunnable("oooooooooo", outputer)).start();
</DeepExtract>
} | java-core | positive | 1,988 |
private static void racePauseResuming(final TestCallStreamObserver<?> downstream, int times) {
Observable.range(0, times).concatMapCompletable(new Function<Integer, CompletableSource>() {
@Override
public CompletableSource apply(Integer i) {
return Completable.fromAction(new Action() {
@Override
public void run() {
downstream.resume();
}
}).subscribeOn(Schedulers.computation()).andThen(Completable.fromAction(new Action() {
@Override
public void run() {
downstream.pause();
}
}).subscribeOn(Schedulers.computation()));
}
}).blockingAwait();
ready = false;
executorService.execute(new Runnable() {
@Override
public void run() {
downstream.resume();
}
});
} | private static void racePauseResuming(final TestCallStreamObserver<?> downstream, int times) {
Observable.range(0, times).concatMapCompletable(new Function<Integer, CompletableSource>() {
@Override
public CompletableSource apply(Integer i) {
return Completable.fromAction(new Action() {
@Override
public void run() {
downstream.resume();
}
}).subscribeOn(Schedulers.computation()).andThen(Completable.fromAction(new Action() {
@Override
public void run() {
downstream.pause();
}
}).subscribeOn(Schedulers.computation()));
}
}).blockingAwait();
<DeepExtract>
ready = false;
</DeepExtract>
executorService.execute(new Runnable() {
@Override
public void run() {
downstream.resume();
}
});
} | reactive-grpc | positive | 1,989 |
public static SoMap getSoMap(String key, Object value) {
if (key.toLowerCase().equals("this")) {
return this;
}
put(key, value);
return this;
} | public static SoMap getSoMap(String key, Object value) {
<DeepExtract>
if (key.toLowerCase().equals("this")) {
return this;
}
put(key, value);
return this;
</DeepExtract>
} | sa-plus | positive | 1,990 |
public void setEmptyView(View paramView) {
this.mEmptyView = paramView;
Adapter localAdapter = getAdapter();
boolean bool = (localAdapter == null) || (localAdapter.isEmpty());
if (isInFilterMode())
bool = false;
if (bool) {
if (this.mEmptyView != null) {
this.mEmptyView.setVisibility(0);
setVisibility(8);
} else {
setVisibility(0);
}
if (this.mDataChanged) {
onLayout(false, getLeft(), getTop(), getRight(), getBottom());
}
} else {
if (this.mEmptyView != null)
this.mEmptyView.setVisibility(8);
setVisibility(0);
}
} | public void setEmptyView(View paramView) {
this.mEmptyView = paramView;
Adapter localAdapter = getAdapter();
boolean bool = (localAdapter == null) || (localAdapter.isEmpty());
<DeepExtract>
if (isInFilterMode())
bool = false;
if (bool) {
if (this.mEmptyView != null) {
this.mEmptyView.setVisibility(0);
setVisibility(8);
} else {
setVisibility(0);
}
if (this.mDataChanged) {
onLayout(false, getLeft(), getTop(), getRight(), getBottom());
}
} else {
if (this.mEmptyView != null)
this.mEmptyView.setVisibility(8);
setVisibility(0);
}
</DeepExtract>
} | android-tv-launcher | positive | 1,991 |
@GenerateMicroBenchmark
public void mediumTestGroovyJavaWithoutRecursion() {
groovyJavaSer2.serialize(MEDIUM_DATA);
} | @GenerateMicroBenchmark
public void mediumTestGroovyJavaWithoutRecursion() {
<DeepExtract>
groovyJavaSer2.serialize(MEDIUM_DATA);
</DeepExtract>
} | json-parsers-benchmark | positive | 1,992 |
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (drawable == null) {
mBitmap = null;
}
if (drawable instanceof BitmapDrawable) {
mBitmap = ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
mBitmap = bitmap;
} catch (OutOfMemoryError e) {
mBitmap = null;
}
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
} | @Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (drawable == null) {
mBitmap = null;
}
if (drawable instanceof BitmapDrawable) {
mBitmap = ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
mBitmap = bitmap;
} catch (OutOfMemoryError e) {
mBitmap = null;
}
<DeepExtract>
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
</DeepExtract>
} | QiQuYing | positive | 1,993 |
public static boolean isDroidiumContainer(ContainerDef containerDef) {
if (isContainerOfType(ContainerType.DROIDIUM, containerDef) || isContainerOfType(ContainerType.ANDROID, containerDef)) {
return true;
}
Map<String, String> properties = containerDef.getContainerProperties();
if (properties.containsKey("avdName") || properties.containsKey("serialId") || properties.containsKey("consolePort") || properties.containsKey("emulatorOptions")) {
return true;
}
return false;
} | public static boolean isDroidiumContainer(ContainerDef containerDef) {
if (isContainerOfType(ContainerType.DROIDIUM, containerDef) || isContainerOfType(ContainerType.ANDROID, containerDef)) {
return true;
}
<DeepExtract>
Map<String, String> properties = containerDef.getContainerProperties();
if (properties.containsKey("avdName") || properties.containsKey("serialId") || properties.containsKey("consolePort") || properties.containsKey("emulatorOptions")) {
return true;
}
return false;
</DeepExtract>
} | arquillian-droidium | positive | 1,994 |
protected String doInBackground(Marker... params) {
marker = params[0];
GeocoderNominatim geocoder = new GeocoderNominatim(userAgent);
String theAddress;
try {
double dLatitude = marker.getPosition().getLatitude();
double dLongitude = marker.getPosition().getLongitude();
List<Address> addresses = geocoder.getFromLocation(dLatitude, dLongitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int n = address.getMaxAddressLineIndex();
for (int i = 0; i <= n; i++) {
if (i != 0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
theAddress = sb.toString();
} else {
theAddress = null;
}
} catch (IOException e) {
theAddress = null;
}
if (theAddress != null) {
return theAddress;
} else {
return "";
}
} | protected String doInBackground(Marker... params) {
marker = params[0];
<DeepExtract>
GeocoderNominatim geocoder = new GeocoderNominatim(userAgent);
String theAddress;
try {
double dLatitude = marker.getPosition().getLatitude();
double dLongitude = marker.getPosition().getLongitude();
List<Address> addresses = geocoder.getFromLocation(dLatitude, dLongitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int n = address.getMaxAddressLineIndex();
for (int i = 0; i <= n; i++) {
if (i != 0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
theAddress = sb.toString();
} else {
theAddress = null;
}
} catch (IOException e) {
theAddress = null;
}
if (theAddress != null) {
return theAddress;
} else {
return "";
}
</DeepExtract>
} | osmbonuspack | positive | 1,995 |
public static void setTheme(ViewGroup root) {
AppStyles instance = new AppStyles(root.getContext());
root.setBackgroundColor(instance.settings.getBackgroundColor());
for (int pos = 0; pos < root.getChildCount(); pos++) {
View child = root.getChildAt(pos);
if (child instanceof SwitchButton) {
SwitchButton sw = (SwitchButton) child;
int[] color = { settings.getIconColor() };
sw.setTintColor(settings.getHighlightColor());
sw.setThumbColor(new ColorStateList(SWITCH_STATES, color));
} else if (child instanceof SeekBar) {
SeekBar seekBar = (SeekBar) child;
setSeekBarColor(seekBar, settings);
} else if (child instanceof Spinner) {
Spinner dropdown = (Spinner) child;
setDrawableColor(dropdown.getBackground(), settings.getIconColor());
} else if (child instanceof TextView) {
TextView tv = (TextView) child;
tv.setTypeface(settings.getTypeFace());
tv.setTextColor(settings.getTextColor());
setDrawableColor(tv, settings.getIconColor());
if (child instanceof Button) {
Button btn = (Button) child;
setButtonColor(btn, settings.getTextColor());
} else if (child instanceof EditText) {
EditText edit = (EditText) child;
edit.setHintTextColor(settings.getTextColor() & HINT_TRANSPARENCY);
}
} else if (child instanceof ImageView) {
ImageView img = (ImageView) child;
setDrawableColor(img.getDrawable(), settings.getIconColor());
if (child instanceof ImageButton) {
ImageButton btn = (ImageButton) child;
setButtonColor(btn, settings.getTextColor());
}
} else if (child instanceof ViewGroup) {
if (child instanceof CardView) {
CardView card = (CardView) child;
card.setCardBackgroundColor(settings.getCardColor());
setSubViewTheme(card);
} else if (!(child instanceof ViewPager2)) {
setSubViewTheme((ViewGroup) child);
}
}
}
} | public static void setTheme(ViewGroup root) {
AppStyles instance = new AppStyles(root.getContext());
root.setBackgroundColor(instance.settings.getBackgroundColor());
<DeepExtract>
for (int pos = 0; pos < root.getChildCount(); pos++) {
View child = root.getChildAt(pos);
if (child instanceof SwitchButton) {
SwitchButton sw = (SwitchButton) child;
int[] color = { settings.getIconColor() };
sw.setTintColor(settings.getHighlightColor());
sw.setThumbColor(new ColorStateList(SWITCH_STATES, color));
} else if (child instanceof SeekBar) {
SeekBar seekBar = (SeekBar) child;
setSeekBarColor(seekBar, settings);
} else if (child instanceof Spinner) {
Spinner dropdown = (Spinner) child;
setDrawableColor(dropdown.getBackground(), settings.getIconColor());
} else if (child instanceof TextView) {
TextView tv = (TextView) child;
tv.setTypeface(settings.getTypeFace());
tv.setTextColor(settings.getTextColor());
setDrawableColor(tv, settings.getIconColor());
if (child instanceof Button) {
Button btn = (Button) child;
setButtonColor(btn, settings.getTextColor());
} else if (child instanceof EditText) {
EditText edit = (EditText) child;
edit.setHintTextColor(settings.getTextColor() & HINT_TRANSPARENCY);
}
} else if (child instanceof ImageView) {
ImageView img = (ImageView) child;
setDrawableColor(img.getDrawable(), settings.getIconColor());
if (child instanceof ImageButton) {
ImageButton btn = (ImageButton) child;
setButtonColor(btn, settings.getTextColor());
}
} else if (child instanceof ViewGroup) {
if (child instanceof CardView) {
CardView card = (CardView) child;
card.setCardBackgroundColor(settings.getCardColor());
setSubViewTheme(card);
} else if (!(child instanceof ViewPager2)) {
setSubViewTheme((ViewGroup) child);
}
}
}
</DeepExtract>
} | Shitter | positive | 1,996 |
@Override
public void onCompleted(Response response) {
Request request = response.getRequest();
if (request != currentRequest) {
return;
}
loading = false;
currentRequest = null;
FacebookRequestError requestError = response.getError();
FacebookException exception = (requestError == null) ? null : requestError.getException();
if (response.getGraphObject() == null && exception == null) {
exception = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
}
if (exception != null) {
nextRequest = null;
if (onErrorListener != null) {
onErrorListener.onError(exception, this);
}
} else {
addResults(response);
}
} | @Override
public void onCompleted(Response response) {
<DeepExtract>
Request request = response.getRequest();
if (request != currentRequest) {
return;
}
loading = false;
currentRequest = null;
FacebookRequestError requestError = response.getError();
FacebookException exception = (requestError == null) ? null : requestError.getException();
if (response.getGraphObject() == null && exception == null) {
exception = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
}
if (exception != null) {
nextRequest = null;
if (onErrorListener != null) {
onErrorListener.onError(exception, this);
}
} else {
addResults(response);
}
</DeepExtract>
} | HypFacebook | positive | 1,997 |
@Override
public void onFailure(Call<ReviewResponse> call, Throwable t) {
mNotAvailableTextView.setVisibility(View.INVISIBLE);
mErrorMessageTextView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.INVISIBLE);
} | @Override
public void onFailure(Call<ReviewResponse> call, Throwable t) {
<DeepExtract>
mNotAvailableTextView.setVisibility(View.INVISIBLE);
mErrorMessageTextView.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.INVISIBLE);
</DeepExtract>
} | Cinematic | positive | 1,998 |
public static String getCurYear(String format) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.YEAR, 0);
return date2Str(calendar, format);
} | public static String getCurYear(String format) {
<DeepExtract>
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.YEAR, 0);
return date2Str(calendar, format);
</DeepExtract>
} | CocoBill | positive | 1,999 |
protected int getDefItemViewType(int position) {
if (mMultiTypeDelegate != null) {
return mMultiTypeDelegate.getDefItemViewType(mData, position);
}
if (getEmptyViewCount() == 1) {
boolean header = mHeadAndEmptyEnable && getHeaderLayoutCount() != 0;
switch(position) {
case 0:
if (header) {
return HEADER_VIEW;
} else {
return EMPTY_VIEW;
}
case 1:
if (header) {
return EMPTY_VIEW;
} else {
return FOOTER_VIEW;
}
case 2:
return FOOTER_VIEW;
default:
return EMPTY_VIEW;
}
}
int numHeaders = getHeaderLayoutCount();
if (position < numHeaders) {
return HEADER_VIEW;
} else {
int adjPosition = position - numHeaders;
int adapterCount = mData.size();
if (adjPosition < adapterCount) {
return getDefItemViewType(adjPosition);
} else {
adjPosition = adjPosition - adapterCount;
int numFooters = getFooterLayoutCount();
if (adjPosition < numFooters) {
return FOOTER_VIEW;
} else {
return LOADING_VIEW;
}
}
}
} | protected int getDefItemViewType(int position) {
if (mMultiTypeDelegate != null) {
return mMultiTypeDelegate.getDefItemViewType(mData, position);
}
<DeepExtract>
if (getEmptyViewCount() == 1) {
boolean header = mHeadAndEmptyEnable && getHeaderLayoutCount() != 0;
switch(position) {
case 0:
if (header) {
return HEADER_VIEW;
} else {
return EMPTY_VIEW;
}
case 1:
if (header) {
return EMPTY_VIEW;
} else {
return FOOTER_VIEW;
}
case 2:
return FOOTER_VIEW;
default:
return EMPTY_VIEW;
}
}
int numHeaders = getHeaderLayoutCount();
if (position < numHeaders) {
return HEADER_VIEW;
} else {
int adjPosition = position - numHeaders;
int adapterCount = mData.size();
if (adjPosition < adapterCount) {
return getDefItemViewType(adjPosition);
} else {
adjPosition = adjPosition - adapterCount;
int numFooters = getFooterLayoutCount();
if (adjPosition < numFooters) {
return FOOTER_VIEW;
} else {
return LOADING_VIEW;
}
}
}
</DeepExtract>
} | HeavenlyModule | positive | 2,000 |
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
Permutation[i] = i;
}
if (N == 0) {
print();
return;
}
generatePermutations(N - 1);
for (int i = 0; i < N - 1; i++) {
int swap = Permutation[i];
Permutation[i] = Permutation[N - 1];
Permutation[N - 1] = swap;
generatePermutations(N - 1);
swap = Permutation[i];
Permutation[i] = Permutation[N - 1];
Permutation[N - 1] = swap;
}
} | public static void main(String[] args) {
for (int i = 0; i < N; i++) {
Permutation[i] = i;
}
<DeepExtract>
if (N == 0) {
print();
return;
}
generatePermutations(N - 1);
for (int i = 0; i < N - 1; i++) {
int swap = Permutation[i];
Permutation[i] = Permutation[N - 1];
Permutation[N - 1] = swap;
generatePermutations(N - 1);
swap = Permutation[i];
Permutation[i] = Permutation[N - 1];
Permutation[N - 1] = swap;
}
</DeepExtract>
} | Java-Translation-Sources | positive | 2,001 |
@Test
public void isConnected_afterSuccessfulConnect_returnsTrue() throws IOException {
when(channelFuture.syncUninterruptibly()).thenReturn(channelFuture);
when(channelFuture.isSuccess()).thenReturn(true);
when(channelFuture.channel()).thenReturn(channel);
when(bootstrap.connect(address)).thenReturn(channelFuture);
communicationService.open(address);
callback.getValue().onConnected();
assertTrue(communicationService.isConnected());
} | @Test
public void isConnected_afterSuccessfulConnect_returnsTrue() throws IOException {
<DeepExtract>
when(channelFuture.syncUninterruptibly()).thenReturn(channelFuture);
when(channelFuture.isSuccess()).thenReturn(true);
when(channelFuture.channel()).thenReturn(channel);
when(bootstrap.connect(address)).thenReturn(channelFuture);
communicationService.open(address);
callback.getValue().onConnected();
</DeepExtract>
assertTrue(communicationService.isConnected());
} | waterrower-core | positive | 2,002 |
@Override
public void assertFalse(boolean value) {
assertTrue(!value, "");
} | @Override
public void assertFalse(boolean value) {
<DeepExtract>
assertTrue(!value, "");
</DeepExtract>
} | parse4cn1 | positive | 2,003 |
private void updateAnimation(float factor) {
float initial = mAnimationInitialValue;
float destination = mReverse ? 0f : 1f;
mCurrentScale = initial + (destination - initial) * factor;
final float currentScale = mCurrentScale;
final Path path = mPath;
final RectF rect = mRect;
final Matrix matrix = mMatrix;
path.reset();
int totalSize = Math.min(getBounds().width(), getBounds().height());
float initial = mClosedStateSize;
float destination = totalSize;
float currentSize = initial + (destination - initial) * currentScale;
float halfSize = currentSize / 2f;
float inverseScale = 1f - currentScale;
float cornerSize = halfSize * inverseScale;
float[] corners = new float[] { halfSize, halfSize, halfSize, halfSize, halfSize, halfSize, cornerSize, cornerSize };
rect.set(getBounds().left, getBounds().top, getBounds().left + currentSize, getBounds().top + currentSize);
path.addRoundRect(rect, corners, Path.Direction.CCW);
matrix.reset();
matrix.postRotate(-45, getBounds().left + halfSize, getBounds().top + halfSize);
matrix.postTranslate((getBounds().width() - currentSize) / 2, 0);
float hDiff = (getBounds().bottom - currentSize - mExternalOffset) * inverseScale;
matrix.postTranslate(0, hDiff);
path.transform(matrix);
invalidateSelf();
} | private void updateAnimation(float factor) {
float initial = mAnimationInitialValue;
float destination = mReverse ? 0f : 1f;
mCurrentScale = initial + (destination - initial) * factor;
<DeepExtract>
final float currentScale = mCurrentScale;
final Path path = mPath;
final RectF rect = mRect;
final Matrix matrix = mMatrix;
path.reset();
int totalSize = Math.min(getBounds().width(), getBounds().height());
float initial = mClosedStateSize;
float destination = totalSize;
float currentSize = initial + (destination - initial) * currentScale;
float halfSize = currentSize / 2f;
float inverseScale = 1f - currentScale;
float cornerSize = halfSize * inverseScale;
float[] corners = new float[] { halfSize, halfSize, halfSize, halfSize, halfSize, halfSize, cornerSize, cornerSize };
rect.set(getBounds().left, getBounds().top, getBounds().left + currentSize, getBounds().top + currentSize);
path.addRoundRect(rect, corners, Path.Direction.CCW);
matrix.reset();
matrix.postRotate(-45, getBounds().left + halfSize, getBounds().top + halfSize);
matrix.postTranslate((getBounds().width() - currentSize) / 2, 0);
float hDiff = (getBounds().bottom - currentSize - mExternalOffset) * inverseScale;
matrix.postTranslate(0, hDiff);
path.transform(matrix);
</DeepExtract>
invalidateSelf();
} | FaceUnityLegacy | positive | 2,004 |
@Override
public void apply(@Nonnull MockServerBuilder serverBuilder, @Nonnull AtomicInteger cnt) {
return withAddress("43.43.43." + cnt.incrementAndGet(), 4, "fixed");
} | @Override
public void apply(@Nonnull MockServerBuilder serverBuilder, @Nonnull AtomicInteger cnt) {
<DeepExtract>
return withAddress("43.43.43." + cnt.incrementAndGet(), 4, "fixed");
</DeepExtract>
} | openstack-cloud-plugin | positive | 2,005 |
public Criteria andUserEmailBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "userEmail" + " cannot be null");
}
criteria.add(new Criterion("USER_EMAIL between", value1, value2));
return (Criteria) this;
} | public Criteria andUserEmailBetween(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "userEmail" + " cannot be null");
}
criteria.add(new Criterion("USER_EMAIL between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | console | positive | 2,006 |
private byte[] serializeStratioStreamingMessage(StratioStreamingMessage message) {
List<com.stratio.decision.commons.avro.ColumnType> columns = null;
if (message.getColumns() != null) {
columns = new java.util.ArrayList<>();
ColumnType c = null;
for (ColumnNameTypeValue messageColumn : message.getColumns()) {
c = new ColumnType(messageColumn.getColumn(), messageColumn.getValue().toString(), messageColumn.getValue().getClass().getName());
columns.add(c);
}
}
InsertMessage insertMessage = new InsertMessage(message.getOperation(), message.getStreamName(), message.getSession_id(), message.getTimestamp(), columns, null);
byte[] result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
SpecificDatumWriter writer = new SpecificDatumWriter<InsertMessage>(InsertMessage.getClassSchema());
try {
writer.write(insertMessage, encoder);
encoder.flush();
out.close();
result = out.toByteArray();
} catch (IOException e) {
return null;
}
return result;
} | private byte[] serializeStratioStreamingMessage(StratioStreamingMessage message) {
List<com.stratio.decision.commons.avro.ColumnType> columns = null;
if (message.getColumns() != null) {
columns = new java.util.ArrayList<>();
ColumnType c = null;
for (ColumnNameTypeValue messageColumn : message.getColumns()) {
c = new ColumnType(messageColumn.getColumn(), messageColumn.getValue().toString(), messageColumn.getValue().getClass().getName());
columns.add(c);
}
}
InsertMessage insertMessage = new InsertMessage(message.getOperation(), message.getStreamName(), message.getSession_id(), message.getTimestamp(), columns, null);
<DeepExtract>
byte[] result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
SpecificDatumWriter writer = new SpecificDatumWriter<InsertMessage>(InsertMessage.getClassSchema());
try {
writer.write(insertMessage, encoder);
encoder.flush();
out.close();
result = out.toByteArray();
} catch (IOException e) {
return null;
}
return result;
</DeepExtract>
} | Decision | positive | 2,007 |
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (!(obj instanceof TableKey))
return false;
final TableKey<?> that = (TableKey<?>) obj;
assert that != null;
return Objects.equals(pktableCatNonNull(), that.pktableCatNonNull()) && Objects.equals(pktableSchemNonNull(), that.pktableSchemNonNull()) && Objects.equals(pktableName, that.pktableName) && Objects.equals(pkcolumnName, that.pkcolumnName) && Objects.equals(fktableCatNonNull(), that.fktableCatNonNull()) && Objects.equals(fktableSchemNonNull(), that.fktableSchemNonNull()) && Objects.equals(fktableName, that.fktableName) && Objects.equals(fkcolumnName, that.fkcolumnName);
} | @Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (!(obj instanceof TableKey))
return false;
final TableKey<?> that = (TableKey<?>) obj;
<DeepExtract>
assert that != null;
return Objects.equals(pktableCatNonNull(), that.pktableCatNonNull()) && Objects.equals(pktableSchemNonNull(), that.pktableSchemNonNull()) && Objects.equals(pktableName, that.pktableName) && Objects.equals(pkcolumnName, that.pkcolumnName) && Objects.equals(fktableCatNonNull(), that.fktableCatNonNull()) && Objects.equals(fktableSchemNonNull(), that.fktableSchemNonNull()) && Objects.equals(fktableName, that.fktableName) && Objects.equals(fkcolumnName, that.fkcolumnName);
</DeepExtract>
} | database-metadata-bind | positive | 2,009 |
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equalizer, container, false);
Wave mWave = (Wave) (ViewGroup) view.findViewById(R.id.waveEqualizer);
mWave.setAboveWaveColor(0xffffffff);
mWave.setBlowWaveColor(0xffffffff);
mWave.initializePainters();
mWave.setFxValues(activity.getService().getFXBandValues());
mWave.setUpdateListener(this);
return view;
} | @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equalizer, container, false);
<DeepExtract>
Wave mWave = (Wave) (ViewGroup) view.findViewById(R.id.waveEqualizer);
mWave.setAboveWaveColor(0xffffffff);
mWave.setBlowWaveColor(0xffffffff);
mWave.initializePainters();
mWave.setFxValues(activity.getService().getFXBandValues());
mWave.setUpdateListener(this);
</DeepExtract>
return view;
} | IdealMedia | positive | 2,010 |
@Test
public void test2CC() throws ContradictionException {
GraphModel m = new GraphModel();
int nb = 6;
UndirectedGraph GLB = new UndirectedGraph(m, nb, SetType.BITSET, false);
UndirectedGraph GUB = new UndirectedGraph(m, nb, SetType.BITSET, false);
for (int i : new int[] { 0, 3 }) GLB.addNode(i);
for (int i : new int[] { 0, 1, 2, 3, 4, 5 }) GUB.addNode(i);
for (int y : 3) GUB.addEdge(0, y);
add_neighbors(GUB, 1, 2, 3);
for (int y : 3) GUB.addEdge(2, y);
for (int y : 5) GUB.addEdge(4, y);
UndirectedGraphVar graph = m.graphVar("G", GLB, GUB);
m.nbConnectedComponents(graph, m.intVar(1)).post();
m.getSolver().propagate();
System.out.println(graph.graphVizExport());
Assert.assertTrue(graph.getMandSuccOrNeighOf(0).contains(3));
Assert.assertTrue(graph.getMandatoryNodes().size() == 2);
Assert.assertTrue(!graph.getPotentialNodes().contains(4));
Assert.assertTrue(!graph.getPotentialNodes().contains(5));
Assert.assertTrue(m.getSolver().solve());
} | @Test
public void test2CC() throws ContradictionException {
GraphModel m = new GraphModel();
int nb = 6;
UndirectedGraph GLB = new UndirectedGraph(m, nb, SetType.BITSET, false);
UndirectedGraph GUB = new UndirectedGraph(m, nb, SetType.BITSET, false);
for (int i : new int[] { 0, 3 }) GLB.addNode(i);
for (int i : new int[] { 0, 1, 2, 3, 4, 5 }) GUB.addNode(i);
for (int y : 3) GUB.addEdge(0, y);
add_neighbors(GUB, 1, 2, 3);
for (int y : 3) GUB.addEdge(2, y);
<DeepExtract>
for (int y : 5) GUB.addEdge(4, y);
</DeepExtract>
UndirectedGraphVar graph = m.graphVar("G", GLB, GUB);
m.nbConnectedComponents(graph, m.intVar(1)).post();
m.getSolver().propagate();
System.out.println(graph.graphVizExport());
Assert.assertTrue(graph.getMandSuccOrNeighOf(0).contains(3));
Assert.assertTrue(graph.getMandatoryNodes().size() == 2);
Assert.assertTrue(!graph.getPotentialNodes().contains(4));
Assert.assertTrue(!graph.getPotentialNodes().contains(5));
Assert.assertTrue(m.getSolver().solve());
} | choco-graph | positive | 2,012 |
public Criteria andSendtimeIsNull() {
if ("sendTime is null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("sendTime is null"));
return (Criteria) this;
} | public Criteria andSendtimeIsNull() {
<DeepExtract>
if ("sendTime is null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("sendTime is null"));
</DeepExtract>
return (Criteria) this;
} | webim | positive | 2,013 |
public Criteria andPhoneNotBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "phone" + " cannot be null");
}
criteria.add(new Criterion("phone not between", value1, value2));
return (Criteria) this;
} | public Criteria andPhoneNotBetween(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "phone" + " cannot be null");
}
criteria.add(new Criterion("phone not between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | health_online | positive | 2,014 |
public static void assertUpdate(SourceRecord record, String idValue) {
assertUpdate(record);
String actualOid = ((Struct) record.value()).getString("documentKey");
assertEquals(idValue, JsonPath.read(actualOid, "$._id.$oid"));
} | public static void assertUpdate(SourceRecord record, String idValue) {
assertUpdate(record);
<DeepExtract>
String actualOid = ((Struct) record.value()).getString("documentKey");
assertEquals(idValue, JsonPath.read(actualOid, "$._id.$oid"));
</DeepExtract>
} | flink-cdc-connectors | positive | 2,015 |
@Override
public org.w3c.dom.Node getNode(Object obj) throws JAXBException {
if (obj == null) {
throw new IllegalArgumentException(Messages.format(Messages.MUST_NOT_BE_NULL, "obj"));
}
if (Boolean.TRUE == null) {
throw new IllegalArgumentException(Messages.format(Messages.MUST_NOT_BE_NULL, "foo"));
}
throw new UnsupportedOperationException();
} | @Override
public org.w3c.dom.Node getNode(Object obj) throws JAXBException {
<DeepExtract>
if (obj == null) {
throw new IllegalArgumentException(Messages.format(Messages.MUST_NOT_BE_NULL, "obj"));
}
if (Boolean.TRUE == null) {
throw new IllegalArgumentException(Messages.format(Messages.MUST_NOT_BE_NULL, "foo"));
}
</DeepExtract>
throw new UnsupportedOperationException();
} | jaxb-api | positive | 2,017 |
private void workEvent(String line) {
logger.debug("Line for project evaluation{},line");
String project;
int indexOf = line.indexOf(PROJECT);
if (indexOf >= 0) {
indexOf += PROJECT.length();
indexOf = line.indexOf(':', indexOf);
indexOf = line.indexOf('"', indexOf);
indexOf++;
int nextSeparator = line.indexOf('/', indexOf);
int nextQuote = line.indexOf('"', indexOf);
if (nextSeparator > 0 && nextSeparator < nextQuote) {
project = line.substring(indexOf, nextSeparator);
}
project = line.substring(indexOf, nextQuote);
} else {
project = "";
}
logger.debug("Project before filter: {}", project);
if (isValidProject(project)) {
work.perform(coordinator);
} else {
logger.debug("Ignoring event from: {}", project);
}
} | private void workEvent(String line) {
logger.debug("Line for project evaluation{},line");
<DeepExtract>
String project;
int indexOf = line.indexOf(PROJECT);
if (indexOf >= 0) {
indexOf += PROJECT.length();
indexOf = line.indexOf(':', indexOf);
indexOf = line.indexOf('"', indexOf);
indexOf++;
int nextSeparator = line.indexOf('/', indexOf);
int nextQuote = line.indexOf('"', indexOf);
if (nextSeparator > 0 && nextSeparator < nextQuote) {
project = line.substring(indexOf, nextSeparator);
}
project = line.substring(indexOf, nextQuote);
} else {
project = "";
}
</DeepExtract>
logger.debug("Project before filter: {}", project);
if (isValidProject(project)) {
work.perform(coordinator);
} else {
logger.debug("Ignoring event from: {}", project);
}
} | gerrit-events | positive | 2,018 |
@Test
public void getMode_throwsIfClosed() throws IOException {
Mma7660Fc driver = new Mma7660Fc(mI2c);
Mma7660Fc driver = new Mma7660Fc(mI2c);
driver.close();
Mockito.verify(mI2c).close();
mExpectedException.expect(IllegalStateException.class);
Mma7660Fc driver = new Mma7660Fc(mI2c);
driver.getMode();
Mockito.verify(mI2c).readRegByte(0x07);
} | @Test
public void getMode_throwsIfClosed() throws IOException {
Mma7660Fc driver = new Mma7660Fc(mI2c);
Mma7660Fc driver = new Mma7660Fc(mI2c);
driver.close();
Mockito.verify(mI2c).close();
mExpectedException.expect(IllegalStateException.class);
<DeepExtract>
Mma7660Fc driver = new Mma7660Fc(mI2c);
driver.getMode();
Mockito.verify(mI2c).readRegByte(0x07);
</DeepExtract>
} | contrib-drivers | positive | 2,020 |
public void startTimer(int interval, String name) {
name = name.intern();
if (timers.containsKey(name)) {
System.out.println("already has timer " + name);
return;
}
Timer t = new Timer(interval, this);
t.start();
timers.put(name, t);
if (t instanceof JComponent) {
((JComponent) t).putClientProperty("name", name);
} else if (t instanceof Document) {
((Document) t).putProperty("name", name);
} else if (t instanceof Component) {
((Component) t).setName(name);
} else {
names.put(t, name);
}
} | public void startTimer(int interval, String name) {
name = name.intern();
if (timers.containsKey(name)) {
System.out.println("already has timer " + name);
return;
}
Timer t = new Timer(interval, this);
t.start();
timers.put(name, t);
<DeepExtract>
if (t instanceof JComponent) {
((JComponent) t).putClientProperty("name", name);
} else if (t instanceof Document) {
((Document) t).putProperty("name", name);
} else if (t instanceof Component) {
((Component) t).setName(name);
} else {
names.put(t, name);
}
</DeepExtract>
} | CaroOnline_SocketJava | positive | 2,021 |
protected void printFreeAttributesHeaderDecl(String cppName) {
privateImplHeaderFile.print("bool");
privateImplHeaderFile.print(" ");
privateImplHeaderFile.print(Util.createFreeAttributesMethodName(cppName));
privateImplHeaderFile.print("( void* " + config.getAttributeDataParameterName() + " )");
privateImplHeaderFile.println(";");
} | protected void printFreeAttributesHeaderDecl(String cppName) {
privateImplHeaderFile.print("bool");
privateImplHeaderFile.print(" ");
privateImplHeaderFile.print(Util.createFreeAttributesMethodName(cppName));
<DeepExtract>
privateImplHeaderFile.print("( void* " + config.getAttributeDataParameterName() + " )");
</DeepExtract>
privateImplHeaderFile.println(";");
} | OpenCOLLADA | positive | 2,022 |
public Nar askNow(final String termString, final AnswerHandler answered) throws Parser.InvalidInputException {
final Sentence sentenceForNewTask = new Sentence(new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Present));
final BudgetValue budgetForNewTask = new BudgetValue(narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters);
final Task t = new Task(sentenceForNewTask, budgetForNewTask, Task.EnumType.INPUT);
this.memory.inputTask(this, t);
return this;
if (answered != null) {
answered.start(t, this);
}
return this;
} | public Nar askNow(final String termString, final AnswerHandler answered) throws Parser.InvalidInputException {
final Sentence sentenceForNewTask = new Sentence(new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Present));
final BudgetValue budgetForNewTask = new BudgetValue(narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters);
final Task t = new Task(sentenceForNewTask, budgetForNewTask, Task.EnumType.INPUT);
<DeepExtract>
this.memory.inputTask(this, t);
return this;
</DeepExtract>
if (answered != null) {
answered.start(t, this);
}
return this;
} | opennars | positive | 2,024 |
public static String docTitle(String docTitle) {
if (docTitle == null || "".equals(docTitle.toString().trim())) {
return "";
}
StringBuilder adocAttr = new StringBuilder();
adocAttr.append(":");
if (Boolean.class.isAssignableFrom(docTitle.getClass())) {
boolean bool = Boolean.parseBoolean(docTitle.toString());
if (!bool) {
adocAttr.append("!");
}
adocAttr.append(DOCTITLE.name).append(":");
} else {
adocAttr.append(DOCTITLE.name).append(":").append(" ").append(docTitle);
}
return adocAttr.toString();
} | public static String docTitle(String docTitle) {
<DeepExtract>
if (docTitle == null || "".equals(docTitle.toString().trim())) {
return "";
}
StringBuilder adocAttr = new StringBuilder();
adocAttr.append(":");
if (Boolean.class.isAssignableFrom(docTitle.getClass())) {
boolean bool = Boolean.parseBoolean(docTitle.toString());
if (!bool) {
adocAttr.append("!");
}
adocAttr.append(DOCTITLE.name).append(":");
} else {
adocAttr.append(DOCTITLE.name).append(":").append(" ").append(docTitle);
}
return adocAttr.toString();
</DeepExtract>
} | cukedoctor | positive | 2,025 |
public static void setupVertex(RenderBlocks renderBlocks, double x, double y, double z, double u, double v, int vertex) {
Tessellator tessellator = Tessellator.instance;
if (renderBlocks != null && renderBlocks.enableAO) {
switch(vertex) {
case BOTTOM_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedBottomLeft + renderBlocks.colorRedBottomRight) / 2.0F, (renderBlocks.colorGreenBottomLeft + renderBlocks.colorGreenBottomRight) / 2.0F, (renderBlocks.colorBlueBottomLeft + renderBlocks.colorBlueBottomRight) / 2.0F);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessBottomLeft, renderBlocks.brightnessBottomRight));
break;
case TOP_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopLeft + renderBlocks.colorRedTopRight) / 2.0F, (renderBlocks.colorGreenTopLeft + renderBlocks.colorGreenTopRight) / 2.0F, (renderBlocks.colorBlueTopLeft + renderBlocks.colorBlueTopRight) / 2);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopLeft, renderBlocks.brightnessTopRight));
break;
case LEFT_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopLeft + renderBlocks.colorRedBottomLeft) / 2.0F, (renderBlocks.colorGreenTopLeft + renderBlocks.colorGreenBottomLeft) / 2.0F, (renderBlocks.colorBlueTopLeft + renderBlocks.colorBlueBottomLeft) / 2.0F);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopLeft, renderBlocks.brightnessBottomLeft));
break;
case RIGHT_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopRight + renderBlocks.colorRedBottomRight) / 2.0F, (renderBlocks.colorGreenTopRight + renderBlocks.colorGreenBottomRight) / 2.0F, (renderBlocks.colorBlueTopRight + renderBlocks.colorBlueBottomRight) / 2);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopRight, renderBlocks.brightnessBottomRight));
break;
case TOP_LEFT:
tessellator.setColorOpaque_F(renderBlocks.colorRedTopLeft, renderBlocks.colorGreenTopLeft, renderBlocks.colorBlueTopLeft);
tessellator.setBrightness(renderBlocks.brightnessTopLeft);
break;
case BOTTOM_LEFT:
tessellator.setColorOpaque_F(renderBlocks.colorRedBottomLeft, renderBlocks.colorGreenBottomLeft, renderBlocks.colorBlueBottomLeft);
tessellator.setBrightness(renderBlocks.brightnessBottomLeft);
break;
case BOTTOM_RIGHT:
tessellator.setColorOpaque_F(renderBlocks.colorRedBottomRight, renderBlocks.colorGreenBottomRight, renderBlocks.colorBlueBottomRight);
tessellator.setBrightness(renderBlocks.brightnessBottomRight);
break;
case TOP_RIGHT:
tessellator.setColorOpaque_F(renderBlocks.colorRedTopRight, renderBlocks.colorGreenTopRight, renderBlocks.colorBlueTopRight);
tessellator.setBrightness(renderBlocks.brightnessTopRight);
break;
}
}
Tessellator.instance.addVertexWithUV(x, y, z, u, v);
++vertexCount;
if (drawMode == GL11.GL_TRIANGLES) {
if (++triVertexCount > 2) {
drawVertex(renderBlocks, x, y, z, u, v);
triVertexCount = 0;
}
}
} | public static void setupVertex(RenderBlocks renderBlocks, double x, double y, double z, double u, double v, int vertex) {
Tessellator tessellator = Tessellator.instance;
if (renderBlocks != null && renderBlocks.enableAO) {
switch(vertex) {
case BOTTOM_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedBottomLeft + renderBlocks.colorRedBottomRight) / 2.0F, (renderBlocks.colorGreenBottomLeft + renderBlocks.colorGreenBottomRight) / 2.0F, (renderBlocks.colorBlueBottomLeft + renderBlocks.colorBlueBottomRight) / 2.0F);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessBottomLeft, renderBlocks.brightnessBottomRight));
break;
case TOP_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopLeft + renderBlocks.colorRedTopRight) / 2.0F, (renderBlocks.colorGreenTopLeft + renderBlocks.colorGreenTopRight) / 2.0F, (renderBlocks.colorBlueTopLeft + renderBlocks.colorBlueTopRight) / 2);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopLeft, renderBlocks.brightnessTopRight));
break;
case LEFT_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopLeft + renderBlocks.colorRedBottomLeft) / 2.0F, (renderBlocks.colorGreenTopLeft + renderBlocks.colorGreenBottomLeft) / 2.0F, (renderBlocks.colorBlueTopLeft + renderBlocks.colorBlueBottomLeft) / 2.0F);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopLeft, renderBlocks.brightnessBottomLeft));
break;
case RIGHT_CENTER:
tessellator.setColorOpaque_F((renderBlocks.colorRedTopRight + renderBlocks.colorRedBottomRight) / 2.0F, (renderBlocks.colorGreenTopRight + renderBlocks.colorGreenBottomRight) / 2.0F, (renderBlocks.colorBlueTopRight + renderBlocks.colorBlueBottomRight) / 2);
tessellator.setBrightness(LightingHelper.getAverageBrightness(renderBlocks.brightnessTopRight, renderBlocks.brightnessBottomRight));
break;
case TOP_LEFT:
tessellator.setColorOpaque_F(renderBlocks.colorRedTopLeft, renderBlocks.colorGreenTopLeft, renderBlocks.colorBlueTopLeft);
tessellator.setBrightness(renderBlocks.brightnessTopLeft);
break;
case BOTTOM_LEFT:
tessellator.setColorOpaque_F(renderBlocks.colorRedBottomLeft, renderBlocks.colorGreenBottomLeft, renderBlocks.colorBlueBottomLeft);
tessellator.setBrightness(renderBlocks.brightnessBottomLeft);
break;
case BOTTOM_RIGHT:
tessellator.setColorOpaque_F(renderBlocks.colorRedBottomRight, renderBlocks.colorGreenBottomRight, renderBlocks.colorBlueBottomRight);
tessellator.setBrightness(renderBlocks.brightnessBottomRight);
break;
case TOP_RIGHT:
tessellator.setColorOpaque_F(renderBlocks.colorRedTopRight, renderBlocks.colorGreenTopRight, renderBlocks.colorBlueTopRight);
tessellator.setBrightness(renderBlocks.brightnessTopRight);
break;
}
}
<DeepExtract>
Tessellator.instance.addVertexWithUV(x, y, z, u, v);
++vertexCount;
</DeepExtract>
if (drawMode == GL11.GL_TRIANGLES) {
if (++triVertexCount > 2) {
drawVertex(renderBlocks, x, y, z, u, v);
triVertexCount = 0;
}
}
} | carpentersblocks | positive | 2,027 |
public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) {
beginShape(POLYGON);
vertexCheck();
float[] vertex = vertices[vertexCount];
if (shapeMode == POLYGON) {
if (vertexCount > 0) {
float[] pvertex = vertices[vertexCount - 1];
if ((Math.abs(pvertex[X] - x1) < RainbowMath.EPSILON) && (Math.abs(pvertex[Y] - y1) < RainbowMath.EPSILON) && (Math.abs(pvertex[Z] - z1) < RainbowMath.EPSILON)) {
return;
}
}
}
curveVertexCount = 0;
vertex[X] = x1;
vertex[Y] = y1;
vertex[Z] = z1;
vertex[EDGE] = edge ? 1 : 0;
boolean textured = textureImage != null;
if (fill || textured) {
if (!textured) {
vertex[R] = fillR;
vertex[G] = fillG;
vertex[B] = fillB;
vertex[A] = fillA;
} else {
if (tint) {
vertex[R] = tintR;
vertex[G] = tintG;
vertex[B] = tintB;
vertex[A] = tintA;
} else {
vertex[R] = 1;
vertex[G] = 1;
vertex[B] = 1;
vertex[A] = 1;
}
}
}
if (stroke) {
vertex[SR] = strokeR;
vertex[SG] = strokeG;
vertex[SB] = strokeB;
vertex[SA] = strokeA;
vertex[SW] = strokeWeight;
}
vertex[U] = textureU;
vertex[V] = textureV;
if (autoNormal) {
float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
if (norm2 < RainbowMath.EPSILON) {
vertex[HAS_NORMAL] = 0;
} else {
if (Math.abs(norm2 - 1) > RainbowMath.EPSILON) {
float norm = RainbowMath.sqrt(norm2);
normalX /= norm;
normalY /= norm;
normalZ /= norm;
}
vertex[HAS_NORMAL] = 1;
}
} else {
vertex[HAS_NORMAL] = 1;
}
vertex[NX] = normalX;
vertex[NY] = normalY;
vertex[NZ] = normalZ;
vertexCount++;
bezierInitCheck();
bezierVertexCheck();
RMatrix3D draw = bezierDrawMatrix;
float[] prev = vertices[vertexCount - 1];
float x1 = prev[X];
float y1 = prev[Y];
float z1 = prev[Z];
float xplot1 = draw.m10 * x1 + draw.m11 * x2 + draw.m12 * x3 + draw.m13 * x4;
float xplot2 = draw.m20 * x1 + draw.m21 * x2 + draw.m22 * x3 + draw.m23 * x4;
float xplot3 = draw.m30 * x1 + draw.m31 * x2 + draw.m32 * x3 + draw.m33 * x4;
float yplot1 = draw.m10 * y1 + draw.m11 * y2 + draw.m12 * y3 + draw.m13 * y4;
float yplot2 = draw.m20 * y1 + draw.m21 * y2 + draw.m22 * y3 + draw.m23 * y4;
float yplot3 = draw.m30 * y1 + draw.m31 * y2 + draw.m32 * y3 + draw.m33 * y4;
float zplot1 = draw.m10 * z1 + draw.m11 * z2 + draw.m12 * z3 + draw.m13 * z4;
float zplot2 = draw.m20 * z1 + draw.m21 * z2 + draw.m22 * z3 + draw.m23 * z4;
float zplot3 = draw.m30 * z1 + draw.m31 * z2 + draw.m32 * z3 + draw.m33 * z4;
for (int j = 0; j < bezierDetail; j++) {
x1 += xplot1;
xplot1 += xplot2;
xplot2 += xplot3;
y1 += yplot1;
yplot1 += yplot2;
yplot2 += yplot3;
z1 += zplot1;
zplot1 += zplot2;
zplot2 += zplot3;
vertex(x1, y1, z1);
}
endShape(OPEN);
} | public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) {
beginShape(POLYGON);
vertexCheck();
float[] vertex = vertices[vertexCount];
if (shapeMode == POLYGON) {
if (vertexCount > 0) {
float[] pvertex = vertices[vertexCount - 1];
if ((Math.abs(pvertex[X] - x1) < RainbowMath.EPSILON) && (Math.abs(pvertex[Y] - y1) < RainbowMath.EPSILON) && (Math.abs(pvertex[Z] - z1) < RainbowMath.EPSILON)) {
return;
}
}
}
curveVertexCount = 0;
vertex[X] = x1;
vertex[Y] = y1;
vertex[Z] = z1;
vertex[EDGE] = edge ? 1 : 0;
boolean textured = textureImage != null;
if (fill || textured) {
if (!textured) {
vertex[R] = fillR;
vertex[G] = fillG;
vertex[B] = fillB;
vertex[A] = fillA;
} else {
if (tint) {
vertex[R] = tintR;
vertex[G] = tintG;
vertex[B] = tintB;
vertex[A] = tintA;
} else {
vertex[R] = 1;
vertex[G] = 1;
vertex[B] = 1;
vertex[A] = 1;
}
}
}
if (stroke) {
vertex[SR] = strokeR;
vertex[SG] = strokeG;
vertex[SB] = strokeB;
vertex[SA] = strokeA;
vertex[SW] = strokeWeight;
}
vertex[U] = textureU;
vertex[V] = textureV;
if (autoNormal) {
float norm2 = normalX * normalX + normalY * normalY + normalZ * normalZ;
if (norm2 < RainbowMath.EPSILON) {
vertex[HAS_NORMAL] = 0;
} else {
if (Math.abs(norm2 - 1) > RainbowMath.EPSILON) {
float norm = RainbowMath.sqrt(norm2);
normalX /= norm;
normalY /= norm;
normalZ /= norm;
}
vertex[HAS_NORMAL] = 1;
}
} else {
vertex[HAS_NORMAL] = 1;
}
vertex[NX] = normalX;
vertex[NY] = normalY;
vertex[NZ] = normalZ;
vertexCount++;
bezierInitCheck();
bezierVertexCheck();
RMatrix3D draw = bezierDrawMatrix;
float[] prev = vertices[vertexCount - 1];
float x1 = prev[X];
float y1 = prev[Y];
float z1 = prev[Z];
float xplot1 = draw.m10 * x1 + draw.m11 * x2 + draw.m12 * x3 + draw.m13 * x4;
float xplot2 = draw.m20 * x1 + draw.m21 * x2 + draw.m22 * x3 + draw.m23 * x4;
float xplot3 = draw.m30 * x1 + draw.m31 * x2 + draw.m32 * x3 + draw.m33 * x4;
float yplot1 = draw.m10 * y1 + draw.m11 * y2 + draw.m12 * y3 + draw.m13 * y4;
float yplot2 = draw.m20 * y1 + draw.m21 * y2 + draw.m22 * y3 + draw.m23 * y4;
float yplot3 = draw.m30 * y1 + draw.m31 * y2 + draw.m32 * y3 + draw.m33 * y4;
float zplot1 = draw.m10 * z1 + draw.m11 * z2 + draw.m12 * z3 + draw.m13 * z4;
float zplot2 = draw.m20 * z1 + draw.m21 * z2 + draw.m22 * z3 + draw.m23 * z4;
float zplot3 = draw.m30 * z1 + draw.m31 * z2 + draw.m32 * z3 + draw.m33 * z4;
for (int j = 0; j < bezierDetail; j++) {
x1 += xplot1;
xplot1 += xplot2;
xplot2 += xplot3;
y1 += yplot1;
yplot1 += yplot2;
yplot2 += yplot3;
z1 += zplot1;
zplot1 += zplot2;
zplot2 += zplot3;
vertex(x1, y1, z1);
}
<DeepExtract>
endShape(OPEN);
</DeepExtract>
} | rainbow | positive | 2,028 |
public double[] getArray() {
double[] weights = new double[inputs.length * hiddenNeurons.length + hiddenNeurons.length * outputs.length];
int k = 0;
for (int i = 0; i < inputs.length; i++) {
for (int j = 0; j < hiddenNeurons.length; j++) {
weights[k] = firstConnectionLayer[i][j];
k++;
}
}
for (int i = 0; i < hiddenNeurons.length; i++) {
for (int j = 0; j < outputs.length; j++) {
weights[k] = secondConnectionLayer[i][j];
k++;
}
}
return weights;
} | public double[] getArray() {
<DeepExtract>
double[] weights = new double[inputs.length * hiddenNeurons.length + hiddenNeurons.length * outputs.length];
int k = 0;
for (int i = 0; i < inputs.length; i++) {
for (int j = 0; j < hiddenNeurons.length; j++) {
weights[k] = firstConnectionLayer[i][j];
k++;
}
}
for (int i = 0; i < hiddenNeurons.length; i++) {
for (int j = 0; j < outputs.length; j++) {
weights[k] = secondConnectionLayer[i][j];
k++;
}
}
return weights;
</DeepExtract>
} | MCTSMario | positive | 2,029 |
@Override
public Integer component3() {
return (Integer) get(2);
} | @Override
public Integer component3() {
<DeepExtract>
return (Integer) get(2);
</DeepExtract>
} | openvsx | positive | 2,030 |
private void setUpSendButton() {
sendSMS = (ImageButton) this.findViewById(R.id.new_message_send);
if (currentActivity == ConversationView.MESSAGE_VIEW) {
if (message == null || message.length() == 0) {
Number number = dba.getNumber(selectedNumber);
message = number.getDraft();
}
EditText et = (EditText) findViewById(R.id.new_message_message);
if (et.getText() != null && (et.getText().toString() == null || et.getText().toString().length() <= 0)) {
et.setText(message);
}
}
if (message == null || message.length() == 0) {
sendSMS.setEnabled(false);
sendSMS.setClickable(false);
}
} | private void setUpSendButton() {
sendSMS = (ImageButton) this.findViewById(R.id.new_message_send);
<DeepExtract>
if (currentActivity == ConversationView.MESSAGE_VIEW) {
if (message == null || message.length() == 0) {
Number number = dba.getNumber(selectedNumber);
message = number.getDraft();
}
EditText et = (EditText) findViewById(R.id.new_message_message);
if (et.getText() != null && (et.getText().toString() == null || et.getText().toString().length() <= 0)) {
et.setText(message);
}
}
</DeepExtract>
if (message == null || message.length() == 0) {
sendSMS.setEnabled(false);
sendSMS.setClickable(false);
}
} | tinfoil-sms | positive | 2,031 |
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
if (isClosed) {
throw new SQLException("No operations allowed after connection closed. you should to use a new connection");
}
if (autoCommit) {
throw new SQLException("This method cannot be called during a transaction");
} else {
this.isReadOnly = readOnly;
}
} | @Override
public void setReadOnly(boolean readOnly) throws SQLException {
<DeepExtract>
if (isClosed) {
throw new SQLException("No operations allowed after connection closed. you should to use a new connection");
}
</DeepExtract>
if (autoCommit) {
throw new SQLException("This method cannot be called during a transaction");
} else {
this.isReadOnly = readOnly;
}
} | dragon | positive | 2,032 |
public ParamSpannableStringBuilder addTextAsParam(String text, int paramIndex, Object... spans) {
int start = mBuilder.length();
mBuilder.append(text);
int end = mBuilder.length();
for (Object span : spans) {
mBuilder.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return this;
if (paramIndex < mParams.length) {
mParams[paramIndex] = new Param(start, end);
}
return this;
} | public ParamSpannableStringBuilder addTextAsParam(String text, int paramIndex, Object... spans) {
int start = mBuilder.length();
mBuilder.append(text);
int end = mBuilder.length();
<DeepExtract>
for (Object span : spans) {
mBuilder.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return this;
</DeepExtract>
if (paramIndex < mParams.length) {
mParams[paramIndex] = new Param(start, end);
}
return this;
} | Utils-Everywhere | positive | 2,033 |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
SafeAppendable builder = new SafeAppendable(sb);
if (statementType == null) {
return null;
}
String answer;
switch(statementType) {
case DELETE:
answer = deleteSQL(builder);
break;
case INSERT:
answer = insertSQL(builder);
break;
case SELECT:
answer = selectSQL(builder);
break;
case UPDATE:
answer = updateSQL(builder);
break;
default:
answer = null;
}
return answer;
return sb.toString();
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
<DeepExtract>
SafeAppendable builder = new SafeAppendable(sb);
if (statementType == null) {
return null;
}
String answer;
switch(statementType) {
case DELETE:
answer = deleteSQL(builder);
break;
case INSERT:
answer = insertSQL(builder);
break;
case SELECT:
answer = selectSQL(builder);
break;
case UPDATE:
answer = updateSQL(builder);
break;
default:
answer = null;
}
return answer;
</DeepExtract>
return sb.toString();
} | EasyJdbc | positive | 2,034 |
public void addComment(Comment comment) {
comments.add(comment);
this.post = this;
} | public void addComment(Comment comment) {
comments.add(comment);
<DeepExtract>
this.post = this;
</DeepExtract>
} | hibernate-master-class | positive | 2,035 |
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mCurrentConversation = intent.getParcelableExtra(BUNDLE_CURRENT_CONVERSATION);
if (mCurrentConversation == null) {
finish();
}
mCurrentContact = mProfileManager.get(mCurrentConversation.getContactId());
ChatHandler.setCurrentVisibleChannel(mCurrentConversation.getContactId());
if (mCurrentConversation == null) {
return;
}
final int contactId = mCurrentConversation.getContactId();
setAvatarImage(contactId);
setTitleText(contactId);
LiveData<List<ChatMessage>> messageLiveData = mPrivateChatViewModel.getMessagesList();
messageLiveData.removeObserver(mMessageObserver);
mPrivateChatViewModel.setCurrentRoomId(mCurrentConversation.getId());
mPrivateChatViewModel.refreshData();
messageLiveData = mPrivateChatViewModel.getMessagesList();
messageLiveData.observe(this, mMessageObserver);
mAdapter.setCurrentContact(mCurrentContact);
} | @Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mCurrentConversation = intent.getParcelableExtra(BUNDLE_CURRENT_CONVERSATION);
if (mCurrentConversation == null) {
finish();
}
mCurrentContact = mProfileManager.get(mCurrentConversation.getContactId());
ChatHandler.setCurrentVisibleChannel(mCurrentConversation.getContactId());
<DeepExtract>
if (mCurrentConversation == null) {
return;
}
final int contactId = mCurrentConversation.getContactId();
setAvatarImage(contactId);
setTitleText(contactId);
</DeepExtract>
LiveData<List<ChatMessage>> messageLiveData = mPrivateChatViewModel.getMessagesList();
messageLiveData.removeObserver(mMessageObserver);
mPrivateChatViewModel.setCurrentRoomId(mCurrentConversation.getId());
mPrivateChatViewModel.refreshData();
messageLiveData = mPrivateChatViewModel.getMessagesList();
messageLiveData.observe(this, mMessageObserver);
mAdapter.setCurrentContact(mCurrentContact);
} | profile-sync | positive | 2,036 |
public Criteria andWeiboGreaterThan(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "weibo" + " cannot be null");
}
criteria.add(new Criterion("weibo >", value));
return (Criteria) this;
} | public Criteria andWeiboGreaterThan(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "weibo" + " cannot be null");
}
criteria.add(new Criterion("weibo >", value));
</DeepExtract>
return (Criteria) this;
} | CRM | positive | 2,037 |
public AbstractNode get(int index) {
if (index < 0 || index > size() - 1) {
throw new IndexOutOfBoundsException("Invalid index:" + index + ", size=" + size());
}
return value;
} | public AbstractNode get(int index) {
if (index < 0 || index > size() - 1) {
throw new IndexOutOfBoundsException("Invalid index:" + index + ", size=" + size());
}
<DeepExtract>
return value;
</DeepExtract>
} | BitcoinVisualizer | positive | 2,040 |
@Override
public FBPParticleDigging init() {
if (sourceState.getBlock() == Blocks.GRASS && facing != EnumFacing.UP)
return;
int i = mc.getBlockColors().colorMultiplier(this.sourceState, this.world, new BlockPos(this.posX, this.posY, this.posZ), 0);
this.particleRed *= (i >> 16 & 255) / 255.0F;
this.particleGreen *= (i >> 8 & 255) / 255.0F;
this.particleBlue *= (i & 255) / 255.0F;
return this;
} | @Override
public FBPParticleDigging init() {
<DeepExtract>
if (sourceState.getBlock() == Blocks.GRASS && facing != EnumFacing.UP)
return;
int i = mc.getBlockColors().colorMultiplier(this.sourceState, this.world, new BlockPos(this.posX, this.posY, this.posZ), 0);
this.particleRed *= (i >> 16 & 255) / 255.0F;
this.particleGreen *= (i >> 8 & 255) / 255.0F;
this.particleBlue *= (i & 255) / 255.0F;
</DeepExtract>
return this;
} | FancyBlockParticles | positive | 2,041 |
private boolean handleSearchResult(@NonNull @SuppressWarnings("unused") YTVideoListTask ytvl, @NonNull @SuppressWarnings("unused") YTDataAdapter.VideoListReq req, @NonNull YTDataAdapter.VideoListResp resp, @NonNull Err err) {
P.bug(AUtil.isUiThread());
if (Err.NO_ERR == err && resp.vids.length <= 0)
err = Err.NO_MATCH;
if (Err.NO_ERR != err) {
mPrevPageToken = mNextPageToken = null;
enableContentText(err.getMessage());
return false;
}
mPrevPageToken = resp.page.prevPageToken;
mNextPageToken = resp.page.nextPageToken;
LinearLayout nb = (LinearLayout) findViewById(R.id.navibar);
nb.setVisibility(View.VISIBLE);
TextView tv = (TextView) nb.findViewById(R.id.navi_current);
tv.setText("");
nb.findViewById(R.id.navi_prev).setVisibility(null != mPrevPageToken ? View.VISIBLE : View.INVISIBLE);
nb.findViewById(R.id.navi_next).setVisibility(null != mNextPageToken ? View.VISIBLE : View.INVISIBLE);
return nb;
return true;
} | private boolean handleSearchResult(@NonNull @SuppressWarnings("unused") YTVideoListTask ytvl, @NonNull @SuppressWarnings("unused") YTDataAdapter.VideoListReq req, @NonNull YTDataAdapter.VideoListResp resp, @NonNull Err err) {
P.bug(AUtil.isUiThread());
if (Err.NO_ERR == err && resp.vids.length <= 0)
err = Err.NO_MATCH;
if (Err.NO_ERR != err) {
mPrevPageToken = mNextPageToken = null;
enableContentText(err.getMessage());
return false;
}
mPrevPageToken = resp.page.prevPageToken;
mNextPageToken = resp.page.nextPageToken;
<DeepExtract>
LinearLayout nb = (LinearLayout) findViewById(R.id.navibar);
nb.setVisibility(View.VISIBLE);
TextView tv = (TextView) nb.findViewById(R.id.navi_current);
tv.setText("");
nb.findViewById(R.id.navi_prev).setVisibility(null != mPrevPageToken ? View.VISIBLE : View.INVISIBLE);
nb.findViewById(R.id.navi_next).setVisibility(null != mNextPageToken ? View.VISIBLE : View.INVISIBLE);
return nb;
</DeepExtract>
return true;
} | netmbuddy | positive | 2,042 |
@Test
public void testTransfer() throws InterruptedException {
SubAccount subAccountFrom = subAccountRepository.findById(1L);
subAccountFrom.setBalanceAmount(100);
subAccountFrom.setStatus(AccountStatus.NORMAL.getId());
SubAccount subAccountTo = subAccountRepository.findById(2L);
subAccountTo.setBalanceAmount(200);
subAccountTo.setStatus(AccountStatus.NORMAL.getId());
AccountRecord accountRecordFrom = accountRecordRepository.findById(1L);
accountRecordFrom.setBalanceAmount(0);
accountRecordFrom.setStatusId(AccountStatus.NORMAL.getId());
AccountRecord accountRecordTo = accountRecordRepository.findById(2L);
accountRecordTo.setBalanceAmount(0);
accountRecordTo.setStatusId(AccountStatus.NORMAL.getId());
transferService.transfer(1, 2, 50);
SubAccount subAccountFrom = subAccountRepository.findById(1L);
SubAccount subAccountTo = subAccountRepository.findById(2L);
Assert.assertTrue(subAccountFrom.getStatus() == AccountStatus.NORMAL.getId());
Assert.assertTrue(subAccountTo.getStatus() == AccountStatus.NORMAL.getId());
Assert.assertTrue(subAccountFrom.getBalanceAmount() == 50);
Assert.assertTrue(subAccountTo.getBalanceAmount() == 250);
} | @Test
public void testTransfer() throws InterruptedException {
<DeepExtract>
SubAccount subAccountFrom = subAccountRepository.findById(1L);
subAccountFrom.setBalanceAmount(100);
subAccountFrom.setStatus(AccountStatus.NORMAL.getId());
SubAccount subAccountTo = subAccountRepository.findById(2L);
subAccountTo.setBalanceAmount(200);
subAccountTo.setStatus(AccountStatus.NORMAL.getId());
AccountRecord accountRecordFrom = accountRecordRepository.findById(1L);
accountRecordFrom.setBalanceAmount(0);
accountRecordFrom.setStatusId(AccountStatus.NORMAL.getId());
AccountRecord accountRecordTo = accountRecordRepository.findById(2L);
accountRecordTo.setBalanceAmount(0);
accountRecordTo.setStatusId(AccountStatus.NORMAL.getId());
</DeepExtract>
transferService.transfer(1, 2, 50);
SubAccount subAccountFrom = subAccountRepository.findById(1L);
SubAccount subAccountTo = subAccountRepository.findById(2L);
Assert.assertTrue(subAccountFrom.getStatus() == AccountStatus.NORMAL.getId());
Assert.assertTrue(subAccountTo.getStatus() == AccountStatus.NORMAL.getId());
Assert.assertTrue(subAccountFrom.getBalanceAmount() == 50);
Assert.assertTrue(subAccountTo.getBalanceAmount() == 250);
} | tyloo | positive | 2,044 |
@Override
public double regress(Instance instance) {
double pred = intercept + w[0] * instance.getValue(attIndex) + w[1] * instance.getValue(attIndex) * instance.getValue(attIndex) + w[2] * instance.getValue(attIndex) * instance.getValue(attIndex) * instance.getValue(attIndex);
for (int i = 0; i < knots.length; i++) {
pred += h(instance.getValue(attIndex), knots[i]) * w[i + 3];
}
return pred;
} | @Override
public double regress(Instance instance) {
<DeepExtract>
double pred = intercept + w[0] * instance.getValue(attIndex) + w[1] * instance.getValue(attIndex) * instance.getValue(attIndex) + w[2] * instance.getValue(attIndex) * instance.getValue(attIndex) * instance.getValue(attIndex);
for (int i = 0; i < knots.length; i++) {
pred += h(instance.getValue(attIndex), knots[i]) * w[i + 3];
}
return pred;
</DeepExtract>
} | mltk | positive | 2,045 |
private void scrollView(float distanceX, float distanceY) {
int newX = (int) distanceX + getScrollX();
int newY = (int) distanceY + getScrollY();
int maxWidth = Math.max(getMaxScrollX(), getScrollX());
if (newX > maxWidth) {
newX = maxWidth;
} else if (newX < 0) {
newX = 0;
}
int maxHeight = Math.max(getMaxScrollY(), getScrollY());
if (newY > maxHeight) {
newY = maxHeight;
} else if (newY < 0) {
newY = 0;
}
smoothScrollBy(newX - getScrollX(), newY - getScrollY());
} | private void scrollView(float distanceX, float distanceY) {
int newX = (int) distanceX + getScrollX();
int newY = (int) distanceY + getScrollY();
int maxWidth = Math.max(getMaxScrollX(), getScrollX());
if (newX > maxWidth) {
newX = maxWidth;
} else if (newX < 0) {
newX = 0;
}
int maxHeight = Math.max(getMaxScrollY(), getScrollY());
if (newY > maxHeight) {
newY = maxHeight;
} else if (newY < 0) {
newY = 0;
}
<DeepExtract>
smoothScrollBy(newX - getScrollX(), newY - getScrollY());
</DeepExtract>
} | ALuaJ | positive | 2,046 |
public void actionPerformed(java.awt.event.ActionEvent evt) {
AbstractButton abstractButton = (AbstractButton) evt.getSource();
boolean selected = abstractButton.getModel().isSelected();
if (selected) {
panelInteranlCustomSet.setVisible(true);
mannualRange = true;
populateColoumnList();
} else {
clearTogglePane();
}
} | public void actionPerformed(java.awt.event.ActionEvent evt) {
<DeepExtract>
AbstractButton abstractButton = (AbstractButton) evt.getSource();
boolean selected = abstractButton.getModel().isSelected();
if (selected) {
panelInteranlCustomSet.setVisible(true);
mannualRange = true;
populateColoumnList();
} else {
clearTogglePane();
}
</DeepExtract>
} | HBase-Manager | positive | 2,047 |
@Override
protected void seekInternal(InternalKey targetKey) {
for (InternalIterator level : levels) {
level.seek(targetKey);
}
int i = 1;
for (InternalIterator level : levels) {
if (level.hasNext()) {
priorityQueue.add(new ComparableIterator(level, comparator, i++, level.next()));
}
}
} | @Override
protected void seekInternal(InternalKey targetKey) {
for (InternalIterator level : levels) {
level.seek(targetKey);
}
<DeepExtract>
int i = 1;
for (InternalIterator level : levels) {
if (level.hasNext()) {
priorityQueue.add(new ComparableIterator(level, comparator, i++, level.next()));
}
}
</DeepExtract>
} | leveldb | positive | 2,049 |
public static void main(String[] args) {
App baz = new App();
this.<Boolean>bar();
System.out.println("worked well");
} | public static void main(String[] args) {
App baz = new App();
<DeepExtract>
this.<Boolean>bar();
</DeepExtract>
System.out.println("worked well");
} | javancss | positive | 2,050 |
public void populateYeastFromRecipe(View parent, Yeast yeast, int packsAccountedFor) {
TextView view = (TextView) parent.findViewById(R.id.inventory_message);
view.setVisibility(View.GONE);
ImageView check = (ImageView) parent.findViewById(R.id.check);
check.setVisibility(View.GONE);
double inInventory = mStorage.retrieveInventory().getItemCount(Yeast.class, yeast.getName());
inInventory -= packsAccountedFor;
if (inInventory < 0)
inInventory = 0;
if (inInventory < 1) {
view.setVisibility(View.VISIBLE);
view.setText("(" + Util.fromDouble(1 - inInventory, 1) + " Pkg.)");
} else {
check.setVisibility(View.VISIBLE);
}
if (!mShowInventory) {
hideInventoryView(parent);
}
TextView view = (TextView) parent.findViewById(R.id.name);
view.setText(yeast.getName());
view = (TextView) parent.findViewById(R.id.attenuation);
view.setText(IngredientInfo.getInfo(yeast));
} | public void populateYeastFromRecipe(View parent, Yeast yeast, int packsAccountedFor) {
TextView view = (TextView) parent.findViewById(R.id.inventory_message);
view.setVisibility(View.GONE);
ImageView check = (ImageView) parent.findViewById(R.id.check);
check.setVisibility(View.GONE);
double inInventory = mStorage.retrieveInventory().getItemCount(Yeast.class, yeast.getName());
inInventory -= packsAccountedFor;
if (inInventory < 0)
inInventory = 0;
if (inInventory < 1) {
view.setVisibility(View.VISIBLE);
view.setText("(" + Util.fromDouble(1 - inInventory, 1) + " Pkg.)");
} else {
check.setVisibility(View.VISIBLE);
}
if (!mShowInventory) {
hideInventoryView(parent);
}
<DeepExtract>
TextView view = (TextView) parent.findViewById(R.id.name);
view.setText(yeast.getName());
view = (TextView) parent.findViewById(R.id.attenuation);
view.setText(IngredientInfo.getInfo(yeast));
</DeepExtract>
} | BrewShopApp | positive | 2,051 |
public int[] mergeSort(int[] nums) {
if (nums == null || nums.length < 2) {
return new int[0];
}
if (0 == nums.length - 1) {
return;
}
int mid = 0 + ((nums.length - 1 - 0) >> 1);
sortProcess(nums, 0, mid);
sortProcess(nums, mid + 1, nums.length - 1);
merge(nums, 0, mid, nums.length - 1);
return nums;
} | public int[] mergeSort(int[] nums) {
if (nums == null || nums.length < 2) {
return new int[0];
}
<DeepExtract>
if (0 == nums.length - 1) {
return;
}
int mid = 0 + ((nums.length - 1 - 0) >> 1);
sortProcess(nums, 0, mid);
sortProcess(nums, mid + 1, nums.length - 1);
merge(nums, 0, mid, nums.length - 1);
</DeepExtract>
return nums;
} | LeetCodeAndSwordToOffer | positive | 2,053 |
@Override
public void onSmoothScrollFinished() {
if (null != mCurrentSmoothScrollRunnable) {
mCurrentSmoothScrollRunnable.stop();
}
final int oldScrollValue;
switch(getPullToRefreshScrollDirection()) {
case HORIZONTAL:
oldScrollValue = getScrollX();
break;
case VERTICAL:
default:
oldScrollValue = getScrollY();
break;
}
if (oldScrollValue != 0) {
if (null == mScrollAnimationInterpolator) {
mScrollAnimationInterpolator = new DecelerateInterpolator();
}
mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(oldScrollValue, 0, SMOOTH_SCROLL_DURATION_MS, null);
if (DEMO_SCROLL_INTERVAL > 0) {
postDelayed(mCurrentSmoothScrollRunnable, DEMO_SCROLL_INTERVAL);
} else {
post(mCurrentSmoothScrollRunnable);
}
}
} | @Override
public void onSmoothScrollFinished() {
<DeepExtract>
if (null != mCurrentSmoothScrollRunnable) {
mCurrentSmoothScrollRunnable.stop();
}
final int oldScrollValue;
switch(getPullToRefreshScrollDirection()) {
case HORIZONTAL:
oldScrollValue = getScrollX();
break;
case VERTICAL:
default:
oldScrollValue = getScrollY();
break;
}
if (oldScrollValue != 0) {
if (null == mScrollAnimationInterpolator) {
mScrollAnimationInterpolator = new DecelerateInterpolator();
}
mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(oldScrollValue, 0, SMOOTH_SCROLL_DURATION_MS, null);
if (DEMO_SCROLL_INTERVAL > 0) {
postDelayed(mCurrentSmoothScrollRunnable, DEMO_SCROLL_INTERVAL);
} else {
post(mCurrentSmoothScrollRunnable);
}
}
</DeepExtract>
} | MingQQ | positive | 2,054 |
@Override
public double getCharge(ItemStack itemStack) {
Long[] stats = getElectricStats(itemStack);
if (stats == null) {
return 0;
}
NBTTagCompound data = TGregUtils.getCompoundTag(itemStack, "TGregBattery");
return data == null ? 0 : data.getLong("currentCharge");
} | @Override
public double getCharge(ItemStack itemStack) {
<DeepExtract>
Long[] stats = getElectricStats(itemStack);
if (stats == null) {
return 0;
}
NBTTagCompound data = TGregUtils.getCompoundTag(itemStack, "TGregBattery");
return data == null ? 0 : data.getLong("currentCharge");
</DeepExtract>
} | TinkersGregworks | positive | 2,055 |
@Override
public E remove() {
final Node<E> f = first;
if (f == null) {
throw new NoSuchElementException();
}
return unlinkFirst(f);
} | @Override
public E remove() {
<DeepExtract>
final Node<E> f = first;
if (f == null) {
throw new NoSuchElementException();
}
return unlinkFirst(f);
</DeepExtract>
} | java-Kcp | positive | 2,056 |
@Override
public Matrix addColumnVector(final Matrix vector) {
if (!(vector instanceof MatrixJBLASImpl)) {
throw new IllegalArgumentException("The given matrix should be JBLAS based");
}
return new MatrixJBLASImpl(jblasMatrix.addColumnVector(((MatrixJBLASImpl) vector).jblasMatrix));
} | @Override
public Matrix addColumnVector(final Matrix vector) {
<DeepExtract>
if (!(vector instanceof MatrixJBLASImpl)) {
throw new IllegalArgumentException("The given matrix should be JBLAS based");
}
</DeepExtract>
return new MatrixJBLASImpl(jblasMatrix.addColumnVector(((MatrixJBLASImpl) vector).jblasMatrix));
} | dolphin | positive | 2,057 |
@Override
public void doReconnect(SocketConnection connection) {
try {
connect();
} catch (Exception e) {
notifyConnectException(e);
}
} | @Override
public void doReconnect(SocketConnection connection) {
<DeepExtract>
try {
connect();
} catch (Exception e) {
notifyConnectException(e);
}
</DeepExtract>
} | bizsocket | positive | 2,058 |
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll();
if (isMenuOpen()) {
if (mOpenedListener != null)
mOpenedListener.onOpened();
} else {
if (mClosedListener != null)
mClosedListener.onClosed();
}
return;
}
if (mScrollingCacheEnabled != true) {
mScrollingCacheEnabled = true;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(true);
}
}
}
}
mScrolling = true;
int width;
if (mViewBehind == null) {
width = 0;
} else {
width = mViewBehind.getBehindWidth();
}
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageDelta = (float) Math.abs(dx) / width;
duration = (int) ((pageDelta + 1) * 100);
duration = MAX_SETTLE_DURATION;
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
invalidate();
} | void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll();
if (isMenuOpen()) {
if (mOpenedListener != null)
mOpenedListener.onOpened();
} else {
if (mClosedListener != null)
mClosedListener.onClosed();
}
return;
}
if (mScrollingCacheEnabled != true) {
mScrollingCacheEnabled = true;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(true);
}
}
}
}
mScrolling = true;
<DeepExtract>
int width;
if (mViewBehind == null) {
width = 0;
} else {
width = mViewBehind.getBehindWidth();
}
</DeepExtract>
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageDelta = (float) Math.abs(dx) / width;
duration = (int) ((pageDelta + 1) * 100);
duration = MAX_SETTLE_DURATION;
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
invalidate();
} | LeaugeBar_Android | positive | 2,059 |
@Override
public void windowClosed(WindowEvent arg0) {
listener.close();
} | @Override
public void windowClosed(WindowEvent arg0) {
<DeepExtract>
listener.close();
</DeepExtract>
} | Towel | positive | 2,060 |
public Criteria andAphoneIn(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "aphone" + " cannot be null");
}
criteria.add(new Criterion("aphone in", values));
return (Criteria) this;
} | public Criteria andAphoneIn(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "aphone" + " cannot be null");
}
criteria.add(new Criterion("aphone in", values));
</DeepExtract>
return (Criteria) this;
} | Hospital | positive | 2,062 |
public void setStrokeColor(int strokeColor) {
this.strokeColor = strokeColor;
StateListDrawable bg = new StateListDrawable();
setDrawable(gd_background, backgroundColor, strokeColor);
bg.addState(new int[] { -android.R.attr.state_pressed }, gd_background);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(bg);
} else {
setBackgroundDrawable(bg);
}
} | public void setStrokeColor(int strokeColor) {
this.strokeColor = strokeColor;
<DeepExtract>
StateListDrawable bg = new StateListDrawable();
setDrawable(gd_background, backgroundColor, strokeColor);
bg.addState(new int[] { -android.R.attr.state_pressed }, gd_background);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(bg);
} else {
setBackgroundDrawable(bg);
}
</DeepExtract>
} | Shopping | positive | 2,063 |
public void onClick(View v) {
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
path = file.getPath();
Uri imageUri = Uri.fromFile(file);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
dismiss();
} | public void onClick(View v) {
<DeepExtract>
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
path = file.getPath();
Uri imageUri = Uri.fromFile(file);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
</DeepExtract>
dismiss();
} | mshopping-android | positive | 2,064 |
@Override
public void onCreateActions(List<GuidedAction> actions, Bundle savedInstanceState) {
actions.add(new GuidedAction.Builder().id(CONTINUE).title(getResources().getString(R.string.guidedstep_continue)).description(getResources().getString(R.string.guidedstep_letsdoit)).build());
actions.add(new GuidedAction.Builder().id(BACK).title(getResources().getString(R.string.guidedstep_cancel)).description(getResources().getString(R.string.guidedstep_nevermind)).build());
} | @Override
public void onCreateActions(List<GuidedAction> actions, Bundle savedInstanceState) {
actions.add(new GuidedAction.Builder().id(CONTINUE).title(getResources().getString(R.string.guidedstep_continue)).description(getResources().getString(R.string.guidedstep_letsdoit)).build());
<DeepExtract>
actions.add(new GuidedAction.Builder().id(BACK).title(getResources().getString(R.string.guidedstep_cancel)).description(getResources().getString(R.string.guidedstep_nevermind)).build());
</DeepExtract>
} | BuildingForAndroidTV | positive | 2,065 |
@Bean
public MapperScannerConfigurer mapperScannerConfigurer2() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory2");
mapperScannerConfigurer.setAnnotationClass(Mapper.class);
mapperScannerConfigurer.setBasePackage("com.xjs1919.mybatis.dao.ds2");
return mapperScannerConfigurer;
} | @Bean
public MapperScannerConfigurer mapperScannerConfigurer2() {
<DeepExtract>
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory2");
mapperScannerConfigurer.setAnnotationClass(Mapper.class);
mapperScannerConfigurer.setBasePackage("com.xjs1919.mybatis.dao.ds2");
return mapperScannerConfigurer;
</DeepExtract>
} | enumdemo | positive | 2,066 |
@Override
public Store.CommandBuilder<C, T> map(Object parameters) {
checkState(m_valid, "This TransactionBuilder is no more usable");
if (parameters instanceof Map) {
Map<?, ?> map = (Map<?, ?>) parameters;
for (Map.Entry<?, ?> e : map.entrySet()) {
String key = (String) e.getKey();
setParameter(key, e.getValue());
}
} else {
throw new UnsupportedOperationException("To be implemented");
}
return this;
} | @Override
public Store.CommandBuilder<C, T> map(Object parameters) {
<DeepExtract>
checkState(m_valid, "This TransactionBuilder is no more usable");
</DeepExtract>
if (parameters instanceof Map) {
Map<?, ?> map = (Map<?, ?>) parameters;
for (Map.Entry<?, ?> e : map.entrySet()) {
String key = (String) e.getKey();
setParameter(key, e.getValue());
}
} else {
throw new UnsupportedOperationException("To be implemented");
}
return this;
} | iron | positive | 2,067 |
public static void main(String[] args) {
MultiGraph graph = new MultiGraph("Test Size");
Viewer viewer = new FxViewer(graph, FxViewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
ViewerPipe pipeIn = viewer.newViewerPipe();
FxDefaultView view = (FxDefaultView) viewer.addView("view1", new FxGraphRenderer());
DefaultApplication.init(view, graph);
new Thread(() -> Application.launch(DefaultApplication.class)).start();
pipeIn.addAttributeSink(graph);
pipeIn.addViewerListener(this);
pipeIn.pump();
graph.setAttribute("ui.stylesheet", styleSheet);
graph.setAttribute("ui.antialias");
graph.setAttribute("ui.quality");
Node A = graph.addNode("A");
Node B = graph.addNode("B");
Node C = graph.addNode("C");
Node D = graph.addNode("D");
Edge AB = graph.addEdge("AB", "A", "B", true);
Edge BC = graph.addEdge("BC", "B", "C", true);
Edge CD = graph.addEdge("CD", "C", "D", true);
Edge DA = graph.addEdge("DA", "D", "A", true);
Edge BB = graph.addEdge("BB", "B", "B", true);
A.setAttribute("xyz", new double[] { 0, 1, 0 });
B.setAttribute("xyz", new double[] { 1, 1, 0 });
C.setAttribute("xyz", new double[] { 1, 0, 0 });
D.setAttribute("xyz", new double[] { 0, 0, 0 });
AB.setAttribute("ui.label", "AB");
BC.setAttribute("ui.label", "A Long label ...");
CD.setAttribute("ui.label", "CD");
BB.setAttribute("ui.label", "BB");
SpriteManager sm = new SpriteManager(graph);
Sprite S1 = sm.addSprite("S1");
S1.attachToNode("C");
S1.setPosition(StyleConstants.Units.PX, 40, 45, 0);
double size = 20f;
double sizeInc = 1f;
while (loop) {
pipeIn.pump();
sleep(40);
A.setAttribute("ui.size", size);
BC.setAttribute("ui.size", size);
S1.setAttribute("ui.size", size);
size += sizeInc;
if (size > 50) {
sizeInc = -1f;
size = 50f;
} else if (size < 20) {
sizeInc = 1f;
size = 20f;
}
}
System.out.println("bye bye");
System.exit(0);
} | public static void main(String[] args) {
<DeepExtract>
MultiGraph graph = new MultiGraph("Test Size");
Viewer viewer = new FxViewer(graph, FxViewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
ViewerPipe pipeIn = viewer.newViewerPipe();
FxDefaultView view = (FxDefaultView) viewer.addView("view1", new FxGraphRenderer());
DefaultApplication.init(view, graph);
new Thread(() -> Application.launch(DefaultApplication.class)).start();
pipeIn.addAttributeSink(graph);
pipeIn.addViewerListener(this);
pipeIn.pump();
graph.setAttribute("ui.stylesheet", styleSheet);
graph.setAttribute("ui.antialias");
graph.setAttribute("ui.quality");
Node A = graph.addNode("A");
Node B = graph.addNode("B");
Node C = graph.addNode("C");
Node D = graph.addNode("D");
Edge AB = graph.addEdge("AB", "A", "B", true);
Edge BC = graph.addEdge("BC", "B", "C", true);
Edge CD = graph.addEdge("CD", "C", "D", true);
Edge DA = graph.addEdge("DA", "D", "A", true);
Edge BB = graph.addEdge("BB", "B", "B", true);
A.setAttribute("xyz", new double[] { 0, 1, 0 });
B.setAttribute("xyz", new double[] { 1, 1, 0 });
C.setAttribute("xyz", new double[] { 1, 0, 0 });
D.setAttribute("xyz", new double[] { 0, 0, 0 });
AB.setAttribute("ui.label", "AB");
BC.setAttribute("ui.label", "A Long label ...");
CD.setAttribute("ui.label", "CD");
BB.setAttribute("ui.label", "BB");
SpriteManager sm = new SpriteManager(graph);
Sprite S1 = sm.addSprite("S1");
S1.attachToNode("C");
S1.setPosition(StyleConstants.Units.PX, 40, 45, 0);
double size = 20f;
double sizeInc = 1f;
while (loop) {
pipeIn.pump();
sleep(40);
A.setAttribute("ui.size", size);
BC.setAttribute("ui.size", size);
S1.setAttribute("ui.size", size);
size += sizeInc;
if (size > 50) {
sizeInc = -1f;
size = 50f;
} else if (size < 20) {
sizeInc = 1f;
size = 20f;
}
}
System.out.println("bye bye");
System.exit(0);
</DeepExtract>
} | gs-ui-javafx | positive | 2,068 |
public static boolean is3G(Context context) {
NetworkInfo activeNetInfo = getNetworkInfo(context);
return activeNetInfo != null && activeNetInfo.getType() == 1;
} | public static boolean is3G(Context context) {
<DeepExtract>
NetworkInfo activeNetInfo = getNetworkInfo(context);
return activeNetInfo != null && activeNetInfo.getType() == 1;
</DeepExtract>
} | TradeIn | positive | 2,070 |
public V add(K key, V value) {
if (key == null)
throw new IllegalArgumentException("Null key");
Entry<K, V> newEntry = new Entry<>(key, value);
int bucketIndex = normalizeIndex(newEntry.hash);
return bucketInsertEntry(bucketIndex, newEntry);
} | public V add(K key, V value) {
<DeepExtract>
if (key == null)
throw new IllegalArgumentException("Null key");
Entry<K, V> newEntry = new Entry<>(key, value);
int bucketIndex = normalizeIndex(newEntry.hash);
return bucketInsertEntry(bucketIndex, newEntry);
</DeepExtract>
} | DEPRECATED-data-structures | positive | 2,072 |
public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException {
boolean errorOccured = false;
if (handle.client != this) {
throw new IOException("The file handle was created with another SFTPv3FileHandle instance.");
}
if (handle.isClosed) {
throw new IOException("The file handle is closed.");
}
int remaining = len * parallelism;
int clientOffset = dstoff;
long serverOffset = fileOffset;
for (OutstandingReadRequest r : pendingReadQueue.values()) {
serverOffset += r.len;
}
while (true) {
if ((pendingReadQueue.size() == 0) && errorOccured) {
break;
}
while (pendingReadQueue.size() < parallelism) {
if (errorOccured) {
break;
}
OutstandingReadRequest req = new OutstandingReadRequest();
req.req_id = generateNextRequestID();
req.serverOffset = serverOffset;
req.len = (remaining > len) ? len : remaining;
req.buffer = dst;
req.dstOffset = dstoff;
serverOffset += req.len;
clientOffset += req.len;
remaining -= req.len;
sendReadRequest(req.req_id, handle, req.serverOffset, req.len);
pendingReadQueue.put(req.req_id, req);
}
if (pendingReadQueue.size() == 0) {
break;
}
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
listener.read(Packet.forName(t));
OutstandingReadRequest req = pendingReadQueue.remove(tr.readUINT32());
if (null == req) {
throw new IOException("The server sent an invalid id field.");
}
if (t == Packet.SSH_FXP_STATUS) {
int code = tr.readUINT32();
String msg = tr.readString();
listener.read(msg);
if (log.isDebugEnabled()) {
String[] desc = ErrorCodes.getDescription(code);
log.debug("Got SSH_FXP_STATUS (" + req.req_id + ") (" + ((desc != null) ? desc[0] : "UNKNOWN") + ")");
}
errorOccured = true;
if (pendingReadQueue.isEmpty()) {
if (ErrorCodes.SSH_FX_EOF == code) {
return -1;
}
throw new SFTPException(msg, code);
}
} else if (t == Packet.SSH_FXP_DATA) {
int readLen = tr.readUINT32();
if ((readLen < 0) || (readLen > req.len)) {
throw new IOException("The server sent an invalid length field in a SSH_FXP_DATA packet.");
}
if (log.isDebugEnabled()) {
log.debug("Got SSH_FXP_DATA (" + req.req_id + ") " + req.serverOffset + "/" + readLen + " (requested: " + req.len + ")");
}
tr.readBytes(req.buffer, req.dstOffset, readLen);
if (readLen < req.len) {
req.req_id = generateNextRequestID();
req.serverOffset += readLen;
req.len -= readLen;
log.debug("Requesting again: " + req.serverOffset + "/" + req.len);
sendReadRequest(req.req_id, handle, req.serverOffset, req.len);
pendingReadQueue.put(req.req_id, req);
}
return readLen;
} else {
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
}
}
throw new SFTPException("No EOF reached", -1);
} | public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException {
boolean errorOccured = false;
<DeepExtract>
if (handle.client != this) {
throw new IOException("The file handle was created with another SFTPv3FileHandle instance.");
}
if (handle.isClosed) {
throw new IOException("The file handle is closed.");
}
</DeepExtract>
int remaining = len * parallelism;
int clientOffset = dstoff;
long serverOffset = fileOffset;
for (OutstandingReadRequest r : pendingReadQueue.values()) {
serverOffset += r.len;
}
while (true) {
if ((pendingReadQueue.size() == 0) && errorOccured) {
break;
}
while (pendingReadQueue.size() < parallelism) {
if (errorOccured) {
break;
}
OutstandingReadRequest req = new OutstandingReadRequest();
req.req_id = generateNextRequestID();
req.serverOffset = serverOffset;
req.len = (remaining > len) ? len : remaining;
req.buffer = dst;
req.dstOffset = dstoff;
serverOffset += req.len;
clientOffset += req.len;
remaining -= req.len;
sendReadRequest(req.req_id, handle, req.serverOffset, req.len);
pendingReadQueue.put(req.req_id, req);
}
if (pendingReadQueue.size() == 0) {
break;
}
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
listener.read(Packet.forName(t));
OutstandingReadRequest req = pendingReadQueue.remove(tr.readUINT32());
if (null == req) {
throw new IOException("The server sent an invalid id field.");
}
if (t == Packet.SSH_FXP_STATUS) {
int code = tr.readUINT32();
String msg = tr.readString();
listener.read(msg);
if (log.isDebugEnabled()) {
String[] desc = ErrorCodes.getDescription(code);
log.debug("Got SSH_FXP_STATUS (" + req.req_id + ") (" + ((desc != null) ? desc[0] : "UNKNOWN") + ")");
}
errorOccured = true;
if (pendingReadQueue.isEmpty()) {
if (ErrorCodes.SSH_FX_EOF == code) {
return -1;
}
throw new SFTPException(msg, code);
}
} else if (t == Packet.SSH_FXP_DATA) {
int readLen = tr.readUINT32();
if ((readLen < 0) || (readLen > req.len)) {
throw new IOException("The server sent an invalid length field in a SSH_FXP_DATA packet.");
}
if (log.isDebugEnabled()) {
log.debug("Got SSH_FXP_DATA (" + req.req_id + ") " + req.serverOffset + "/" + readLen + " (requested: " + req.len + ")");
}
tr.readBytes(req.buffer, req.dstOffset, readLen);
if (readLen < req.len) {
req.req_id = generateNextRequestID();
req.serverOffset += readLen;
req.len -= readLen;
log.debug("Requesting again: " + req.serverOffset + "/" + req.len);
sendReadRequest(req.req_id, handle, req.serverOffset, req.len);
pendingReadQueue.put(req.req_id, req);
}
return readLen;
} else {
throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")");
}
}
throw new SFTPException("No EOF reached", -1);
} | Testingbot-Tunnel | positive | 2,073 |
public void launchPurchaseFlow(Activity act, String sku, String itemType, List<String> oldSkus, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) throws IabAsyncInProgressException {
if (mDisposed)
throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
if (!mSetupDone) {
logError("Illegal state for operation (" + "launchPurchaseFlow" + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + "launchPurchaseFlow");
}
synchronized (mAsyncInProgressLock) {
if (mAsyncInProgress) {
throw new IabAsyncInProgressException("Can't start async operation (" + "launchPurchaseFlow" + ") because another async operation (" + mAsyncOperation + ") is in progress.");
}
mAsyncOperation = "launchPurchaseFlow";
mAsyncInProgress = true;
logDebug("Starting async operation: " + "launchPurchaseFlow");
}
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle;
if (oldSkus == null || oldSkus.isEmpty()) {
buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
} else {
if (!mSubscriptionUpdateSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTION_UPDATE_NOT_AVAILABLE, "Subscription updates are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
buyIntentBundle = mService.getBuyIntentToReplaceSkus(5, mContext.getPackageName(), oldSkus, sku, itemType, extraData);
}
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
} catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
}
} | public void launchPurchaseFlow(Activity act, String sku, String itemType, List<String> oldSkus, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) throws IabAsyncInProgressException {
if (mDisposed)
throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
if (!mSetupDone) {
logError("Illegal state for operation (" + "launchPurchaseFlow" + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + "launchPurchaseFlow");
}
<DeepExtract>
synchronized (mAsyncInProgressLock) {
if (mAsyncInProgress) {
throw new IabAsyncInProgressException("Can't start async operation (" + "launchPurchaseFlow" + ") because another async operation (" + mAsyncOperation + ") is in progress.");
}
mAsyncOperation = "launchPurchaseFlow";
mAsyncInProgress = true;
logDebug("Starting async operation: " + "launchPurchaseFlow");
}
</DeepExtract>
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle;
if (oldSkus == null || oldSkus.isEmpty()) {
buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
} else {
if (!mSubscriptionUpdateSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTION_UPDATE_NOT_AVAILABLE, "Subscription updates are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
buyIntentBundle = mService.getBuyIntentToReplaceSkus(5, mContext.getPackageName(), oldSkus, sku, itemType, extraData);
}
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
} catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
}
} | Trivia-Knowledge | positive | 2,074 |
@Override
public List<HttpCookie> get(URI uri) {
mLock.lock();
if (isEnable() && mCookieEntityDao == null) {
mCookieEntityDao = new CookieEntityDao(mContext);
Where where = new Where(CookieSQLHelper.EXPIRY, Options.EQUAL, -1L);
mCookieEntityDao.delete(where.get());
}
mLock.unlock();
mLock.lock();
try {
if (uri == null || !isEnable())
return Collections.emptyList();
uri = getEffectiveURI(uri);
Where where = new Where();
String host = uri.getHost();
if (!TextUtils.isEmpty(host)) {
Where subWhere = new Where(CookieSQLHelper.DOMAIN, Options.EQUAL, host).or(CookieSQLHelper.DOMAIN, Options.EQUAL, "." + host);
int firstDot = host.indexOf(".");
int lastDot = host.lastIndexOf(".");
if (firstDot > 0 && lastDot > firstDot) {
String domain = host.substring(firstDot, host.length());
if (!TextUtils.isEmpty(domain)) {
subWhere.or(CookieSQLHelper.DOMAIN, Options.EQUAL, domain);
}
}
where.set(subWhere.get());
}
String path = uri.getPath();
if (!TextUtils.isEmpty(path)) {
Where subWhere = new Where(CookieSQLHelper.PATH, Options.EQUAL, path).or(CookieSQLHelper.PATH, Options.EQUAL, "/").orNull(CookieSQLHelper.PATH);
int lastSplit = path.lastIndexOf("/");
while (lastSplit > 0) {
path = path.substring(0, lastSplit);
subWhere.or(CookieSQLHelper.PATH, Options.EQUAL, path);
lastSplit = path.lastIndexOf("/");
}
subWhere.bracket();
where.and(subWhere);
}
where.or(CookieSQLHelper.URI, Options.EQUAL, uri.toString());
List<CookieEntity> cookieList = mCookieEntityDao.getList(where.get(), null, null, null);
List<HttpCookie> returnedCookies = new ArrayList<>();
for (CookieEntity cookieEntity : cookieList) {
if (!cookieEntity.isExpired())
returnedCookies.add(cookieEntity.toHttpCookie());
}
return returnedCookies;
} finally {
mLock.unlock();
}
} | @Override
public List<HttpCookie> get(URI uri) {
<DeepExtract>
mLock.lock();
if (isEnable() && mCookieEntityDao == null) {
mCookieEntityDao = new CookieEntityDao(mContext);
Where where = new Where(CookieSQLHelper.EXPIRY, Options.EQUAL, -1L);
mCookieEntityDao.delete(where.get());
}
mLock.unlock();
</DeepExtract>
mLock.lock();
try {
if (uri == null || !isEnable())
return Collections.emptyList();
uri = getEffectiveURI(uri);
Where where = new Where();
String host = uri.getHost();
if (!TextUtils.isEmpty(host)) {
Where subWhere = new Where(CookieSQLHelper.DOMAIN, Options.EQUAL, host).or(CookieSQLHelper.DOMAIN, Options.EQUAL, "." + host);
int firstDot = host.indexOf(".");
int lastDot = host.lastIndexOf(".");
if (firstDot > 0 && lastDot > firstDot) {
String domain = host.substring(firstDot, host.length());
if (!TextUtils.isEmpty(domain)) {
subWhere.or(CookieSQLHelper.DOMAIN, Options.EQUAL, domain);
}
}
where.set(subWhere.get());
}
String path = uri.getPath();
if (!TextUtils.isEmpty(path)) {
Where subWhere = new Where(CookieSQLHelper.PATH, Options.EQUAL, path).or(CookieSQLHelper.PATH, Options.EQUAL, "/").orNull(CookieSQLHelper.PATH);
int lastSplit = path.lastIndexOf("/");
while (lastSplit > 0) {
path = path.substring(0, lastSplit);
subWhere.or(CookieSQLHelper.PATH, Options.EQUAL, path);
lastSplit = path.lastIndexOf("/");
}
subWhere.bracket();
where.and(subWhere);
}
where.or(CookieSQLHelper.URI, Options.EQUAL, uri.toString());
List<CookieEntity> cookieList = mCookieEntityDao.getList(where.get(), null, null, null);
List<HttpCookie> returnedCookies = new ArrayList<>();
for (CookieEntity cookieEntity : cookieList) {
if (!cookieEntity.isExpired())
returnedCookies.add(cookieEntity.toHttpCookie());
}
return returnedCookies;
} finally {
mLock.unlock();
}
} | NoHttp | positive | 2,075 |
@Override
public Properties getClientInfo() throws SQLException {
if (!pooledObject.isBorrowed()) {
throw new SQLException("PooledConnection has been returned to pool");
}
return connection.getClientInfo();
} | @Override
public Properties getClientInfo() throws SQLException {
<DeepExtract>
if (!pooledObject.isBorrowed()) {
throw new SQLException("PooledConnection has been returned to pool");
}
</DeepExtract>
return connection.getClientInfo();
} | jsql | positive | 2,076 |
@Override
public void setIs24HourView(boolean is24HourView) {
if (is24HourView == mIs24HourView) {
return;
}
mIs24HourView = is24HourView;
final int k0 = KeyEvent.KEYCODE_0;
final int k1 = KeyEvent.KEYCODE_1;
final int k2 = KeyEvent.KEYCODE_2;
final int k3 = KeyEvent.KEYCODE_3;
final int k4 = KeyEvent.KEYCODE_4;
final int k5 = KeyEvent.KEYCODE_5;
final int k6 = KeyEvent.KEYCODE_6;
final int k7 = KeyEvent.KEYCODE_7;
final int k8 = KeyEvent.KEYCODE_8;
final int k9 = KeyEvent.KEYCODE_9;
mLegalTimesTree = new Node();
if (mIs24HourView) {
Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
minuteFirstDigit.addChild(minuteSecondDigit);
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit);
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
Node thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
secondDigit = new Node(k6, k7, k8, k9);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
firstDigit = new Node(k2);
mLegalTimesTree.addChild(firstDigit);
secondDigit = new Node(k0, k1, k2, k3);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
secondDigit = new Node(k4, k5);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteSecondDigit);
firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(minuteFirstDigit);
} else {
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(ampm);
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit);
secondDigit.addChild(ampm);
Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
thirdDigit.addChild(fourthDigit);
fourthDigit.addChild(ampm);
thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
secondDigit = new Node(k3, k4, k5);
firstDigit.addChild(secondDigit);
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(ampm);
secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
}
int hour;
int currentHour = mRadialTimePickerView.getCurrentHour();
if (mIs24HourView) {
hour = currentHour;
} else {
switch(mRadialTimePickerView.getAmOrPm()) {
case PM:
hour = (currentHour % HOURS_IN_HALF_DAY) + HOURS_IN_HALF_DAY;
case AM:
default:
hour = currentHour % HOURS_IN_HALF_DAY;
}
}
mInitialHourOfDay = hour;
final String bestDateTimePattern = DateFormatUtils.getBestDateTimePattern(mCurrentLocale, (mIs24HourView) ? "Hm" : "hm");
final int lengthPattern = bestDateTimePattern.length();
boolean hourWithTwoDigit = false;
char hourFormat = '\0';
for (int i = 0; i < lengthPattern; i++) {
final char c = bestDateTimePattern.charAt(i);
if (c == 'H' || c == 'h' || c == 'K' || c == 'k') {
hourFormat = c;
if (i + 1 < lengthPattern && c == bestDateTimePattern.charAt(i + 1)) {
hourWithTwoDigit = true;
}
break;
}
}
final String format;
if (hourWithTwoDigit) {
format = "%02d";
} else {
format = "%d";
}
if (mIs24HourView) {
if (hourFormat == 'k' && hour == 0) {
hour = 24;
}
} else {
hour = modulo12(hour, hourFormat == 'K');
}
CharSequence text = String.format(format, hour);
mHourView.setText(text);
if (false) {
tryAnnounceForAccessibility(text, true);
}
if (mIs24HourView) {
mAmPmLayout.setVisibility(View.GONE);
} else {
final String dateTimePattern = DateFormatUtils.getBestDateTimePattern(mCurrentLocale, "hm");
final boolean isAmPmAtStart = dateTimePattern.startsWith("a");
setAmPmAtStart(isAmPmAtStart);
updateAmPmLabelStates(mInitialHourOfDay < 12 ? AM : PM);
}
mRadialTimePickerView.initialize(mInitialHourOfDay, mInitialMinute, mIs24HourView);
setCurrentItemShowing(mRadialTimePickerView.getCurrentItemShowing(), false, true);
mDelegator.invalidate();
} | @Override
public void setIs24HourView(boolean is24HourView) {
if (is24HourView == mIs24HourView) {
return;
}
mIs24HourView = is24HourView;
final int k0 = KeyEvent.KEYCODE_0;
final int k1 = KeyEvent.KEYCODE_1;
final int k2 = KeyEvent.KEYCODE_2;
final int k3 = KeyEvent.KEYCODE_3;
final int k4 = KeyEvent.KEYCODE_4;
final int k5 = KeyEvent.KEYCODE_5;
final int k6 = KeyEvent.KEYCODE_6;
final int k7 = KeyEvent.KEYCODE_7;
final int k8 = KeyEvent.KEYCODE_8;
final int k9 = KeyEvent.KEYCODE_9;
mLegalTimesTree = new Node();
if (mIs24HourView) {
Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
minuteFirstDigit.addChild(minuteSecondDigit);
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit);
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
Node thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
secondDigit = new Node(k6, k7, k8, k9);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
firstDigit = new Node(k2);
mLegalTimesTree.addChild(firstDigit);
secondDigit = new Node(k0, k1, k2, k3);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteFirstDigit);
secondDigit = new Node(k4, k5);
firstDigit.addChild(secondDigit);
secondDigit.addChild(minuteSecondDigit);
firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(minuteFirstDigit);
} else {
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(ampm);
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit);
secondDigit.addChild(ampm);
Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
thirdDigit.addChild(fourthDigit);
fourthDigit.addChild(ampm);
thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
secondDigit = new Node(k3, k4, k5);
firstDigit.addChild(secondDigit);
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(ampm);
secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
thirdDigit.addChild(ampm);
}
int hour;
int currentHour = mRadialTimePickerView.getCurrentHour();
if (mIs24HourView) {
hour = currentHour;
} else {
switch(mRadialTimePickerView.getAmOrPm()) {
case PM:
hour = (currentHour % HOURS_IN_HALF_DAY) + HOURS_IN_HALF_DAY;
case AM:
default:
hour = currentHour % HOURS_IN_HALF_DAY;
}
}
mInitialHourOfDay = hour;
final String bestDateTimePattern = DateFormatUtils.getBestDateTimePattern(mCurrentLocale, (mIs24HourView) ? "Hm" : "hm");
final int lengthPattern = bestDateTimePattern.length();
boolean hourWithTwoDigit = false;
char hourFormat = '\0';
for (int i = 0; i < lengthPattern; i++) {
final char c = bestDateTimePattern.charAt(i);
if (c == 'H' || c == 'h' || c == 'K' || c == 'k') {
hourFormat = c;
if (i + 1 < lengthPattern && c == bestDateTimePattern.charAt(i + 1)) {
hourWithTwoDigit = true;
}
break;
}
}
final String format;
if (hourWithTwoDigit) {
format = "%02d";
} else {
format = "%d";
}
if (mIs24HourView) {
if (hourFormat == 'k' && hour == 0) {
hour = 24;
}
} else {
hour = modulo12(hour, hourFormat == 'K');
}
CharSequence text = String.format(format, hour);
mHourView.setText(text);
if (false) {
tryAnnounceForAccessibility(text, true);
}
if (mIs24HourView) {
mAmPmLayout.setVisibility(View.GONE);
} else {
final String dateTimePattern = DateFormatUtils.getBestDateTimePattern(mCurrentLocale, "hm");
final boolean isAmPmAtStart = dateTimePattern.startsWith("a");
setAmPmAtStart(isAmPmAtStart);
updateAmPmLabelStates(mInitialHourOfDay < 12 ? AM : PM);
}
<DeepExtract>
mRadialTimePickerView.initialize(mInitialHourOfDay, mInitialMinute, mIs24HourView);
setCurrentItemShowing(mRadialTimePickerView.getCurrentItemShowing(), false, true);
</DeepExtract>
mDelegator.invalidate();
} | AppCompat-Extension-Library | positive | 2,077 |
@Override
public void run() {
if (Build.VERSION.SDK_INT < 26)
return;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, DocumentFile.fromTreeUri(GrantActivity.this, Uri.parse(Global.URI_DATA)).getUri());
startActivityForResult(intent, 0);
ToastManager.showToast(GrantActivity.this, getResources().getString(R.string.dialog_grant_toast_data), Toast.LENGTH_SHORT);
} | @Override
public void run() {
<DeepExtract>
if (Build.VERSION.SDK_INT < 26)
return;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, DocumentFile.fromTreeUri(GrantActivity.this, Uri.parse(Global.URI_DATA)).getUri());
startActivityForResult(intent, 0);
</DeepExtract>
ToastManager.showToast(GrantActivity.this, getResources().getString(R.string.dialog_grant_toast_data), Toast.LENGTH_SHORT);
} | apkextractor | positive | 2,078 |
private int serialize(final int activePathIndex) {
if (this.serialized.length < size + ARC_SIZE * MAX_LABELS) {
serialized = Arrays.copyOf(serialized, serialized.length + bufferGrowthSize);
serializationBufferReallocations++;
}
final int newState = size;
final int start = activePath[activePathIndex];
final int len = nextArcOffset[activePathIndex] - start;
System.arraycopy(serialized, start, serialized, newState, len);
size += len;
return newState;
} | private int serialize(final int activePathIndex) {
<DeepExtract>
if (this.serialized.length < size + ARC_SIZE * MAX_LABELS) {
serialized = Arrays.copyOf(serialized, serialized.length + bufferGrowthSize);
serializationBufferReallocations++;
}
</DeepExtract>
final int newState = size;
final int start = activePath[activePathIndex];
final int len = nextArcOffset[activePathIndex] - start;
System.arraycopy(serialized, start, serialized, newState, len);
size += len;
return newState;
} | elasticsearch-plugin-bundle | positive | 2,079 |
@Override
public void _main(String[] args) throws IOException {
new MH().run(args, null);
} | @Override
public void _main(String[] args) throws IOException {
<DeepExtract>
new MH().run(args, null);
</DeepExtract>
} | iNotes-exporter | positive | 2,080 |
@Override
public void onClick(View v) {
int value;
try {
value = forceInRange(minValue, maxValue, inputToInt(customValueView.getText().toString()));
} catch (Exception e) {
Log.e(TAG, "worng input(non-integer): " + customValueView.getText().toString());
notifyWrongInput();
return;
}
if (persistValueListener != null) {
persistValueListener.persistInt(value);
dialog.dismiss();
}
} | @Override
public void onClick(View v) {
<DeepExtract>
int value;
try {
value = forceInRange(minValue, maxValue, inputToInt(customValueView.getText().toString()));
} catch (Exception e) {
Log.e(TAG, "worng input(non-integer): " + customValueView.getText().toString());
notifyWrongInput();
return;
}
if (persistValueListener != null) {
persistValueListener.persistInt(value);
dialog.dismiss();
}
</DeepExtract>
} | EucWorldAndroid | positive | 2,081 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.